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.
asked Apr 1, 2015 at 12:54
Zaxter
3,0553 gold badges35 silver badges50 bronze badges
2 Answers 2
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);
}
answered Apr 1, 2015 at 12:58
Deeban Babu
7291 gold badge15 silver badges51 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Zaxter
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']);"
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,0344 gold badges24 silver badges30 bronze badges
answered Apr 1, 2015 at 12:58
Tuğca Eker
1,49313 silver badges20 bronze badges
1 Comment
Tuğca Eker
Can you edit your PHP Code with " print_r($_POST);" and share result?
default
data: JSON.stringify(request)noteandpreviousIDshould probably be strings"note"and"previousID"