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.

3
  • data: JSON.stringify(request) Commented Apr 1, 2015 at 12:56
  • 1
    The undefined variables note and previousID should probably be strings "note" and "previousID" Commented Apr 1, 2015 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. Commented Apr 1, 2015 at 16:49

2 Answers 2

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);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

I tried this, but I'm getting "POST server/add_request.php 500 (Internal Server Error)" . Its at the line "$array = json_decode($_POST['array']);"
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?

1 Comment

Can you edit your PHP Code with " print_r($_POST);" and share result?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.