I have the below code running to send data as a JSON object
var jdata = JSON.stringify(grid.serialize());
$.ajax({
'type': 'POST',
'url': 'print.php',
'data': jdata, //assuming you have the JSON library linked.
'contentType': "application/json",
'success': function (data) {
alert(data);
},
'error': function (x, y, z) {
alert(x.responseText);
// x.responseText should have what's wrong
}
});
alert(JSON.stringify(grid.serialize()));
Currenty the alert after the ajax function prints
[{"id":"1","col":"1","row":"1","size_y":"1","size_x":"1"},{"id":"2","col":"2","row":"1","size_y":"1","size_x":"1"}]
On the receiving page I am using <?php print_r($_POST) ?> to see what the page is being sent and it keeps outputting
Array
(
)
I must be missing something simple but have been unable to figure out what. Maybe a fresh set of eyes will see a simple mistake I have made.
I think $_POST is only populated if you send the data encoded as x-www-form-urlencoded. So, just assign the JSON string to a key (jQuery takes care of encoding it properly):
'data': {data: jdata}
and remove the 'contentType': "application/json" part.
Then you get the data in PHP with:
$data = json_decode($_POST['data'], true);
Alternatively, get the raw body of the request in PHP and process it: How to retrieve Request Payload
If you are sending JSON to the server, on the back-end grab your JSON using:
json_decode(file_get_contents('php://input'));
It won't be in the $_POST super global.
Related
I'm working at an app which would make a POST ajax request to a PHP script on my server. The script would query the database and return a row of records, as an array. (One array for each row, containing elements such as id, title, etc). I then want to use json_encode() to encode this array, and pass it back to the javascript which will use it to display the records.
1) How can I return the JSON encoded string to the javascript?
2) How will the javascript loop through the rows and access their fields?
To get JSON with jQuery, just use jQuery.getJSON(). Alternatively, you can use any other AJAX tool and then just eval() the json to get a javascript object.
To loop through an array, I usually use jQuery.each():
var recordList = yourMethodToGetRecordListWithAjax();
jQuery.each(recordList, function()
{
alert(this.Name); // For example
});
1) in the php script:
$return["foo"] = "bar";
$return["blah"] = "bleg";
print json_encode($return);
2) in the javascript:
$.ajax({
type: "POST",
url: URL,
cache: false,
data: values,
dataType: 'json',
success: function(json) {
var foo = json.foo;
if (json.blah == "bleg") {
// do stuff
}
} // end success function
}); // end ajax call
You can return the JSON encoded string to the JS by echoing it with a Content-Type of application/json.
See above answer for the rest.
I'm passing a simple JSON array with 4 words to PHP. I want to store that array in a database after I serialize it. Since it's an Ajax call I can only investigate any echoed values by json_encode and alerting them in AJAX success function.
Here's my code:
var jsonString = JSON.stringify(ans);
//if I alert jsonString - it shows the proper array
$.ajax({
type: "POST",
url: "script.php",
data: jsonString,
cache: false,
success: function(data){
alert(data);
},
error: function(){
alert("error");
}
});
That's what I do in PHP with the array:
$answerAr = json_decode($_POST['data']);
$answers = serialize($answerAr);
If I echo the json_encode($answerAr) it alerts NULL in Ajax and $answers turns into 'N;'
Json_last_error returns 0.
If you're posting data directly to PHP, you'll have to use php://input and parse that; data given in JSON isn't form data, and wont auto-populate the request superglobals ($_GET, $_POST).
$data = json_decode(file_get_contents("php://input"));
Most frameworks do this transparently for you and populate a request object with data in it. You should probably check if the request sends JSON data in the body via headers (Content-Type, Accept: application/json, etc)
Alternatively, you can change your AJAX call to give it an array key:
$.ajax({
data: {data: jsonString},
// etc
});
Which will then be accessible as $_POST["data"]
Change your ajax data attribute to like this and try
data: {json: jsonString}
and in the php script you can access it by
$answerAr = json_decode($_POST['json']);
Hello I have a problem with my ajax request in jquery.
When I use my get request without sending any data the response is as expected, I receive my array and can access the values:
$.get(
loadUrl,
function(data) {
useReturnData(data);
},
"json"
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
This works as expected and I recieve my value of "528" being my leftPlayer[4] value.
But when I change my request to send a piece of data to php in the request like so:
$.get(
loadUrl,
{ type: "left" })
.done(function(data) {
useReturnData(data);
},
"json"
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
My data received seems to be in string format to javascript.
My alert prints "5" (the 4th character if the array was a string)
When alerting leftPlayer. I find that in the first request in which I send no data the variable is printed as: 355,355,355,355,528,etc...
Whereas in the second request in which I DO send data it prints as:
[355,355,355,355,528,etc...]
Notice the []. It isn't recognised as an array.
The php file it accesses has absolutely no changes in each request, as I am testing at the moment. The data sent isn't even used in the php file at the moment.
Any ideas where I'm going wrong?
I've fixed my problem.
Like what "nnnnnn" said in his comment I'm passing my "json" parameter to the .done() function instead of the $.get() function.
I couldn't seem to get it to correctly view it as JSON though so I used the easiest method:
$.getJSON(
loadUrl,
{ type: "left" },
function(data) {
useReturnData(data);
}
);
function useReturnData(data){
leftPlayer = data;
alert(leftPlayer[4]);
};
Using $.getJSON instead does like what it says and expects JSON to be returned as default.
I have the following object that gets created in my javascript application.
poll_data[active_question] = {
'question': $('div.question_wrap textarea').attr('value'),
'answers': [
$('div.answer_wrap input#0').attr('value'),
$('div.answer_wrap input#1').attr('value'),
$('div.answer_wrap input#2').attr('value'),
$('div.answer_wrap input#3').attr('value'),
$('div.answer_wrap input#4').attr('value'),
$('div.answer_wrap input#5').attr('value')
]
};
active_question is set to 'poll', 0, 1, 2, 3, 4, or 5 depending on the question being worked on at the moment. I am trying to post this object to a php script using the following JS code.
$.ajax({
url: '/somewebsite/poll/create?json=show',
type: 'POST',
// dataType: 'json',
data: poll_data,
contentType: 'application/json; charset=utf-8',
success: function(data) {
alert(data);
}
});
My PHP code is very simple.
echo json_encode($_POST); exit;
When I run the script and click the button that triggers the submission of the data, I receive the alert (so the actual ajax code works), but the result from my PHP script is just an empty array. I think that this is an issue with the way the object is constructed, but I am not sure, and have not been able to find a work around.
Thanks in advance.
Okay, a few things:
poll_data is not a valid JSON object. You would have to use poll_data[active_question], which IS a valid JSON object. jQuery should serialize this correctly. Remove the contentType -- I am pretty sure that is for php (not positive) but your code wouldn't work for me until I removed it. Finally, the appending of json=show to the query string doesn't do anything..it will just be ignored.
A couple minor things too: you can use .val() instead of .attr('value'), and have you looked into .serialize() to create your post data for you?
do this on server
$data;
$data->question=$_POST['question']
$data->answer=$_POST['answers']
echo json_encode($data);
do this for ajax request
$.ajax({
url: '/somewebsite/poll/create?json=show',
type:'POST',
//modified data proprty
data:poll_data[active_question],
success: function(data) {
alert(data);
}
});
I send data from javascript to PHP like this:
$.ajax({'url': 'my.php',
'type': 'POST',
'data': JSON.stringify(update_data),
'success': function(response) {
alert(response);
}
});
Using HTTPFOX Firefox plug-in I see the following data in the POST DATA tab:
{"file_id":["1","2","3"],"description":["lala","kuku","wow!"],"tags":[["julia","paper"],["Very nice car"],[]]}
however, if I do in my.php print_r($_POST) I see an empty array. Why is that ? How could I collect the data ?
The data needs to be in the form name=value.
try...
$.ajax({'url': 'my.php',
'type': 'POST',
'data': 'mydata=' + JSON.stringify(update_data),
'success': function(response) {
alert(response);
}
});
Then you should have your json string in $_POST['mydata']
You'll then need to use json_decode to actually get at the individual values in your string.
http://php.net/manual/en/function.json-decode.php
The response you are getting is in JSON format. Use the json_decode function to convert it to array.
print_r(json_decode($_POST['description'], true));
I'd expect your data to be in $HTTP_RAW_POST_DATA. Then json_decode to make sense of it.