2

I'm trying to send a associative array via AJAX $.post to php. Here's my code:

var request = {
        action: "add",
        requestor: req_id,
        ...
    }

    var reqDetails = $("#request_details").val();

    switch(reqDetails){
        case 1: 
            request[note] = $("#note").val();
            break;

        ...

    }

    if(oldRequest()){
        request[previousID] = $("old_id").val();
    }

    $('#req_button').toggleClass('active');
    $.post("scripts/add_request.php", {
        request_arr: JSON.stringify(request)
        }, function(data){
            console.log(data);
            $('#req_button').toggleClass('active');
    }, 'json');

And i'm simply trying to read the received data in my php script:

echo json_decode($_POST["request_arr"]);

But it's not working. I'm a newbie to js, I can't figure out what I'm doing wrong.

Zaxter
  • 2,939
  • 3
  • 31
  • 48
  • `data: JSON.stringify(request)` – Dan Smith Apr 01 '15 at 12:56
  • 1
    The undefined variables `note` and `previousID` should probably be strings `"note"` and `"previousID"` – James Apr 01 '15 at 12:59
  • Thanks for pointing that @James. I've changed the code now, but I still get the same problem. I even tried Deeban's answer, but It isn't working for me. – Zaxter Apr 01 '15 at 16:49

2 Answers2

3

Check below link for your reference

Sending an array to php from JavaScript/jQuery

Step 1

$.ajax({
    type: "POST",
    url: "parse_array.php",
    data:{ array : JSON.stringify(array) },
    dataType: "json",
    success: function(data) {
        alert(data.reply);
    }
});

Step 2

You php file looks like this:

<?php 



  $array = json_decode($_POST['array']);
    print_r($array); //for debugging purposes only

     $response = array();
     if(isset($array[$blah])) 
        $response['reply']="Success";
    else 
        $response['reply']="Failure";

   echo json_encode($response);

Step 3

The success function

success: function(data) {
        console.log(data.reply);
        alert(data.reply);
    }
Community
  • 1
  • 1
Deeban Babu
  • 729
  • 1
  • 15
  • 49
  • I tried this, but I'm getting "POST http://server/add_request.php 500 (Internal Server Error)" . Its at the line "$array = json_decode($_POST['array']);" – Zaxter Apr 01 '15 at 16:47
0

You are already using "json" as dataType, so you shouldn't apply 'stringify' operation on your data.

Instead of request_arr: JSON.stringify(request), can you try request_arr: request directly?

Apul Gupta
  • 3,044
  • 3
  • 22
  • 30
Tuğca Eker
  • 1,493
  • 13
  • 20