Converting JSON using jQuery - javascript

For reference, this is the JSON I'm working with: http://goo.gl/xxHci0
In regular JavaScript, using the code below works fine and I can manipulate it easily:
var info = JSON.parse(document.getElementsByTagName("pre")[0].innerHTML);
alert(info[0]["AssetId"]);
But I'm working on a jQuery version of the same code to avoid using methods like iFrames to get this data. My jQuery function is:
$.get (
page,
function parse(data) {
var r = $.parseJSON(data);
alert(r[0]["AssetId"]);
}
);
I found ways to convert the JSON using jQuery, but I'm having trouble finding where the JSON code is that needs to be converted.

Provided that the response from the server is a valid string representation of a JSON object, you'll be able to specify the dataType for the get() request. You could do something like this:
$.get( page, function( data ) {
alert( data[0]["AssetId"] );
}, "json" ); // <-- here is the dataType
With the correct dataType set, you will not need to manually parse the data, it will arrive in your callback function as a JSON object.
References:
$.get()
jQuery.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )

You can use getJson. This converts your JSON string to a JavaScript object.
I threw JSFiddle together for you using the facebook graph api:
http://jsfiddle.net/J4LCX/
$.getJSON( "http://graph.facebook.com/spikeh/",
function( data ) {
alert(data.id);
});
Alternatively, to fix your code, just reference the object's id directly:
$.get (
"http://graph.facebook.com/spikeh/",
function parse(data) {
alert(data.id);
}
);
JsFiddle: http://jsfiddle.net/LBy9y/

Related

Pass JSON in Javascript variable into a JQuery post

I am trying to get some data from a remote location by a JQuery post. It works great when I hardcode the data to post, but doesn't work when I put the JSON in a javascript variable, and then pass it in. As far as I understand, a JSON is just a string, so I'm not sure what the difference is.
so, this works:
$.post( PostURL, {var:"somevalue"}, function( data ) {
// do something with data
}
but this doesn't:
jsonstring = '{var:"somevalue"}';
$.post( PostURL, jsonstring, function( data ) {
// do something with data
}
obviously, I'm going to need to send different variables to get the stuff I need, so it can't be hard-coded. What am I doing wrong?
Data in post() doesn't take JSON as an argument but an object, which is why the first code works. Your second code is using JSON, which is a string representation of an object rather than an actual object, therefore invalid.
jQuery.post( url [, data ] [, success ] [, dataType ] )
url
Type: String
A string containing the URL to which the request is sent.
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
http://api.jquery.com/jquery.post/
Note that while it says that data can take a string, it is of the form key=value&key=value.
You don't need JSON, simply store the object in your variable rather than converting it to a string.
var myData = {var:"somevalue"};
$.post(PostURL, myData, function(data) {
// do something with data
});
jsonstring = JSON.parse('{var:"somevalue"}');
$.post( PostURL, jsonstring, function( data ) {
// do something with data
}

Serialize and de-serialize array (without jquery?)

I have a method which sends an ajax request. When the reply from the server is received I need to serialize and later de-serialize
$.ajax({
//.....
done(function(data) {
//1 Need to serialize data (which is an array)
});
function myFunction() {
//2 Need to de-serialize data which has been serialized
}
I know I could use jquery#serializeArray() if I had a form to serialize:
$( "form" ).submit(function( event ) {
console.log( $( this ).serializeArray() );
event.preventDefault();
});
But I don't have a form and data from the server (I guess) has nothing to do with serializeArray function of jquery. So how can I do it? What's one of the best ways?
Preferably not to use any third-party libraries except jquery or even not to use jquery at all.
The common way to serialize JS-objects to JSON is via JSON.stringify().
The other way around is via JSON.parse().
o={"firstName":"john","lastName":"doe"};
console.log(JSON.stringify(o));
console.log(JSON.parse(JSON.stringify(o)));
See MDN for stringify and parse
Here is a Fiddle.
.serializeArray() from jQuery is only a neat helper function to serialize form-data.
It builds its objects from the ground up. Here is the source for that.
If you want to submit your data as JSON, you simply
$.ajax({
type: "POST",
url: url,
data: JSON.stringify(data),
success: success,
dataType: dataType
});
Free after jQuery.post().

Fetch data from a complex JSON

I'm new to javascript and JSON and I've been given a task to complete. Please find the JSON in the following link,
http://pastebin.com/0BY3eptF
According to me the above is a very complex JSON.
I'm trying to fetch the out from a WSDL via ajax
success: function(api) {
console.log(api.SearchResult); // trying to fetch information on SearchResult object
}
This doesn't work. I would like to learn how to iterate each JSON string loop. I also see an array which is WSResult[]. A neat javascript with explanation will help me a lot. Thank you.
Some web services return content type as plain text instead of json, you have to manually convert into json. below code will help you do the same.
success: function(api) {
if (api.constructor === String) {
api = JSON.parse(api);
}
console.log(api.SearchResult);
}
To loop through api.SearchResult.Result.WSResult array, please find below code
$(api.SearchResult.Result.WSResult).each(function (index, val) {
// here val is single object of WSResult array
});
success: function(api) {}, here, api is still a string, you have to parse it to JSON first:
success: function(api) {
var api = JSON.parse(api);
console.log(api.SearchResult); // trying to fetch information on SearchResult object
}
Not a complete answer, but some useful pointers:
$ajax({
url: 'http://myURL',
// specify the datatype; I think it overrides inferring it from the document MIME type
dataType: 'json',
success: function (api) {
// provided your data does come back as a JSON document
// you should be able to access api.SearchResult
},
error: function( jsXHR, textStatus, errorThrown) {
// always have an error handler, so you can see how it went wrong.
}
);
Read the section on dataType here, as it may solve your problem

not sure why this jquery post isn't working

I have the following jquery:
var xj=[{"name":"person","id":1},{"name":"jack", "id":2}];
$.post('/hex-jt/locations',xj , function(data){
console.log("this posted");
},'json');
which seems like it should be ok. But it is passed like this to my rails app:
Any idea what is going on with this?
You are calling jquery.post() with bad argument data, passing an array instead of a String or a PlainObject.
jQuery.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
data
Type: PlainObject or String
A plain object or string that is sent to the server with the request.
You can for instance modify it like this, wrapping the array in an object:
xj={"users":[{"name":"person","id":1},{"name":"jack", "id":2}]};

How to retrieve response from xmlhttprequest? (screenshots)

I've got this code of autocomplete jqueryUI:
.autocomplete({
source: function( request, response ) {
var results = $.getJSON( url, {
term: extractLast( request.term )
}, response );
console.log(results);
},...
The console.log of the var 'results' looks like this:
I need to extract the response or responseText field to test if is empty and popup an error with no matches found. But nothing works to retrieve that field:
results.response
results.getResponse()
results.getResponseHeader()
Neither of these methods works. Thanks
Both of the answers work: It returns my response properly. I can test it.. but it break my autocomplete. I am still looking into it.
The third variation, the callback, provides the most flexibility, and can be used to connect any data source to Autocomplete. The callback gets two arguments:
A request object, with a single property called "term", which refers
to the value currently in the text input. For example, when the user
entered "new yo" in a city field, the Autocomplete term will equal
"new yo".
A response callback, which expects a single argument to
contain the data to suggest to the user. This data should be filtered
based on the provided term, and can be in any of the formats described
above for simple local data (String-Array or Object-Array with
label/value/both properties). It's important when providing a custom
source callback to handle errors during the request. You must always
call the response callback even if you encounter an error. This
ensures that the widget always has the correct state.
This is the jquery UI autocomplete documentation about source by callback function. I can't understand why the new version is not working
if you want the response you probably want to do
var results = $.getJSON( url, {
term: extractLast( request.term )
}, function(response) {
console.log(response);
});
.getJSON is asynchronous and will return the result in a callback function.
Hence, change your code to something like this:
.autocomplete({
source: function( request, response ) {
var results = $.getJSON( url, {
term: extractLast( request.term )
}, function( results ) {
console.log( results );
});
}, ...
);
If you by some reason need to do a synchronous call you can use jQuery's .ajax function instead with the async option set to false.
You need a success callback when performing jQuery's ajax functions. You should read the documentation.

Categories