basic json_encode and jquery multiple values - php

This is my 3rd jquery script and I'm not sure what I'm doing.
I want to read multiple json values from 3 different queries.
My JSON is returning what I was expecting:
key
1 ["value1"]
2 ["value2"]
max 2101
total 22
I can read the first two values using somethin like this:
ajax(
url: 'api.php, data: "", dataType: 'json', success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
value1 = row[0];
}
How can I read the max value from the JSON? I tried thing like:
$row[max], $row['max'], etc.
I'm reading the values with JavaScript
Thanks

row.max might be what you're looking for.

Try using javascript's eval function in your success handler. It will convert your returned json text into a javascript object which you can then manipulate. Something like:
success: function(data) {
var returned_array = eval(data);
//access values as if it were a regular javascript object
alert(returned_array['max']);
//OR
alert(returned_array.max);
}

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.

how to have access to 2d array elements using JSON.stringify?

I have posted a question about How to alert a php array in ajax success function in this post: How to alert a php array in ajax success function
I got the answer to use alert(JSON.stringify(result[0])); but this will give me access to the first row of the array while i need to have access to each element of each row. imagine that my array is like this now
[0]1>>>>2>>>>>3>>>>>5>>>>>6
[1]1>>>>2>>>>>3>>>>>5>>>>>6
[2]1>>>>2>>>>>3>>>>>5>>>>>6
[3]1>>>>2>>>>>3>>>>>5>>>>>6
[4]1>>>>2>>>>>3>>>>>5>>>>>6
[5]1>>>>2>>>>>3>>>>>5>>>>>6
alert(JSON.stringify(result[0])) will give me only [0]1>>>>2>>>>>3>>>>>5>>>>>6 but I want to alert 5 only, I have tried alert(JSON.stringify(result[0][3])) but no luck.
Could you tell me how to have access to 2d array elements using JSON.stringify? Or is there any other way than JSON.stringify(result[0]
Here is the ajax function :
$.ajax({
type: 'POST',
url: "profile/ajax/getorder.php",
data: {id:gotid},
dataType: 'json',
cache: false,
success: function(result) {
alert(JSON.stringify(result[0]))
},
});
here is the php
$ent = $_POST['id'];
$column = array();
$gtord = mysql_query("SELECT * FROM order WHERE oId = '$ent' ");
while($rowmnu2=mysql_fetch_array($gtord))
{
$column[] = $rowmnu2;
}
echo json_encode($column);
Appreciated.
The json.stringify method simply gets the array in a text format that can be sent to alert. If you are only looking at a single value that isn't an array, you don't need it. Just alert(result[0][3]).
After getting more info:
To access a whole row, use JSON.stringify(result[0]), to look at a specific element use result[0]['user_id']. If you want to use numbers to look at the specific elements, use mysql_fetch_row instead of mysql_fetch_assoc. Hope that helps.

ajax / json output must be an other format

Hi for an jquery map I get the values over ajax. The format for the map must be
var new_sample_data = {"af":"16.63","al":"11.58","dz":"158.97",...};.
I have tested it with var new_sample_data = {"af":16.63,...}; and all works good. But If I take it over jason. It doesn't work. What I must change?
The php testcode:
$sample_data[] = array("de","$de");
echo json_encode($sample_data);
The javascript code:
$.ajax({
type: "POST",
url: '../mail/assets/includes/geodata1.php',
data: {datum1: Date.today().add({days: -29}).toString('yyyy-MM-dd'), datum2: Date.today().toString('yyyy-MM-dd')},
dataType: 'json',
success: function(data)
{
var new_sample_data = data;
In Firebug I see the response is [["de","4"]]. But how I can change it to the format the map need?
You need to create an associative array in PHP:
$sample_data = array("de"=>"$de");
Then encoding it should result in a proper JSON String that can be parsed into a JavaScript Object.
To see the proper content of new_sample_data in JavaScript, use console.dir(new_sample_data);, it will list the object's attributes.
You can access the value of your new attribute this way in JavaScript:
console.log(new_sample_data.de);
Your php array should set the index of de to the variable like such:
$sample_data[] = array("de" => "$de");
That wasy $sample_data["de"] will = "$de";
$sample_data['de'] = $de;
it will work as you expected

Creating a 2-dimensional jQuery array from a 2-dimensional PHP array with AJAX

I am using jQuery, AJAX and PHP to update the contents of a drop down box on an event. My code currently triggers the event and uses AJAX to call a PHP function which goes to the database and gets the records associated with each member of the drop down.
I can currently return this 2-dimensional array (an array of records with an array of columns in each one) back to my jQuery function but I am at a loss as to how to convert the array into something which I can use.
jQuery code to call AJAX:
var element= $('select[name=elementName]');
var data = 'inData=' + element.val();
// Call AJAX to get the info we need to fill the drop downs by passing in the new ID
$.ajax(
{
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
success:
function(outData)
{
// WHAT DO I DO HERE TO CONVERT 'outData' INTO A 2-DIMENSIONAL jQUERY ARRAY??
},
error:
function()
{
}
});
PHP code:
$sqlResults= mysql_query("SELECT data FROM table WHERE id='".$_POST['inData']."'");
$outData = array();
// Fill the data array with the results
while ($outData[]= mysql_fetch_array($sqlResults));
// echo the data to return it for use in the jQuery file
echo $outData;
The code posted is working fine - I just don't know how to read 'outData' in jQuery.
Thanks in advance for any help!!
Have you looked at json_encode?
echo json_encode($outData);
This will convert it into a json object that can be read by jQuery.
your looking for json
//php
echo json_encode($outData);
//javascript
$.ajax({
type: "POST",
url: "ops.php",
data: "op=getInfo&" + data,
dataType: "json",
success: function(outData) {
console.log(outData); //this will be an object just like
//your php associative array
},
error: function() {
}
});
JSON can do the trick, but why not look at it from another angle?
If you're pinging PHP to get updated info, just have PHP output the option values you want in your select box. Then use the HTML return of jQuery AJAX to .html() the result into your select element.
There's a couple of different ways to skin a cat, and I would submit that this much easier approach is going to gain you extra time to do more jQuery wizardry.
jQuery can not read the echo of a PHP array. Use json_encode before you output it:
echo json_encode($outData);
That's a format jQuery actually can parse as the response.

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