I am trying to get a php file setup to return the results of a MySQL database query from a jQuery AJAX call. The returned results will be an array. I have a very basic start where I am just getting some basic data back and forth to and from the php file, but am stuck with some basic syntax issues:
The PHP code:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr);
The jQuery code:
$.post("dbFile.php", str, function(theResponse){
alert('the response: ' + theResponse);
var obj = $.parseJSON(theResponse);
alert(obj.a);
I can print out obj.a, obj.b, obj.c... no problem. The problem is I will be incrementing a counter as I increment through the MySQL results. So, the array does not use letters, it uses numbers:
$arr[$i] = mysqlresults ... $i++;
So, in the JavaScript/jQuery I have an object (not an array). I can print out obj.a for example, but I can not print out obj.2 (for example). In other words, if I replace the letters with numbers in the php array, I don't know how to print them out in JavaScript/jQuery. Can I change the object that parseJSON returns into an array somehow (so that I can cycle through it)?
Use the array access syntax:
alert(obj[42]);
You can use:
alert(obj['a']);
See this question for more info.
Related
I am trying to add a marker to my gmaps.js map. The long. and lat. values are stored in a database, which I select using a PHP Script.
Once fetched, both of the long. and lat. values are stored in an array, under the variable $data.
I wanted to use json_encode($data); in order to pass the variables, however I would have had to change the header to a json application, I have already echoed some PHP onto the page, therefore this is unfeasable.
I have now tried echoing the json_encode into the jQuery function using an $.each loop, however it has been unsuccessful, as not every entry retrieved by the database will have a marker.
What is the best solution, to get an ID, long. and lat. value for max 10 records, pass this to a jQuery function to position on a map?
As not all records have markers, youll have to parse the results so that only the required data gets passed to your js function. I'd create a php array and add the marker I'd, lat,long etc... Under the same key:
$markersarray = array ()
foreach($records as $record){
if($record['lat'] != ““){
$markersarray[] = array(
'id'=>$record['id'],
'lat'=>$record['lat'],
'long'=>$record['long']
);
}
}
$markersjson = json_encode($markersarray);
Then you could use a hidden input to store the encoded json string which then could be passed into your js.
<input id="markersjson" type="hidden" value="<?php echo $markersjson; ?>"/>
in your js function
var markersdata = $('#markersjson').val();
You may need to parse this value to an object
var obj = jQuery.parseJSON(markersdata);
then use a $.each to loop through your obj
I am using a jQuery plugin of nestable forms and storing the order of these in a database using serialize (achieved through JS). Once I retrieve this data from the database I need to be able to unserialize it so that each piece of data can be used.
An example of the data serialized and stored is
[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]
The number of ID's stored in each serialized data varies and the JS plugin adds the [ and ] brackets around the serialization.
I have used http://www.unserialize.com/ to test an unserialization of the data and it proves successful using print_r. I have tried replicating this with the following code:
<?php
print_r(unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]'));
?>
but I get an error. I am guessing that I need to use something similar to strip_tags to remove the brackets, but am unsure. The error given is as follows
Notice: unserialize(): Error at offset 0 of 70 bytes
Once I have the unserialized data I need to be able to use each ID as a variable and I am assuming to do so I need to do something as:
<?php
$array = unserialize('[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]');
foreach($array as $key => $val)
{
// Do something here, use each individial ID however
// e.g database insert using $val['id']; to get H592736029375 then K235098273598 and finally B039571208517
}
?>
Is anyone able to offer any help as to how to strip the serialized data correctly to have the ID's ready in an array to then be used in the foreach function?
Much appreciated.
PHP's serialize() and unserialize() functions are PHP specific, not for communicating with other languages.
It looks like your JS serialize function is actually generating JSON though, so on the PHP side, use json_decode() rather than unserialize.
Here's a fiddle
$data = '[{"id":"H592736029375"},{"id":"K235098273598"},{"id":"B039571208517"}]';
$array = json_decode($data, true);
foreach($array as $index=>$data){
echo "$index) {$data['id']}\n";
}
Outputs:
0) H592736029375
1) K235098273598
2) B039571208517
An Ajax call is computing me a multidimensional PHP array '$tree', after this call is made I would like to retrieve this array as a JSON.
My PHP page is only printing the Array:
print_r(json_encode($tree));
Here the success part of my ajax call:
success: function(data, textStatus, jqXHR) {
var myObject = JSON.parse(data);
alert(myObject);
}
Unfortunately the alert box is not triggered.
Also, I noticed that when I'm reaching my PHP page through a web browser:
print_r(json_encode($tree));
isn't displaying anything, while:
print_r($tree);
Is printing my multidimensional Array
echo json_encode($tree);
exit;
This is the ideal way to send JSON back to browser.
Also check that you do not have any special characters in your array otherwise you will have to use BITMASKs in json_encode function.
Also, All string data must be UTF-8 encoded, so you may want to correct the encoding of your data.
Further reading: http://php.net/manual/en/function.json-encode.php
As others already said, the correct method to output a JSON from PHP is via the json_encode function.
echo json_encode($tree);
You should probably check the encode of the Array data; if you have any string they must be encoded in UTF-8. I suggest you to loop through the $tree Array and to force the encode via the utf8_encode function (you can find PHP docs here).
If your Array has a depth of 2 levels you can try something like this, or some kind of array walk loop.
for (i = 0; i < count($tree); i++)
{
for (j = 0; j < count($tree[$i]; j++)
{
utf8_encode($tree[$i][$j]);
}
}
You probably just need to encode strings, so you should reduce the amount of data to encode if you can (i.e. you know that only 2 indexes in the whole array could be strings, or maybe could contain characters that need to be encoded).
Never forget the header!
<?php
header("Content-Type: application/json");
echo json_encode($tree);
First of all you need to test if the function json_encode exists.
if (function_exists('json_encode')) print 'json_encode working';
else print 'json_encode not working';
If it doesn't, you need to enable it, see here https://stackoverflow.com/a/26166916/5043552
Last, use print json_encode($tree) instead of print_r(json_encode($tree)).
I would like to send an integer array with 30 values Integer[] temp = new Integer[30] over HTTP (POST) to PHP an get the data in PHP again. How can I do that? I know how to send a single value, like a string, but not how to send an array.
One way is to serialize the array in the way the php serialize command does it.
After receiving the string value(by the method you currently use), you can use the unserialize command to get the array in your php code.
Here is a litle php example to demonstrate the workflow.
$arr = array(1,2,3,4,5,6);
$stringArr = serialize($arr);
echo $stringArr;
echo "<br/>";
$arr2 = unserialize($stringArr);
if ($arr === $arr2)
{
echo "arrays are equal";
}
The output of the script is:
a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}
arrays are equal
The main difficulty is to construct the resulting string for complex structures (in your case, it is pretty straight forward for an array of integers).
This fact results in the second approach.
One can use a serialization API or another notation than used by the php example.
As stated by the others, JSON is one of the widespread notations.
PHP also provides a possibility to serialize and unserialize json objects.
Simply use json_decode and look at the example in the manual.
Im running a javascript code which reads values from different XML files and it generates a multidimentional array based on those values. Now I need to pass this array to a PHP page. I tried different but it always pass the arrray as string not as an array.
Anyone has an idea :( ... and thank you very much
What Caleb said.
Use this and JSON encode your JS array to a string, send it over to PHP and use json_decode to decode it into a PHP array.
You need a JSON encoder/decoder to do that. Prototype has it implemented by default and with jQuery you can use jQuery-JSON
For example if you use Prototype as your JS library then you can convert your array into a string like that:
var example_multi_dim_arr = {"a":[1,2,3], "b": [4,5,6]};
var string_to_be_sent_to_server = Object.toJSON(example_multi_dim_arr);
And in the PHP side (assuming that the JSON string is passed to the script as a POST variable)
$multi_dim_arr = json_decode($_POST["variable_with_json"], true);
The last true field in json_decode indicates that the output should be in the form of an array ($multi_dim_arr["a"]) and not as an object ($multi_dim_arr->a).
NB! the function json_decode is not natively available in PHP 4, you should find a corresponding JSON class if you are using older versions of PHP. In PHP 5 everything should work fine.