How to use JSON with Jquery? - 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

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

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.

Splitting a JSON Array with JQuery that has been returned by PHP

I am new to JQuery and the whole JQuery to PHP back to JQuery process.
So i have a simple ajax JQuery script:
$.ajax({
type: "POST",
url: "includes/calc.php",
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data);
$("input#hiddenprice").val(data);
$('#'+itemprice).html("€"+data);
}
})
This goes to a PHP script and then I return a value, using a simple echo
echo $newprice;
The success function above uses this as 'data'. This all works and is fine.
But what if I want to return more than one value.
I think I can used json_encode();
As I understand it something like:
$dataset = array($var1, var2, var3);
echo json_encode($dataset);
But say I have two values, how do i put them both into the JSON and then how do I split them on the other end.
So say 'data' is an array, how do I tell JQuery to split it?
Sorry if this is simple
If you specify the dataType option for .ajax() as json, jQuery will automatically parse the JSON string returned by the call into an appropriate javascript object/array.
So your call might look like this:
$.ajax({
type: "POST",
url: "includes/calc.php",
dataType: "json",
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data);
$("input#hiddenprice").val(data);
$('#'+itemprice).html("€"+data);
}
})
Now, let's say the response from your PHP script is a JSON string representing an object like this:
{"key1":"value1","key2":"value2"}
In your success handler you can simply access this as an object like this:
success: function(data){
alert(data.key1);
alert(data.key2);
}
Or, if the returned JSON string represents an array like this:
["value1","value2"]
Then you can access the array values in the success handler like this:
success: function(data){
alert(data[0]);
alert(data[1]);
}
If you do not want to add the dataType option, you can also opt to manually parse the returned JSON string into an object/array like this:
success: function(data){
var dataObj = JSON.parse(data);
alert(dataObj.key1);
alert(dataObj.key2);
}
$.ajax({
type: "POST",
url: "includes/calc.php",
datatype : 'json',
data: {
'var1':var1,
'var2':var2,
},
success: function(data){
alert(data.firstvalue);
alert(data.secondvalue);
}
})
please look at that datatype. now the respose need to be json.
In your php user json_encode instead of echo.
$firstvalue = 'your first value';
$secondvalue = 'your second value';
echo json_encode(array('firstvalue' => $firstvalue,'secondvalue' => $secondvalue));
There are many ways to organize data in a JSON object. The simplest is to return a linear array of strings or numbers. Use http://jsonlint.com/ to test your data to see if it's valid JSON, or just feed a PHP array (linear or associative) into json_encode.
If data is a JSON linear array, you can treat it like any other JavaScript array in your success callback:
var first = data[0]; // first element
var second = data[1]; // second element
implode your php variables with a symbol or any custom data
like
$var[0] = '1st variable';
$var[1] = '2nd variable';
$var[2] = '3rd variable';
echo implode('_SPLIT_',$var);
Now in jquery success function
split the response with 'SPLIT'
as
var response = data.responseText.split('_SPLIT_');
var variable1 = response[0];
var variable2 = response[1];
var variable3 = response[2];
and assign as your wish

PHP array to JavaScript using jQuery AJAX

I want to manipulate a PHParray in javascript. This is the code i'm using.
Array.php
<?php
$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler";
?>
fx_funciones.js
/*Pre-sentences*/
var js_array=new Array();
$.ajax({
type: "POST",
url: "array.php",
success: function(response) {
js_array=response
}
});
This is what I want to do but it's not working.
I think , the answer for above question is already addressed in below link. please check them out.
Get data from php array - AJAX - jQuery
I hope it will help you
Try this:
<?php
$sentido[1]="ver";
$sentido[2]="tocar";
$sentido[3]="oir";
$sentido[4]="gustar";
$sentido[5]="oler";
echo json_encode($sentido);
And:
$.getJSON('array.php', function(sentido) {
console.log(sentido);
});
You'll need to return the array from your PHP code as JSON, using the json_encode function. Then, in your jQuery code, specify a json dataType so that it's implicitly converted and passed to the callback function as an array:
var js_array=new Array();
$.ajax({
type: "POST",
url: "array.php",
success: function(response) {
js_array=response
},
dataType: 'json'
});
Use the standard JSON notation. It serializes objects and arrays. Then print it, fetch it on the client and parse it.
On the server:
echo json_encode($sentido);
For more on PHP's json_encode: http://php.net/manual/de/function.json-encode.php
On the client, this is specially easy if you use the jQuery function for ajax that expect JSON-encoded objects, and parses them for you:
$.getJSON('address/to/your/php/file.php', function(sentidos) {
alert(sentidos[0]); // It will alert "ver"
alert(sentidos[1]); // It will alert "tocar"
});
It uses GET but this most probably what you need.
For more on jQuery's $.getJSON: http://api.jquery.com/jQuery.getJSON/

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.
}

Categories