Ajax : How to Loop through Huge JSON data - php
I receive the below Json Data in an ajax response... I dont know how to traverse it I wana loop through it and make an array out of it, Which I will gonna be using in the HTML DOM also I wana Cache this data for No More Ajax requests if data is already available...
How Can I do that,
I have Tried to do it with $.each(data, function(key,value){ ---- }). But the problem is looping through the data I wanna put a for Loop and Inside it I wanna Populate some other array or object...
Does that Make any sense, Can we do that?
{"CountryCode":"ABW","Language":"Dutch"}{"CountryCode":"ABW","Language":"English"}{"CountryCode":"ABW","Language":"Papiamento"}{"CountryCode":"ABW","Language":"Spanish"}{"CountryCode":"AFG","Language":"Balochi"}{"CountryCode":"AFG","Language":"Dari"}{"CountryCode":"AFG","Language":"Pashto"}{"CountryCode":"AFG","Language":"Turkmenian"}{"CountryCode":"AFG","Language":"Uzbek"}{"CountryCode":"AGO","Language":"Ambo"}{"CountryCode":"AGO","Language":"Chokwe"}{"CountryCode":"AGO","Language":"Kongo"}{"CountryCode":"AGO","Language":"Luchazi"}{"CountryCode":"AGO","Language":"Luimbe-nganguela"}{"CountryCode":"AGO","Language":"Luvale"}{"CountryCode":"AGO","Language":"Mbundu"}{"CountryCode":"AGO","Language":"Nyaneka-nkhumbi"}{"CountryCode":"AGO","Language":"Ovimbundu"}{"CountryCode":"AIA","Language":"English"}{"CountryCode":"ALB","Language":"Albaniana"}{"CountryCode":"ALB","Language":"Greek"}{"CountryCode":"ALB","Language":"Macedonian"}{"CountryCode":"AND","Language":"Catalan"}{"CountryCode":"AND","Language":"French"}{"CountryCode":"AND","Language":"Portuguese"}{"CountryCode":"AND","Language":"Spanish"}{"CountryCode":"ANT","Language":"Dutch"}{"CountryCode":"ANT","Language":"English"}{"CountryCode":"ANT","Language":"Papiamento"}{"CountryCode":"ARE","Language":"Arabic"}{"CountryCode":"ARE","Language":"Hindi"}{"CountryCode":"ARG","Language":"Indian Languages"}{"CountryCode":"ARG","Language":"Italian"}{"CountryCode":"ARG","Language":"Spanish"}{"CountryCode":"ARM","Language":"Armenian"}{"CountryCode":"ARM","Language":"Azerbaijani"}{"CountryCode":"ASM","Language":"English"}{"CountryCode":"ASM","Language":"Samoan"}{"CountryCode":"ASM","Language":"Tongan"}{"CountryCode":"ATG","Language":"Creole English"}{"CountryCode":"ATG","Language":"English"}{"CountryCode":"AUS","Language":"Arabic"}{"CountryCode":"AUS","Language":"Canton Chinese"}{"CountryCode":"AUS","Language":"English"}{"CountryCode":"AUS","Language":"German"}{"CountryCode":"AUS","Language":"Greek"}{"CountryCode":"AUS","Language":"Italian"}{"CountryCode":"AUS","Language":"Serbo-Croatian"}{"CountryCode":"AUS","Language":"Vietnamese"}{"CountryCode":"AUT","Language":"Czech"}{"CountryCode":"AUT","Language":"German"}{"CountryCode":"AUT","Language":"Hungarian"}{"CountryCode":"AUT","Language":"Polish"}{"CountryCode":"AUT","Language":"Romanian"}{"CountryCode":"AUT","Language":"Serbo-Croatian"}{"CountryCode":"AUT","Language":"Slovene"}{"CountryCode":"AUT","Language":"Turkish"}{"CountryCode":"AZE","Language":"Armenian"}{"CountryCode":"AZE","Language":"Azerbaijani"}{"CountryCode":"AZE","Language":"Lezgian"}{"CountryCode":"AZE","Language":"Russian"}{"CountryCode":"BDI","Language":"French"}{"CountryCode":"BDI","Language":"Kirundi"}{"CountryCode":"BDI","Language":"Swahili"}{"CountryCode":"BEL","Language":"Arabic"}{"CountryCode":"BEL","Language":"Dutch"}{"CountryCode":"BEL","Language":"French"}{"CountryCode":"BEL","Language":"German"}{"CountryCode":"BEL","Language":"Italian"}{"CountryCode":"BEL","Language":"Turkish"}{"CountryCode":"BEN","Language":"Adja"}{"CountryCode":"BEN","Language":"Aizo"}
Your problem can be solved in two steps:
1) convert your json data to a php String
2) iterate over that array:
step 1) convert to array
$arr = json_decode($jsondata);
step 2) iterate over array
arrayRecurssive($arr);
function arrayRecurssive($arr){
foreach($arr as $key=>$val){
if(is_array($val)){
echo "$key\n";
arrayRecurssive($val);
}else{
echo "$key\n";
echo "$val\n";
}
}
}
in my example above im using '\n' as my new line, but that may as well be <br/>. further formatting of the output is left as an exercise for the coder :-)
The json data appears to be badly formatted. It should be:
[{"CountryCode":"ABW","Language":"Dutch"},{"CountryCode":"ABW","Language":"English"},{"CountryCode":"ABW","Language":"Papiamento"},{"CountryCode":"ABW","Language":"Spanish"},{"CountryCode":"AFG","Language":"Balochi"},{"CountryCode":"AFG","Language":"Dari"},{"CountryCode":"AFG","Language":"Pashto"},{"CountryCode":"AFG","Language":"Turkmenian"},{"CountryCode":"AFG","Language":"Uzbek"},{"CountryCode":"AGO","Language":"Ambo"},{"CountryCode":"AGO","Language":"Chokwe"},{"CountryCode":"AGO","Language":"Kongo"},{"CountryCode":"AGO","Language":"Luchazi"},{"CountryCode":"AGO","Language":"Luimbe-nganguela"},{"CountryCode":"AGO","Language":"Luvale"},{"CountryCode":"AGO","Language":"Mbundu"},{"CountryCode":"AGO","Language":"Nyaneka-nkhumbi"},{"CountryCode":"AGO","Language":"Ovimbundu"},{"CountryCode":"AIA","Language":"English"},{"CountryCode":"ALB","Language":"Albaniana"},{"CountryCode":"ALB","Language":"Greek"},{"CountryCode":"ALB","Language":"Macedonian"},{"CountryCode":"AND","Language":"Catalan"},{"CountryCode":"AND","Language":"French"},{"CountryCode":"AND","Language":"Portuguese"},{"CountryCode":"AND","Language":"Spanish"},{"CountryCode":"ANT","Language":"Dutch"},{"CountryCode":"ANT","Language":"English"},{"CountryCode":"ANT","Language":"Papiamento"},{"CountryCode":"ARE","Language":"Arabic"},{"CountryCode":"ARE","Language":"Hindi"},{"CountryCode":"ARG","Language":"Indian Languages"},{"CountryCode":"ARG","Language":"Italian"},{"CountryCode":"ARG","Language":"Spanish"},{"CountryCode":"ARM","Language":"Armenian"},{"CountryCode":"ARM","Language":"Azerbaijani"},{"CountryCode":"ASM","Language":"English"},{"CountryCode":"ASM","Language":"Samoan"},{"CountryCode":"ASM","Language":"Tongan"},{"CountryCode":"ATG","Language":"Creole English"},{"CountryCode":"ATG","Language":"English"},{"CountryCode":"AUS","Language":"Arabic"},{"CountryCode":"AUS","Language":"Canton Chinese"},{"CountryCode":"AUS","Language":"English"},{"CountryCode":"AUS","Language":"German"},{"CountryCode":"AUS","Language":"Greek"},{"CountryCode":"AUS","Language":"Italian"},{"CountryCode":"AUS","Language":"Serbo-Croatian"},{"CountryCode":"AUS","Language":"Vietnamese"},{"CountryCode":"AUT","Language":"Czech"},{"CountryCode":"AUT","Language":"German"},{"CountryCode":"AUT","Language":"Hungarian"},{"CountryCode":"AUT","Language":"Polish"},{"CountryCode":"AUT","Language":"Romanian"},{"CountryCode":"AUT","Language":"Serbo-Croatian"},{"CountryCode":"AUT","Language":"Slovene"},{"CountryCode":"AUT","Language":"Turkish"},{"CountryCode":"AZE","Language":"Armenian"},{"CountryCode":"AZE","Language":"Azerbaijani"},{"CountryCode":"AZE","Language":"Lezgian"},{"CountryCode":"AZE","Language":"Russian"},{"CountryCode":"BDI","Language":"French"},{"CountryCode":"BDI","Language":"Kirundi"},{"CountryCode":"BDI","Language":"Swahili"},{"CountryCode":"BEL","Language":"Arabic"},{"CountryCode":"BEL","Language":"Dutch"},{"CountryCode":"BEL","Language":"French"},{"CountryCode":"BEL","Language":"German"},{"CountryCode":"BEL","Language":"Italian"},{"CountryCode":"BEL","Language":"Turkish"},{"CountryCode":"BEN","Language":"Adja"},{"CountryCode":"BEN","Language":"Aizo"}]
You can then simply assign that to an array. For example:
var countries = $.parseJSON('[{"CountryCode":"ABW","Language":"Dutch"},{"CountryCode":"ABW","Language":"English"},{"CountryCode":"ABW","Language":"Papiamento"},{"CountryCode":"ABW","Language":"Spanish"},{"CountryCode":"AFG","Language":"Balochi"},{"CountryCode":"AFG","Language":"Dari"},{"CountryCode":"AFG","Language":"Pashto"},{"CountryCode":"AFG","Language":"Turkmenian"},{"CountryCode":"AFG","Language":"Uzbek"},{"CountryCode":"AGO","Language":"Ambo"},{"CountryCode":"AGO","Language":"Chokwe"},{"CountryCode":"AGO","Language":"Kongo"},{"CountryCode":"AGO","Language":"Luchazi"},{"CountryCode":"AGO","Language":"Luimbe-nganguela"},{"CountryCode":"AGO","Language":"Luvale"},{"CountryCode":"AGO","Language":"Mbundu"},{"CountryCode":"AGO","Language":"Nyaneka-nkhumbi"},{"CountryCode":"AGO","Language":"Ovimbundu"},{"CountryCode":"AIA","Language":"English"},{"CountryCode":"ALB","Language":"Albaniana"},{"CountryCode":"ALB","Language":"Greek"},{"CountryCode":"ALB","Language":"Macedonian"},{"CountryCode":"AND","Language":"Catalan"},{"CountryCode":"AND","Language":"French"},{"CountryCode":"AND","Language":"Portuguese"},{"CountryCode":"AND","Language":"Spanish"},{"CountryCode":"ANT","Language":"Dutch"},{"CountryCode":"ANT","Language":"English"},{"CountryCode":"ANT","Language":"Papiamento"},{"CountryCode":"ARE","Language":"Arabic"},{"CountryCode":"ARE","Language":"Hindi"},{"CountryCode":"ARG","Language":"Indian Languages"},{"CountryCode":"ARG","Language":"Italian"},{"CountryCode":"ARG","Language":"Spanish"},{"CountryCode":"ARM","Language":"Armenian"},{"CountryCode":"ARM","Language":"Azerbaijani"},{"CountryCode":"ASM","Language":"English"},{"CountryCode":"ASM","Language":"Samoan"},{"CountryCode":"ASM","Language":"Tongan"},{"CountryCode":"ATG","Language":"Creole English"},{"CountryCode":"ATG","Language":"English"},{"CountryCode":"AUS","Language":"Arabic"},{"CountryCode":"AUS","Language":"Canton Chinese"},{"CountryCode":"AUS","Language":"English"},{"CountryCode":"AUS","Language":"German"},{"CountryCode":"AUS","Language":"Greek"},{"CountryCode":"AUS","Language":"Italian"},{"CountryCode":"AUS","Language":"Serbo-Croatian"},{"CountryCode":"AUS","Language":"Vietnamese"},{"CountryCode":"AUT","Language":"Czech"},{"CountryCode":"AUT","Language":"German"},{"CountryCode":"AUT","Language":"Hungarian"},{"CountryCode":"AUT","Language":"Polish"},{"CountryCode":"AUT","Language":"Romanian"},{"CountryCode":"AUT","Language":"Serbo-Croatian"},{"CountryCode":"AUT","Language":"Slovene"},{"CountryCode":"AUT","Language":"Turkish"},{"CountryCode":"AZE","Language":"Armenian"},{"CountryCode":"AZE","Language":"Azerbaijani"},{"CountryCode":"AZE","Language":"Lezgian"},{"CountryCode":"AZE","Language":"Russian"},{"CountryCode":"BDI","Language":"French"},{"CountryCode":"BDI","Language":"Kirundi"},{"CountryCode":"BDI","Language":"Swahili"},{"CountryCode":"BEL","Language":"Arabic"},{"CountryCode":"BEL","Language":"Dutch"},{"CountryCode":"BEL","Language":"French"},{"CountryCode":"BEL","Language":"German"},{"CountryCode":"BEL","Language":"Italian"},{"CountryCode":"BEL","Language":"Turkish"},{"CountryCode":"BEN","Language":"Adja"},{"CountryCode":"BEN","Language":"Aizo"}]');
alert(countries.length);
Related
Finding titles in JSON
I currently have this large JSON file: hastebin But just want the titles of the posts. I've tried this... $json = $page; $o = json_decode($json, true); echo($json); $titles = $o["*"]["*"]["*"]["*"]["title"]; var_dump($titles); But it isn't working - it's returning NULL! Sometimes it just doesn't return anything. If anyone is wondering, yes this is from Reddit.
This should do it: $titles = array_map(function($post) { return $post['data']['title']; }, $o['data']['children']); I'm not sure what you expected using "x" indices, but you should probably read about arrays.
PHP can't use wildcards like * in array keys. Whatever string you use to reference the key, it's going to try to find a key with that exact string. So what you tried can't work because there aren't any * keys. You can get it by iterating all the levels, or iterating the outer level and referring to the proper nested key. But if you're just looking for all instances of 'title' a recursive method may be an easier way to get them. array_walk_recursive($o, function($value, $key) use (&$titles) { if ($key == 'title') $result[] = $value; }); var_dump($titles); This will get any value of 'title' regardless of its depth in the array, so if that's not what you want, then you'll need to iterate it and specifically reference the proper ones.
It's very hard to deal directly with such a long JSON document. The returned result from the page is not a valid JSON. It contains some HTML tags, but if you take the posts data and insert it in a file you can do the following according to the structure of your JSON (You can find your JSON in an external link here): <?php header("Content-Type:application/json"); $posts=file_get_contents('json.php'); //decode your JSON STRING $posts=json_decode($posts,true); //create a title variable to store your titles $titles=array(); foreach($posts['data']['children'] as $child) { array_push($titles,$child['data']['title']); } echo json_encode($titles); ?> You can even use this approach using a URL but ensure that it will return a valid JSON with no html
read jquery array in php
i am trying to retrieve the value of array via post in php script. var data = []; table.rows({ selected: true }).every(function(index){ // Get and store row ID data.push(this.data()[0]); //create a 1 dimensional array }); //send data via ajax $.ajax({ url: '/...../...', type: 'POST', data: {userid:data}, dataType: 'json', In my PHP script so far I am unable to decode the array. Have tried many ways $myArray = $_REQUEST['userid']; foreach ($arr as $value) { $userid= $value; //for now just trying to read single item } I have tried print_r($myArray ); this sucessfully prints array contents to screen. I am trying to retrieve the values for processing! Kindly point me in the right direction
I don't think that PHP would recognise the array that you've called "data" as being an array. Couldn't you turn the data from your table rows into values in a JavaScript object, encode it as a JSON string, then post that to your PHP script and use json_decode($_POST["userid"]) on the PHP end to convert it into a PHP array.
The object you are posting to PHP isn't in particular a jQuery object. Instead it is an JSON object or rather a JSON string. I guess you can't read that object the way you would read an regular array in PHP. You might want to try to decode the string with json_decode(). With true as an function argument, it will return an php array as suggested in this stackoverflow answer https://stackoverflow.com/a/6964549/6710876 $phpArray = json_decode($myArray, true); Documentation of json_decode(): http://php.net/manual/en/function.json-decode.php
simply use: echo json_encode($myArray);
You're foreach is looping $arr, which doesn't exist. Your array is being set to $myArray, so use that in your for. $myArray = $_REQUEST['userid']; foreach ($myArray as $value) { $userid= $value; //for now just trying to read single item } I believe you should also be able to find your values in $_POST
According to your var_dump : array(1) { ["userid"]=> string(21) "assssssss,camo,castor" } and if we assume "assssssss,camo,castor" are 3 different usernames. You should use this: $userids=explode(",",$myArray->userid); foreach($userids as $userid){ // use $userid }
Echo/return an array in php
Im trying to query a database from a php file then return the results (userLOC of each row) to the calling Jquery function. Calling Jquery: $.post(url, data, function (data) { alert(data); }) relavent PHP: $sql = "Select * from location"; $result = mysql_query($sql); $stack = array(); while($row = mysql_fetch_array($result)) { array_push($stack, $row["userLOC"]); } return $stack; The problem is that I cant return it correctly, if I "echo $stack" it does not work it says Im trying to convert the array to string. If I "echo $stack[0]" it will give me the first result in the array correctly so I know the values are being stored correctly (as are $stack[1], etc.) but this only sends the one value back. And if I "return $stack" as pictured nothing is alerted because nothing is echoed. How would I go about getting the whole array back so that I could iterate through and use them on the jquery side?
In PHP $foo = array(); echo $foo; will produce the literal string Array as output. You need to convert your array into a string. Since you're dealing with a Javascript target, use JSON as the perfect means of doing so: $foo = array('a', 'b', 'c', 'd', 'e'); echo json_encode($foo); Then in your JS code: $.get(...., function (data) { alert(data[1]); // spits out 'b' }); Just remember to tell jquery that you're expecting JSON output.
You need to wrap (serialize) the data in a way that can be transported to the client via HTTP and used to get the original data. Usual container formats are XML and JSON. JSON is well suited for usage in JavaScript, so use the PHP function json_encode() and echo the result.
Youll want to use JSON! Client-side: jQuery.post(url, data, function( data ) { //Data is already converted from JSON }, "json"); Server-side: return json_encode($stack); Explanation Hope this helps!
echo json_encode($stack); can help you at jquery side use jQuery.parseJSON()
You need to convert the array to a JSON object like this : return json_encode($stack);
Just convert your array it to a JSON object and return it back to your JavaScript: return json_encode($stack);
As others have said, you may wish to wrap the output using something like json: echo json_encode($stack); However, if you aren't looking for an output with the complexity of JSON formatting, you could just use implode() to output a comma separated list: echo implode(',',$stack);
Pass string to json with jquery and loop the elements
Hello there I have a really complex php script that produces a javascript file in jquery There is a string that is stored in an input type text and I want to converted into json. The input type text has undedined number of elements. So I initisialize the string in the input box <input type="text" id="selectbuttons" value="{}"> After some actions the string in the input box is something like that: {"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"} etc... Then this is my script , i use the function addScriptto to add it to the document's header, also I am using the core of jquery jquery-1.6.2.min.js to make the json object $document->addScriptto(' $.noConflict(); jQuery(document).ready(function($) { var loaded=$("#selectButtons").val(); var obj = jQuery.parseJSON(loaded); }); //end of dom ready '); But I can't make it work, when the string is not empty Is there something wrong with my json syntax? Also, I would be later able to loop all the elements and retrieve the data? Thanks in advance
Your JSON string should be in an array format like below [{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}] And then you can use the $.each to loop through the JOSN values as below: $.each(yourJSONstring,function(i,values) { //yourJSONstring holds the JSON array // i is just the loop index. it will increment by 1 in every loop alert(values.button) //will alert bt1 in the 1st loop, bt2 in 2nd alert(values.style) //will alert style1 in 1st loop, style2 in 2nd //You can have values here of the keys in JSON using the dot notation as above and do your operations. })
maybe just put [ ... ] around the JSON so it is understood as an array, something like: var obj = jQuery.parseJSON( '[' + loaded + ']' );
Yes, your JSON syntax is wrong. You should have it like: [{"button":"bt1","style":"style1"},{"button":"bt2","style":"style2"}] and then you will have array of your objects.
Associative array decoding in JSON
I am trying to change the class of a list of elements based on information in a DB. I figure the easy way was via an array. I build the array on the php side as follows. $setClassResult = array(); while($row = mysql_fetch_array( $result )) { $setClassResult= array_push_assoc($setClassResult, $row['item_id'], $row['parent']); } echo json_encode(array($setClassResult)); break; which give me.... [{"830":"0","734":"830","733":"830","732":"830","735":"830","737":"830","736":"830","738":"830","739":"830","740":"830","741":"830","742":"830","872":"0","869":"872","868":"872","880":"872","964":"872"}] to decode and change the elements I use..... $.each(data, function(key, val) { $("#recordsArray_"+key).toggleClass(val); alert(key+" "+val); }); The alert happens once with 0[object,Object] Is this because of the way I created the array? The first thing I notice wrong is the [ and ] around the JSON.
No need to add extra array, try with : echo json_encode($setClassResult);
Your result is in array of object format: [{"830":"0","734":"830","733":"830","732":"830","735":"830","737":"830","736":"830","738":"830","739":"830","740":"830","741":"830","742":"830","872":"0","869":"872","868":"872","880":"872","964":"872"}] So when you iterate, it iterates through array first & says key is 0 & value is an object.so, if you later iterate through value which is an object, you will get it or as soju if u dont require to store it in array of objects but a single object & iterate once.