How can I iterate this json? - javascript

"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?

If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.

As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.

Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value

I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there

Related

In Javascript array there are items, but when I pass an array to an MVC Controller, list/array is empty

I'm using ajax POST method
to send objects stored in an array to Mvc Controller to save them to a database, but list in my controller is allways empty
while in Javascript there are items in an array.
here is my code with Console.Log.
My controller is called a ProductController, ActionMethod is called Print, so I written:
"Product/Print"
Console.Log showed this:
So there are 3 items!
var print = function () {
console.log(productList);
$.ajax({
type: "POST",
url: "Product/Print",
traditional: true,
data: { productList: JSON.stringify(productList) }
});}
And when Method in my controller is called list is empty as image shows:
Obliviously something is wrong, and I don't know what, I'm trying to figure it out but It's kinda hard, because I thought everything is allright,
I'm new to javascript so probably this is not best approach?
Thanks guys
Cheers
When sending complex data over ajax, you need to send the json stringified version of the js object while specifying the contentType as "application/json". With the Content-Type header, the model binder will be able to read the data from the right place (in this case, the request body) and map to your parameter.
Also you do not need to specify the parameter name in your data(which will create a json string like productList=yourArraySuff and model binder won't be able to deserialize that to your parameter type). Just send the stringified version of your array.
This should work
var productList = [{ code: 'abc' }, { code: 'def' }];
var url = "Product/Print";
$.ajax({
type: "POST",
url: url,
contentType:"application/json",
data: JSON.stringify(productList)
}).done(function(res) {
console.log('result from the call ',res);
}).fail(function(x, a, e) {
alert(e);
});
If your js code is inside the razor view, you can also leverage the Url.Action helper method to generate the correct relative url to the action method.
var url = "#Url.Action("Print","Product)";

Get JSON data from WFS/Geoserver

I am struggling with getting data from WFS in my GeoServer. I want to get specific properties from the JSON returned by WFS and use it in my html page filling a table. I have read lots of posts and documentation but I can't seem to make it work. I have:
(a) changed the web.inf file in my geoserver folder to enable jsonp
(b) tried combinations of outputFormat (json or text/javascript)
(c) tried different ways to parse the JSON (use . or [], JSON.parse or parseJSON etc),
(d) used JSON.stringify to test whether the ajax call works correctly (it does!!)
but, in the end, it always returns undefined!!
function wfs(longitude, latitude){
function getJson(data) {
var myVar1=data['avgtemp1'];
document.getElementById("v1").innerHTML = myVar;
}
var JsonUrl = "http://88.99.13.199:8080/geoserver/agristats/wfs?service=wfs&version=2.0.0&request=GetFeature&typeNames=agristats:beekeeping&cql_filter=INTERSECTS(geom,POINT(" + longitude + " " + latitude + "))&outputFormat=text/javascript&format_options=callback:getJson";
$.ajax({
type: 'GET',
url: JsonUrl,
dataType: 'jsonp',
jsonpCallback:'getJson',
success: getJson
});
}
wfs(38, 23);
Could you please help me?
You are close to it. First, you have a typo in the variable name you are writing (myVar1 vs myVar). Secondly, your function is receiving a Json object, so you must dive into its structure. First you get the features, then the 1st one, then the property array, then the property of your choice.
I suggest you read a tutorial on Json Objects, as you will surely want to loop through properties/items, validate they are not null etc.
function getJson(data) {
var myVar1=data.features[0].properties['avgtemp1'];
document.getElementById("v1").innerHTML = myVar1;
}
At last, don't forget to use the debugger in your favorite browser. put a breakpoint in your function and check the structure and content of data.

Retrieve JSON encoded data in AJAX callback

This is the result when I do console.log(data) within my AJAX callback
{"image":"http://placehold.it/290x120","url":"http://www.google.com.my"}
but when I do data['image'] or data['url'], it can't retrieve the value correctly. I also tried data[0]['image'] to no avail
So I guess data is returned from a ajax request. Your can use the following code to convert string to object:
data = JSON.parse(data);
If you are using jQuery to do the ajax request, you can add dataType: "json" to the ajax option. In this way, there's no need to convert data.
Your data in callback is JSON Object,then
var image=data.image;
var url=data.url;
have you tried data.image and data.url?
also try var x = eval(data);
then x.image and x.url
Be careful of eval() on untrusted data though!!
You need to parse it to Json
var retrieved = ......;
var json = JSON.parse(retrieved);
and then just use:
var image = json.image;
var url = json.url;
Usualy this code from jQuery API's page works great:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.
However, you must remember about the same origin policy as well as the about the correct server response's content type. For json response it should be application/x-javascript or at least text/json.
javascript does not have associative arrays, You should use a javascript object like
var data = JSON.parse(data)
and then you can acces it by
data.image and data.url
If You are getting string as a response then use like below.
var response = '{"image":"http://placehold.it/290x120","url":"http://www.google.com.my"}';
var data = eval("("+response +")");
console.log(data["image"]);
console.log(data["url"]);

Use and meaning of data: { get_param: 'value' } in jQuery ajax + JSON

I am parsing generated json with jquery $.ajax but there is one option that I dont understand. I saw it in some examples and tried to look for at jquery.com but still not sure about it:
this option is:
data: { get_param: 'value' }
which is used like this:
$.ajax({
type: 'GET',
url: 'http://example/functions.php',
data: { get_param: 'value' }, //why we shell use that in that case?
success: function (data) {
var names = data
$('#cand').html(data);
}
});
I know that "data:" is what sent to the server but parsing JSON I thought i don't send but retrieve from server with GET type. And the next part "get_param: 'value'"
does not make sense to me in that case either, could anyone please explain when and what for and in what cases it shell be used?
thank you.
I know that "data" is what sent to the server
Yes. If data is an object, it gets serialized to an application/x-www-form-urlencoded string and then placed in the query string or request body as appropriate for the request type (GET/POST).
jQuery does all the escaping necessary for this.
(It also, by default, collapses nested data structures (you don't have any in your example) into PHP-style by adding [] to key names).
but parsing JSON
JSON is not involved (unless the server responds with some).
when and what for and in what cases it shell be used
Whenever you want to pass data to the server rather than requesting a static URI.
You don't send JSON (usually), you send simple GET or POST HTTP parameters. They are given to the ajax method in an object literal usually, but you could have used the string "getparam=value", too. If you provide an object, jQuery will do the parameter-serialisation and URL-encoding for you - they're sent as x-www-form-urlencoded.
To cite from the docs:
data (Object, String)
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests. See
processData option to prevent this automatic processing. Object must
be Key/Value pairs. If value is an Array, jQuery serializes multiple
values with same key based on the value of the traditional setting.

pass array and individual string to php file using ajax call

I try to implement the following code
var flag = new Array();
var name = $("#myselectedset").val();
$.ajax({
type: 'post',
cache: false,
url: 'moveto.php',
data: {'myselectset' : name,
'my_flag' : flag
},
success: function(msg){
$("#statusafter").ajaxComplete(function(){$(this).fadeIn("slow").html(msg)});
}
});
You can see that the name is a single string and the flag is an arry, am I using the right format for passing them throw ajax call, anyone could help me, thanks
It is impossible to pass arrays in a POST request. Only strings.
You will either need to stringify your array, or consider posting as JSON instead.
You should be able to do something quite simple, like replace your "data" property with:
data : JSON.stringify( { myselectset : name, my_flag : flag } )
That will convert the data into a JSON string that you can turn into PHP on the other side, using json_decode($_POST["my_flag"]);
Very important note:
For JSON.stringify to work, there can't be any functions in the array - not even functions that are object methods.
Also, because this is a quick example, make sure that you're testing for null data and all of the rest of the best-practices.

Categories

Resources