how to receive ajax response as array in php [duplicate] - php

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.

Related

json_decode returns NULL, json_last_error throws 0

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']);

Javascript post to PHP and get back an array?

So i have this piece of javascript, it posts to foo.php with value val, gets back data, empties the container and call function graph which will fill the container with a new chart.
$.post("foo.php", {val: val}, function(data){
if(data.length >0) {
$('#container').html('');
graph(data);
}
});
in foo.php, how do I make it pass back an array instead of string? at the moment I just have an echo in foo.php that echos the data delimited by a comma, ie: 1,2,3,4,5. then in the graph function I have a split(',' data) that creates an array for later use.
I mean, all this works fine, I'm just wondering if I can avoid the split step and have foo.php return an array directly.
thanks!
That's what json_encode is for:
echo json_encode( $array );
Just remember to set JSON headers, so that jQuery will know to parse the returned data as JSON. If you don't, you'll have to specify that in your jQuery AJAX call as follows:
$.post("foo.php", {val: val}, function(data){
if (data.length > 0) {
$('#container').html('');
graph(data);
}
}, 'json'); // <-- Here you're specifying that it'll return JSON
json_encode your array in PHP and jquery can easily parse your JSON encoded data.

Traverse JSON data with jQuery

I can't figure out how to get a bunch of MySQL rows into a JSON data structure and iterate each of the row fields in java script.
Here is my query in codeigniter
function get_search_results() {
//$this->db->like('title', $searchText);
//$this->db->orderby('title');
$query = $this->db->get('movies');
if($query->num_rows() > 0) {
foreach($query->result() as $movie) {
$movies[] = $movie->title;
}
}
return $movies;
}
Encode array for json
$rows= $this->movie_model->get_search_results();
echo json_encode($rows);
My jQuery AJAX request,
$.ajax({
type: "GET",
url: "publishlinks/search_movies",
data: searchString,
...
This is how I've been trying to traverse rows in the java script. It is iterating over every character: 1 t 2 h 3 e 4 g ... 7 e
I need this: 1 the game 2 lost 3 you
success:
function(result) {
$.each(result, function(key, val) {
alert(key + ' ' + val);
})
//alert(result);
}
It looks like it is treating the result as a string instead of parsed JSON, hence iterating over it as if it was a string. This could mean that it isn't returning a clean JSON encoded string in the response, so I'd check the response to make sure it is valid JSON. jQuery is supposed to intelligently guess the content type and parse accordingly.
You could also try the dataType: "json" option on the ajax request to force it to be parsed as JSON instead of letting jQuery guess.
Use the dataType property of $.ajax
$.ajax documentation
dataType
"The type of data that you're expecting back from the
server."
Use firebug to find the type of the response variable. In your case the response is string but it should be Array (or Object?)
If you don't want jQuery to automatically eval the json then live it as it is and in the success function add the following:
var parsed = $.parseJson(response);
Here is the documentation of the parseJson method: parseJson
I think you problem is you don't fetch actual json but simple string response....
use $.getJSON or specify dataType as json in your jquery ajax request!
Do you return a JSON header with your PHP ?
header('Content-type: application/json');
Else try
result = JSON.decode(result);
before your "each" loop
Be sure to return proper content-type from your server side. For JSON that would be application/json.
$rows = $this->movie_model->get_search_results();
header('Content-type: application/json');
echo json_encode($rows);
Also add dataType: "json" to your jQuery request, just as beefsack said:
$.ajax({
type: "GET",
url: "publishlinks/search_movies",
data: searchString,
dataType: "json",
...
dataType: "json",
success:function(data){
var obj=$.parseJSON(data);
data=obj.data;
$.each(data,function(){
//json data
})
}

Pass PHP Variable to AJAX Variable

After a completed calculation form where the total is loaded in via PHP we have 4 pieces of data (variables left over with PHP)
$totalprice;
$totalduration;
$totaldives;
$totalhire;
At the moment the PHP ends with echo for each of these. The ajax then collects them like this.
success: function() {
$('#results').html();
The problem is that echos all results.
I would like to send the $totalprice to $('#resultsprice').html(); the $totalduration to $('#resultsduration').html(); etc etc...
Any ideas how to do that?
Marvellous
You could return a JSON string from PHP:
echo json_encode( array('totalprice'=>$totalprice, 'totalduration'=>$totalduration, 'totaldives'=>$totaldives, 'totalhire'=>$totalhire));
Then, change your jquery ajax call to set the response to json:
$.ajax({
url: your_url,
dataType: 'json',
success: function (data) {
$('#resultsprice').html(data.totalprice);
$('#resultsduration').html(data.totalduration);
});
Use the php function json_encode(). First in php create an array with the 4 variables. Json encode the array and echo the result. Then in jQuery use jQuery.parseJSON() to parse the json code to javascript variables. Here's an example:
PHP:
$data = array('var1' => 'value1', 'var2' => 'value2', 'var3' => 'value3', 'var4' => 'value14');
echo json_encode($data);
jQuery:
success: function(data) {
data = jQuery.parseJSON(data);
}
Use JSON as data format.
In PHP, you can use json_encode to create a JSON string. compact is an easy way to create an associative array from variables:
echo json_encode(compact('totalprice', 'totalduration', 'totaldives', 'totalhire'));
// compact produces array('totalprice' => <value-of-totalprice>, ...)
// json_encode produces '{"totalprice": <value>, ...}'
In jQuery, set the dataType option to json and the argument passed to the success callback will be a JavaScript object:
$.ajax({
// ... all other options ...
dataType: 'json',
success: function(data) {
// use .html() only for HTML data
$('#resultsprice').text(data.totalprice);
$('#resultsduration').text(data.totalduration);
//...
}
});
What is actually returned from the AJAX call? If it's a JSON object containing the various values, you can set each one to various HTML elements. Something like this:
success: function(data) {
$('#resultsprice').html(data.TotalPrice);
$('#resultsduration').html(data.TotalDuration);
// etc.
}

How to use JSON with Jquery?

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.

Categories