[{"id":"1","name":"Bangalore"},{"id":"3","name":"Mysore"}]
I tried using the below code but its not giving me any output
var obj=jQuery.parseJSON(response); // now obj is a json object
alet(obj.id);
$("#state").html("<option value='"+ obj.id +"'>'"+ obj.name +"'</option>");
$("#state").next().next().html("<li rel='"+ obj.id +"'>"+ obj.name +"</li>");
Your JSON is a JSON array containing two objects. Therefore, you need to read it as an array first, before accessing the id:
alert(obj[0].id);
To loop all, you will write something like this:
for(var i = 0; i < obj.length; i++){
console.log("ID: " + obj[i].id);
};
Loop through array
var response=jQuery.parseJSON(response);
var li='';
for(var i=0;i<response.length;i++){
li=li+ "<option value='"+ response[i].id +"'>'"+ response[i].name +"'</option>";
}
$("#state").html(li);
Related
I have a json response from php to ajax. The thing is depending on the value entered in a text box the number of json arrays vary. Example: sometimes it may return {"count1":10, "ccc1":30} and sometimes like this {"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}. I extract the value in jquery this way:
success: function(response){
var count = response.count1;
//do something
}
But now since the number of counts are different I used a loop. Question is I can figure out how many of them I am receiving but how can I process them? The var count = response.count needs to be specific right? I cannot just concate any strings like this:
var count = 0;
while(something){
count = count + 1;
var str = "count"+count;
var whatever = response.str;
}
So, can someone please help me with a suitable solution in this case?
You are on the right track there. Something like this should work for you.
var i = 1;
while(response['count' + i]) {
var count = response['count' + i++];
}
You can access the properties as if they were array indices. so response['count'+i] works.
Loop through all properties and add them in a variable like following.
var response = { "count1": 10, "ccc1": 32, "count2": 40, "ccc2": 123, "count3": 32, "ccc3": 21 };
var count = 0;
for (var prop in response) {
if (prop.startsWith('count'))
count += response[prop];
}
console.log(count);
To retrieve all values use jQuery $.each function.
var data_tmp = '{"count1":10, "ccc1":32, "count2":40, "ccc2":123,"count3":32,"ccc3":21}';
var data = $.parseJSON(data_tmp);
$.each(data, function(k,val){
if(k.toLowerCase().indexOf("count") >= 0){
$('.wr').append('<div>' + val + '</div>')
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="wr"></div>
success: function(response){
var count = response.count1;
var object = JSON.parse(response);
alert(object.length);
for (i = 0; i < object.length; i++) {
console.log(object[i]);
}
}
I have a problem with jQuery to obtain each value from jSon string and modify a div or span or other id with value obtained from a jSon string.
At the start of each PHP file i have an SQL request generate an hidden input with a jSon string as value. This is for multilanguage for example in english the generated string is
<input type="hidden" id="page_json_language_home" value='{
"label_title":"My WebSite",
"label_settings":"Settings",
"label_subscription":"Subscription"
}' />
for french :
<input type="hidden" id="page_json_language_home" value='{
"label_title":"Mon site web",
"label_settings":"Parametres",
"label_subscription":"Abonnement"
}' />
this is work fine !
After that i have a javascript using jquery to match each label_xxx with value
i have many html code like this
<title id="label_title></title>
<div id="label_settings"></div>
or
<span id="label_subscription"></span>
This is my (partial) code in my javascript file i called to obtain the json string from hidden input :
var _getPageJsonLanguage = function(id) {
if (!id)
id = "page_json_language";
else
id = "page_json_language_" + id;
var json = $("#" + id).val();
var data = bsc.data.jsonParse(json);
return data;
};
This is work fine too !
The code in problem is :
data_language = bsc.page.getPageJsonLanguage("home");
var j = 0;
var language = [];
for (i in data_language) {
console.log("i in language = " + i);
language[j] = i;
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
The result can i obtain in browser 1) undefined for each label or 2) label_xxx for each label_xxx
I need help to access each value of each label_xxx .
I can't obtain the value, this is my last try....
I believe the problem is in your for in loop, you never actually grab the value, only the key:
for (i in data_language) {
console.log("i in language = " + i);
language[j] = data_language[i]; //changed this line to actually grab the value
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
If you are receiving undefined, it may be due to the JSON not being parsed correctly. Since your using jQuery, you can always run $.parseJSON(json) to be sure.
Fiddle accessing your JSON in a for in loop and logging: http://jsfiddle.net/tymeJV/CKBLc/1/
I hope this will work -
var data_language = JSON.parse($("#page_json_language_home").val());
var language = [];
var j = 0;
for (i in data_language) {
console.log("i in language = " + i);
language[j] = data_language[i];
console.log("language[j] = " + language[j]);
$("#" + i).html(language[j]);
j++;
}
I have a PHP file which only return an array with the drivers and a url:
{"drivers":[{"marco":[0],"luigi":[123],"Joan":[2444],"George":[25]}, {"marco":[23],"luigi":[3],"Joan":[244],"George":[234]}],"url":"google.es"}
Is the json correctly structured?
And I'm trying to get the result using jQuery and AJAX by this way:
$.getJSON('calculate.php&someparams=123', function(data) {
alert("url - " + data.url);
var arr = data.drivers;
for (var i = 0; i < arr.length; i++) {
alert(arr[i] + " - " + arr[i][0]);
}
});
I see the first alert() with the url, but the second one does not works...
What am I doing wrong?
If you need more info let me know and I'll edit the post.
The drivers is not an array, it is an object, you use $.each to iterate through the object elements.
$.getJSON('calculate.php&someparams=123', function(data) {
$.each(data.drivers, function(key, value){
$.each(value, function(key, value){
console.log(key, value);
});
})
});
That's an object, not an array. It has named properties, not numerical indexes.
You need a for in loop to loop over the properties.
drivers is an object. Not an array.
How about this?
var json_string = '{"drivers":{"marco":[0],"luigi":[123],"Joan":[2444],"George":[25]},"url":"google.es"}';
var obj = jQuery.parseJSON(json_string);
alert(obj.url);
I have a problem with the returned array from ajax call.
the array is encrypted using json. it is as below
while ($found_course = mysql_fetch_assoc($sql)) {
$info[] = array(
'code' => $found_course['course_code'],
'name' => $found_course['course_name'] );
}
echo json_encode($info); //this is returned to javascript
then the problem is that I am unable to use the above array returned in javascript. I tried using the $.each method but to no avail. the eval() also do not work as it give output as [object object]. Can someone please help me with this.
All I want is to be able to acces the code and the name of the course saperately
Thanks.
Just loop through it with for()
for (var c in myAjaxArray){
myAjaxArray[c].code; // contains the code
myAjaxArray[c].name // contains the name
}
Make sure you set the dataType in the jQuery ajax call to "JSON" to make sure you have a json Object. Or use the $.getJSON() function.
<script>
var data = <?= json_encode($info); ?>;
for (var i = 0; i < data.length; i++) {
var item = data[i];
alert(item["code"] + " / " + item["name"]);
}
<script>
This should get you the data you need. Not sure how you tried using $.each but it should be in your success function on your ajax call. Also make sure the datatype is set to json.
success: function(data){
$(data).each(function(idx,val){
alert(val.code + " " + val.name);
})
}
I'm trying to take a jSON encoded string out of my database and loop through the items but I'm having some difficulty. Here's the string in the database:
["volunteers","seat_dedication_program","memberships"]
And here is the code:
//Looks for _checkbox when looping through my database fields (object dbVals) and turns it into a true jQuery array if it finds it.
if( key.search(/_checkbox/i) > 0 ) var arr = $.makeArray(dbVals[key]);
//If it is an array, loop through the array values and show them
if($.isArray(arr)==true){
$.each(arr, function(i, n){
alert(i + " : " + n);
});
}
What I want is this:
//alert
0 : volunteers
//alert
1 : seat_dedication_program etc...
What I'm getting is this:
//alert
0 : ["volunteers","seat_dedication_program","memberships"]
I think I've included all relevant data. Can anyone help me figure out why this is happening?
Thanks.
Using $.makeArray(..) is giving you an array where the only element is the string you gave it. You need to parse the string into a JavaScript object. Use the JSON2.js library to parse then your code would look something like this.
var arr = JSON.parse(dbVals[key]);
if($.isArray(arr)==true){
$.each(arr, function(i, n){
alert(i + " : " + n);
});
}
Just use a regular for loop:
for (var i=0; i<arr.length; i++) {
var n = arr[i];
alert(i + " : " + n);
}
or for large arrays, the slightly optimized:
for (var i=0,l=arr.length; i<l; i++) {
var n = arr[i];
alert(i + " : " + n);
}
or if you really hate for loops:
Array.prototype.each = function (callback) {
for (var index=0,l=this.length;index<l;index++) {
var item = this[index];
// index is second arg since it's optional
callback(item,index);
}
}
arr.each(function(n,i){
alert(i + " : " + n);
});
but I'd recommend the for loop to avoid clashing with library modifications or when Firefox suddenly decide to implement its own each method for arrays (some libraries have already been bitten by this).