Pass JSON in Javascript variable into a JQuery post - javascript

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
}

Related

IE11 inteprets AJAX POST reply as string, despite being JSON array

From an JQuery AJAX post request the server sends me an reply that just says Hello, and I want to get that Hello as a string.
I wrote this code to get the text value:
var posting = $.post(
"https://server/bla",
{
input: theinput
}
);
posting.done(function( reply ) {
console.log(reply);
console.log(typeof reply);
console.log(reply[0]);
}
It works perfectly on Firefox 55:
Array [ "Hello" ]
object
Hello
... but IE11 seems to believe it is a string (same code):
["Hello"]
string
"[\"Hello\"]"
I wrote a hackish workaround that just uses substring to remove the brackets and quotes at the beginning and end if the variable is a string, but it does not handle well quotes within the reply (Hell"o becomes Hell\"o).
Is there a cleaner solution?
By the way, here is the server side Java code:
JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
jsonArray.put("Hello");
As tipped by Rory, the datatype parameter helps here.
dataType Type: String The type of data expected from the server.
Default: Intelligent Guess (xml, json, script, text, html).
I rewrote the query part to this:
var posting = $.ajax({
type: "POST",
url: "<%=addResUrl%>",
data: {
input: theinput
},
dataType: "json"
});
Note the dataType: "json".
And now it works in IE11 the same way as in Firefox: The JSON is recognized as JSON.

Difference between filter_input and direct acces on $_POST after objective ajax request

I have different results by using filter_input(INPUT_POST, 'attribute') and $_POST['attribute'] and don't know why this happens.
The Post-Request is send by a JavaScript build with JQuery and looks like that:
// type javaScript
var formData = {
field_a: "valueA",
field_b: "",
field_c: undefined
};
$.ajax({
url: 'serverAddress',
data: {action: 99, formData: formData},
dataType: 'json',
method: 'post',
success: function(){
console.log(arguments)
}
});
My PHP-Script looks like that:
// type php
$requestMethod = INPUT_POST;
$response = [
"fi-result" => filter_input($requestMethod, 'formData'),
"direct-result" => $_POST['formData'];
];
echo json_encode($response);
the result what is coming back is not what i was awaiting because the access via filter_input returns falsein my tests and not an json object like the direct access on the super global $_POST.
// type json response
{
"fi_result": false,
"direct-result": {
"field_a": "valueA",
"field_b": ""
}
}
Why are there differences between using filter_input and direct access on $_POST?
I don't want to access the super global $_POST. Is there any way to use filter_input like above without encode formData to a String in JavaScript and decode it in PHP one simple step after encoding?
By the way. I'm using TypeScript to generate my JavaScript. That is not supporting the FormData Object (transpiler throws error on new FormData()). So i can't use this.
I found the answer deep in the PHP docs. POST is not build to transport deep object. And filter_input method tries to get simple datatypes like string or int. this method does not parse internal so i have to send it as JSON string and decode it or i can't use filter_input in my case.
i took the first and send now strings.

PHP json_encode is returning as array string, but is not converting to array in JavaScript properly

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

Converting JSON using jQuery

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/

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}]};

Categories