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/
Related
I have a php file which when called returns a simple non associative array of string values. When I request the array using the jQuery get routine I get the array I expect, but when I try to iterate it , instead of getting the two string values, the $.each command iterates every char. I don't understand what I'm getting wrong.
My code:
<div name ="test_spot" id ="test_spot" width="200" height="400">Test</div>
<script type="text/javascript">
function getOutput(){
$.get( "data.php", function( data ) {
// This call verifies the the array is what I would expect.
// ["one","two"]. Then I comment this out and run the code below.
//$( "#test_spot" ).html( data);
$.each(data, function(index, value){
// This outputs each char instead of each string each on its own line in the div.
// [
// "
// o
// n
// e etc
$('#test_spot').append($('<p>').text(value));
});
});
}
</script>
<button onClick="getOutput()" style="height: 60px; width:100px;" >Test</button>
Thanks for the help.
You are expecting an object but are getting back a JSON string. When you pass that to .each it iterates over the characters in the string.
Try specifying the dataType as json like this:
$.get( "data.php", function( data ) {
$.each(data, function(index, value){
$('#test_spot').append($('<p>').text(value));
});
}, "json" );
Or, like charlietfl points out, simply use
$.getJSON( "data. php", function( data ) {
$.each(data, function(index, value){
$('#test_spot').append($('<p>').text(value));
});
});
If that still doesnt work, Id look at the output and make sure that it is valid JSON.
I have a jquery function that sends some data to a method and receives a simple json from the php (the json returns the data sent through get).
$("#filter").submit(function() {
$.ajax({
data:$("form").serialize(),
type: $(this).attr("get"),
url:"get.php",
success: function(response){
$("#rez").html(response);
}
});
return false;
});
This is the json I get
{"list1":["bike","car","bus"],"list2":["1 seat","4 seas","10 seats"],"list3":["cheap","medium","expensive"],"list4":["green energy","bio","petrol"]}
I tried to iterate through it like this:
$.each(response, function(index, val)
{
alert(response[index]);
});
Also, tried this:
alert(val);
How can I iterate through it and make a simple alert?
The goal is to append each item to the "#rez" paragraph. But for now, I just want to iterate through the json and can't figure it out.
ALSO!
I have another json like this:["first val","second val"] how do I iterate this? Tried the above methods and none worked.
Before you start to loop you have to parse the JSON string into an Object and in this case you can do it using something like this:
var obj = JSON && JSON.parse(response) || $.parseJSON(response);
$.each(obj, function(index, val) {
// ...
});
If you don't provide the data type like dataType:"json" in your ajax params object then you have to explicitly parse the string to an object. Read more abour $.parseJSON here.
I had similar issues and used this:
for (var key in someObject) {
if (someObject.hasOwnProperty(key)) {
var something = someObject[key];
console.log(something)
}
}
Basically using "for"-loop here.
I'm trying to send a Get request by ajax and output json data that is returned by server in html.
But, I got this error.
Uncaught TypeError: Cannot use 'in' operator to search for '324' in
[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]
This is my code that sends a Get request to php file by ajax.
When I use $.each method, it get the error that I showed in the above.
parentCat.on('change', function(e){
parentCatId = $(this).val();
$.get(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
}
)
})
This is my PHP code that returns query result in json format.
public function actionAjax(){
$parentCatId=$_GET['parentCatId'];
$catData = Category::getTargetCategoryData($parentCatId);
echo CJSON::encode($catData);
Yii::app()->end();
}
json data outputted by this php is like this.
[{"id":50,"name":"SEO"},{"id":22,"name":"LPO",}]
How can this problem be fixed?
You have a JSON string, not an object. Tell jQuery that you expect a JSON response and it will parse it for you. Either use $.getJSON instead of $.get, or pass the dataType argument to $.get:
$.get(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
},
'json'
);
You can also use $.parseJSON(data) that will explicit convert a string thats come from a PHP script to a real JSON array.
If you're fetching JSON, use $.getJSON() so it automatically converts the JSON to a JS Object.
I fixed a similar error by adding the json dataType like so:
$.ajax({
type: "POST",
url: "someUrl",
dataType: "json",
data: {
varname1 : "varvalue1",
varname2 : "varvalue2"
},
success: function (data) {
$.each(data, function (varname, varvalue){
...
});
}
});
And in my controller I had to use double quotes around any strings like so (note: they have to be escaped in java):
#RequestMapping(value = "/someUrl", method=RequestMethod.POST)
#ResponseBody
public String getJsonData(#RequestBody String parameters) {
// parameters = varname1=varvalue1&varname2=varvalue2
String exampleData = "{\"somename1\":\"somevalue1\",\"somename2\":\"somevalue2\"}";
return exampleData;
}
So, you could try using double quotes around your numbers if they are being used as strings (and remove that last comma):
[{"id":"50","name":"SEO"},{"id":"22","name":"LPO"}]
Use getJSON
$.getJSON(
'index.php?r=admin/post/ajax',
{"parentCatId":parentCatId},
function(data){
$.each(data, function(key, value){
console.log(key + ":" + value)
})
});
Detail look here http://api.jquery.com/jQuery.getJSON/
In my case, I forgot to tell the type controller that the response is a JSON object.
response.setContentType("application/json");
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 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);
}