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);
Related
[{"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);
I have created APIs to retrieve data from my server and then I get the data with json format like this :
{
"items": [
{
"2013-03-28": 1771,
"2013-03-29": 1585,
"2013-03-30": 1582,
"2013-03-31": 1476,
"2013-04-01": 2070,
"2013-04-02": 2058,
"2013-04-03": 1981,
"2013-04-04": 1857,
"2013-04-05": 1806,
"2013-04-06": 1677,
"2013-04-07": 1654,
"2013-04-08": 2192,
"2013-04-09": 2028,
"2013-04-10": 1974,
"2013-04-11": 1954,
"2013-04-12": 1813,
"2013-04-13": 1503,
"2013-04-14": 1454,
"2013-04-15": 1957,
"2013-04-16": 1395
}
]
}
How do I looping with my json data dynamically using jQuery?
My code :
<html>
<head></head>
<body>
<script src="jquery-1.9.1.js"></script>
<script>
$(document).ready(function() {
$.ajax({
type : "GET",
url: "myurl.php",
cache: false,
dataType: "jsonp",
success:function(data){
if(data==''){
alert('Fail');
}else{
alert('Success');
}
}
})
});
</script>
</body>
</html>
How do I modify my jQuery to get data dynamically following the date that the data will change every day as in the example I wrote above data??
Thanks before...
There are a few things to consider with your example data, but in your case, the following will do the trick:
var importantObject = data.items[0];
for(var item in importantObject ){
var theDate = item;//the KEY
var theNumber = importantObject[item];//the VALUE
}
Here is a working example
But what does all this mean?...
First of all, we need to get the object that we want to work with, this is the list of dates/numbers found between a { } (which means an object) - an array is defined as [ ]. With the example given, this is achieved like so:
var importantObject = data.items[0];
because items is an array, and the object we want is the first item in that array.
Then we can use the foreach technique, which effectively iterates all properties of an object. In this example, the properties are the date values:
for(var item in importantObject ){ ... }
Because we are iterating the properties, item will be the property value (i.e. the date bit), so item is the date value:
var theDate = item;//the KEY
Finally we get the number part. We can access the value of any given object property by using the string value of the property index (relative to the object), like so:
var theNumber = importantObject[item];//the VALUE
If you already know which date you want the value for, then you can access it directly like so:
var myValue = data.items[0]["2013-04-16"];//myValue will be 1395 in this example
Using jQuery.each() loop through the items
$.each(data.items[0], function (key, value) {
console.log(key + ": " + value);
var date = key;
var number = value;
});
DEMO HERE
You can use the jQuery each function to do this. For example like this:
$.each(data, function(k, v) {
// Access items here
});
Where k is the key and v is the value of the item currently processed.
//get your detail info.
var detail = data.items[0];
$.each(detail, function(key, val) {
console.log(key + ": " + val);
}
i am using this to get informations from ajax jquery in json formate but it give me error
like this 0 =[object object]
$.getJSON("ajax_files/getSingleRow.php?id="+id+"&type="+type, function(json){
$.each(json, function(key, val) {
//$("#"+key).val(val);
alert(key+'='+val);
});
});
here is my josn string
[{"id":"1","ref":"RH-R-1","name":"","description_demo":"this is desc test"}]
Thanks all...here is how my json develops
while($rw = $oAppl->row($res))
{
$return[]=array('id'=>$rw['id'],
'ref'=>$rw['ref'],
'name'=>$rw['name'],
'description_demo'=>$rw['description_demo']);
}
header('Content-type: application/json');
echo json_encode($return);
The JSON text consists of an array containing an object.
When you loop over it, you get the first key of the array (0) and then the string serialisation of the object ([Object object]). Then it stops because there is only one entry in the array.
This is not an error. It is expected behaviour given the data you are inputting.
Possibly you want to loop over the object instead, in which case:
var ob = json[0];
$.each(ob, function(key, val) {
That isn't an error, strictly, it's an object. It might contain an error, who knows. But the thing itself is a thing waiting to be accessed (i.e., the value of val) and there's nothing inherently erroneous with it.
Try accessing the members, output the id, name, etc, instead of just dumping the thing in an alert.
Try this:
$.getJSON("ajax_files/getSingleRow.php?id=" + id + "&type=" + type, function (json) {
$.each(json, function (key, val) {
// This will only give you the 'ref' value
alert(key + '=' + val.ref);
// To loop through all the values
$.each(val, function (key2, data) {
alert(key2 + ": " + data);
});
});
});
DEMO HERE
Your JSON string is wrapped inside an array. [ {} ] Leave the "[" and "]" out.
Read the propery value of your JSON collection item.
$.each(json, function(key, item) {
alert(key+'='+item.id);
alert(key+'='+item.ref);
alert(key+'='+item.description_demo);
});
This should work fine assuming you have no other script errors in your page.
Working sample : http://jsfiddle.net/a4Efx/4/
i am learning on how to parse json using jquery
PHP
foreach($cars as $car)
{
$output['carID'][] = $car->carID;
$output['carName'][] = $car->carName;
}
echo jsonEncode($output);
JSON
{"carID":["1","2"],"carName":["BMW","Mercedez Benz"]}
My javascript
$.getJSON('/cars.php', { carID: carID }, function(data) {
$.each(data, function(i,item) {
for(j=0; j < item[item.carName]; j++) {
console.log(item[item.carName][j]);
}
});
});
I think my code is entirely wrong because its not working.
how can i get the value inside of ["1","2"] ?
Thanks for the help.
It's not the "value of 1" that you're looking for. It's the value at index 0, which happens to be "1".
["1","2"] is the value of carID, and it is an array.
Try accessing it this way:
alert(item.carID[0]); // will alert "1"
alert(item.carID[1]); // will alert "2"
As I know, array indexes start from "0" in many languages, so you need something like this to get array values in your code;
var data = {"carID":["1","2"],"carName":["BMW","Mercedez Benz"]};
$.each(data.carID, function(key, val){
var i = 0, id;
while(id = val[i++]) console.log(id);
});
// or just simply use
console.log(data.carID[0]);
I have a php page that returns json like this:
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
$rows[] = $row;
}
print json_encode($rows);
When I run the php page I get back something like:
[{"phone":"1234567"},{"phone":"1234567"}]
This is my jquery code:
$.ajax({
url: 'test.php',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function(response) {
$.each(response, function() {
$.each(this, function(key, value){
alert(key + " --> " + value);
});
});
}
});
});
I got that from another SO question. This will give me my keys and value in the alert. This was just for me to make sure everything works. I have searched but cannot figure out how to just get one value. Say I wanted the name, what do I put? I have tried:
success: function(response) {
var obj = $.parseJSON(response);
alert( obj.phone );
}
But since it is multiple rows it won't work unless I have, and it also fails when I have one row like this:
echo json_encode(array("phone" => "123")
How do I get a single value from a row?
How do I iterate through multiple rows and only get one of the column values?
The response variable is an array of objects. To access a single index in your response variable:
var phone = response[0].phone;//replace `0` with the index you want
If you end-up iterating through your response in a loop make sure to do it like this for the best performance:
var len = response.length;
for (var i = 0; i < len; i++) {
console.log(response[i].phone);
}
Check-out this jsperf to see how much faster this type of loop is than for(i in array): http://jsperf.com/for-in-tests
The response JSON is an array. To get the first phone number, retrieve the first object through response[0], then get the property using .phone:
success: function(response) { //response = array, when using dataType:"JSON"
alert(response[0].phone);
}
Replace 0 with any number between 0 and response.length to get the corresponding phone property.
Javascript:
for (var i; i < response.length; i++) {
console.log(response[i].phone);
}