How can print date and age (in following array) separate by $.ajax()?
php:
$array = array(
'date' => 2011/9/14,
'age' => 48,
);
return $array // this send for ajax call in the jQuery
I want this output by jquery:2011/9/14 & 48
Use $.ajax Methods and setting parameter dataType to JSON for receive data type JSON from PHP file.
Jquery Code:
$.ajax({
url: "getdata.php",
type: "post",
dataType: "json",
success: function(data){
alert("Date:" + data.date + "\n" + "Age:" + data.age);
}
});
if your array data contains string make sure it's closured with quote then make data type JSON with json_encode() function.
PHP Code (getdata.php):
$array= array('date'=>'2011/9/14','age'=>48);
echo json_encode($array);
Echo the encoded array in php page say mypage.php
using
echo json_encode($array);
And use jQuery.getJson in the client side
$.getJSON('mypage.php', function(data) {
alert(data['date']);
alert(data['age']);
});
You need to encode the array as a valid JSON string using the PHP function json_encode. You can then use the jQuery function $.parseJSON to convert it into a JavaScript object. From there you'll be able to do whatever you want with it.
If you do this, you'll end up with an object like:
ajaxDataObj = {
date: '2011/9/14',
age: 48
}
**Edit**
Please see stratton's comment below about using $.getJSON for a more compact solution.
Also, Ben Everard's comment on your original post about using echo rather than return is critical.
You can't just return $array to the browser, the result will be "Array" as string.
YOu have to use return json_encode($array); which returns a string that could be parsed by browser.
If the server-client communication is working alright, then you should do something like this on the client side:
$.ajax({
//configuration...
'success':function(response){
var dateAge = response.date+' & '+response.age;
//put or append the string somewhere.
}
});
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.
returns
I have a php script which is called by ajax and i do some operation on mysql in this file and now i want to return the result stored in php array to ajax call. So how it can be possible.
You should use it.
echo json_encode($array);
Try this:
Use json for that. Read this for more details.
http://php.net/json_encode
JSON is used especially for this purpose.
--
Thanks
If you want to pass PHP Array to an AJAX call convert it as JSON and pass it.
The below is an example
<?php
$arr = array('a' => 10, 'b' => 23, 'c' => 32, 'd' => 42, 'e' => 52);
echo json_encode($arr);
?>
Anything you print in the php script will be 'returned' to the ajax call and caught in the success callback.
$.ajax({
type: "POST",
url: url,
data: data,
success: function(response){
alert(response); // Will print whatever the php script 'echos' out.
// or with the php code below as the script you call, you can use:
if(response.result) {
alert(response.data); // For the data in 'data' to be printed.
// Where response.data is your array:
for(var i=0;i<response.data.length;i++){
console.log(response.data[i]);
}
} else {
console.log(response.error);
}
},
});
Edit:
As other states in the other answers, json is perfect to return from a php script to an ajax callback, cause JavaScript and PHP both handles this very well.
<?php
// I like to return an associative array,
// which in the javascript part of the code can be used as a object.
// I always include a 'result' boolean value which will let me know on the js
// side if the request was successfully done or not, and if false,
// i usually include a 'error' property with a error message.
$myreturndata = array("result" => true, "data" => $yourArray, "error" => null);
header('Content-Type: application/json');
die(json_encode($myreturndata));
In your ajax call you can specify the return datatype like this
$.ajax({
url : url,
data : data,
dataType : 'json',
success : function(data){
console.log(data);
}
})
In you php script you can print the json encoded string like this
print_r(json_enocde(array()));
A useful example on top of the other answers. Splitting each array value into javascript variables.
Improved with useful advice :)
PHP
echo json_encode($array);
jQuery.ajax in your success function
// pass each value to variables (this example array looks like this: [100,200,300])
var variableOne = response[0]; // This variable will = 100
var variableTwo = response[1]; // This variable will = 200
var variableThree = response[2]; // This variable will = 300
// Now you can easily use each individual value.
alert(variableOne);
Hi I'm working on passing back an array from php to javascript. I learned online that I should use json_encode on the array when passing it back but now that i have it in the ajax i'm unsure how i can loop over it because doing things like response[0] gives me [ and response[1] gives me " although when writing the entire thing to the document using innerHTML i can see it looks like an array but using a for loop gives me each letter like i stated above with the response[0] equaling [ rather than the first entry. What am i doing wrong? Any help is greatly appreciated!
PHP
<?PHP
$link = mysql_connect('localhost', 'root', 'root');
mysql_select_db("Colleges");
$result = mysql_query("SELECT * FROM `Colleges` ORDER BY School");
$schools = array();
while ($row = mysql_fetch_array($result)) {
array_push($schools, $row['School']);
}
mysql_close();
die(json_encode($schools));
?>
Ajax
<script type="text/javascript">
function schools(){
$.ajax({
url: "Schools.php",
type: "POST",
success: function (response) {
//Loop over response
}
});
}
</script>
You should decode your JSON response (which is a string actually) to be able to work with it as with an object:
var respObj = JSON.parse(response);
The other way around is noticing jQuery that JSON will be supplied by the server (with either dataType: 'json' ajax parameter or Content-Type: application/json response header).
In the object you pass to the ajax method, you should try to add dataType: 'json' in order to specify that the result is json, or you could specify it in your php script calling header('Content-type: application/json'); before the call to die();
Doing so will result in your response being the object you expect instead of a string.
Finally, you could leave it as is, and call in your success callback response = $.parseJSON(response); which will take the response string and turn it into an object, see http://api.jquery.com/jQuery.parseJSON/
Use Following if it helps
res=jQuery.parseJSON(response);
for(i=0;i<res.length;i++)
{
alert(res[i].propertyname);
}
here property name implies to the keys on json .In your case it can be 'School' or just a number i or value can also be just res[i]
Javascript
for ( variable in response ) {
alert(results[variable]);
}
JQuery
$.each(response, function(ind, val){
alert("index:" + ind + ". value:" + val);
});
I'm trying to communicate AJAX, JSON to PHP and then PHP returns some data and I'm trying to parse it with Javascrpt.
From the php, server I return,
echo json_encode($data);
// it outputs ["123","something","and more something"]
and then in client-side,
success : function(data){
//I want the data as following
// data[0] = 123
// data[1] = something
// data[3] = and more something
}
But, it gives as;
data[0] = [
data[1] = "
data[2] = 1
It is reading each character but I want strings from the array, not individual characters. What is happening here? Thanks in advance, I am new to Javascript and JSON, AJAX.
JSON.parse(data) should do the trick.
Set the dataType property of the ajax call to json. Then jQuery will automatically convert your response to object representation.
$.ajax({
url : ...,
data : ...,
dataType : "json",
success : function(json) {
console.log(json);
}
});
Another option is to set headers in PHP so that JQuery understand that you send a JSON object.
header("Content-Type: application/json");
echo json_encode($data);
Check this one... Should Work
success : function(data){
var result = data;
result=result.replace("[","");
result=result.replace("]","");
var arr = new Array();
arr=result.split(",")
alert(arr[0]); //123
alert(arr[1]); //something
alert(arr[2]); //......
}
You did not shown function in which you parse data. But you shoud use
JSON.parse
and if broser does not support JSON then use json polyfill from https://github.com/douglascrockford/JSON-js
dataArray = JSON.parse(dataFomXHR);
I'm not sure if this is what you want but why don't you want php to return it in this format:
{'item1':'123','item2':'something','item3':'and more something'}
Well to achieve this, you'll need to make sure the array you json_encode() is associative.
It should be in the form below
array("item1"=>123,"item2"=>"something","item3"=>"more something");
You could even go ahead to do a stripslashes() in the event that some of the values in the array could be URLs
You could then do a JSON.parse() on the JSON string and access the values
Hop this helps!
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.
}