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}]};
Related
I have a PHP script which returns a JSON response like the below
[{"agencyID":"99999", "name":"john", "surname":"doe", "bookings":[{
"ID":"54321", "transactions":[{"desc":"example text"}],
}]
}]
MUST ADD - I HAVE MADE UP THIS JSON - JUST AN EXAMPLE.
How do i push all this information into a JavaScript array from AJAX success block?
I would like to be able to use the information later for example like this -$('#div').append(array.desc);
Content-Type
application/x-www-form-urlencoded; charset=UTF-8
If you are using the jQuery ajax method, you can push the response from your PHP script into an array and use it later. Here's an example:
JavaScript
$.ajax({
url: 'url/to/php/script.php',
dataType: 'JSON',
success: function (data, textStatus, jqXHR) {
var array = [];
array.push(data);
$('#foo').append(array);
}
});
I make a $.post request to submit data and return invalid data. Here is the $.post request:
$('#submitAll').click(function(){
$.post("php/entries/submitAndReload.php", {array : dataObject.dataArray}, function(data){
alert(data); // alerts: "[[“0”, “0”,””,””, “0”, “0”, “0”, “0”,”No Style”]]"
dataObject.dataArray = data;
$.post("php/entries/stageArea.php", {array : dataObject.dataArray}, function(data){
$('#stageArea').html(data);
});
});
});
dataObject.dataArray is a double array and alert(data) alerts what looks like the proper format for the subsequent $.post request, but the output from the 2nd $.post request looks like I pass in the following array:[[ "[" ]]. The first field gets a "[" and no other fields get data.
I'm not sure what's going on here and how to properly store the returned data into dataObject.dataArray
What's going on here?
Correct this line:
dataObject.dataArray = data;
To this:
dataObject.dataArray = JSON.parse( data );
You need to parse JSON, untill parsing it is just a string.
Add dataType argument to $.post.
When set as 'json' jQuery knows to parse it to object/array from json string
$.post(url, postData, function(data){
// handling code
alert($.type(data)); //"array"
},'json');
If you set proper content Type header at server also it helps
Reference: $.post docs
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
}
Why is the getJSON function structured this way?
$.getJSON( url [, data ] [, success ] )
Instead of just returning an object, i.e.:
var myjson = $.getJSON( url [, data ])
Because it returns a jqXHR object that contains responseText and responseXML properties, as well as a getResponseHeader() method. When the transport mechanism is something other than XMLHttpRequest (for example, a script tag for a JSONP request) the jqXHR object simulates native XHR functionality where possible. Basically, how would you know if the request was successful?
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/