Send a JavaScript array as a JSON value? - javascript

How can I send a JavaScript array as a JSON variable in my AJAX request?

This requires you to serialize the javascript array into a string, something that can easily be done using the JSON object.
var myArray = [1, 2, 3];
var myJson = JSON.stringify(myArray); // "[1,2,3]"
....
xhr.send({
data:{
param: myJson
}
});
As the JSON object is not present in older browsers you should include Douglas Crockfords json2 library
If you already rely on some library that includes methods for encoding/serializing then you can use this instead. E.g. ExtJs has Ext.encode

If you're not using a javascript library (jQuery, prototype.js, etc) that will do this for you, you can always use the example code from json.org

Just encode the array and send it as part of your AJAX recuest:
http://www.openjs.com/scripts/data/json_encode.php
There are too many others encoders, or even plugins for JQuery and Mootools :D

Here's an example:
var arr = [1, 2, 3];
$.ajax({
url: "get.php",
type: "POST",
data: {ids:arr},
dataType: "json",
async: false,
success: function(data){
alert(data);
}
});
In get.php:
echo json_encode($_POST['ids']);
Array will be converted to object using {ids:arr}, pass the object itself and letting jQuery do the query string formatting.

Related

How to tell JavaScript that my variable is an array and not a string?

I'm using flask and my backend returns to AJAX a response in the form of a python list, and then JavaScript understands it as a string, but that's a problem because I have to iterate over that list.
All i could find on the internet is how to check the type of a variable, but couldn't find any method (which in python is pretty straightforward) to change it
The Array.isArray() method determines whether the passed value is an Array or not.
var someNumbers = [1,2,3];
console.log( Array.isArray( someNumbers ) );
and if it is an array it will return
true
Check this link to know more about Array.isArray
If your response is a string, you can use JSON.parse to turn it into an JS Object/Array.
var response = someAjaxStuff(...);
// response is a string
response = JSON.parse(response);
// now reponse is an Object/Array
If you use AJAX with jQuery, you can also use dataType:
$.ajax({
url: 'https://example.com/api/somejson',
dataType: 'json',
method: 'get',
success: function(res) {
// console.log res will be an object/array here.
}
});
But if you're writing your own API, I suggest you have to add the right header to tell browser that it is a JSON format instead of string.
For flask you can use jsonify (reference):
return jsonify(somedict)

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.

sending a 2d array jquery post to java servlet

I have some data that I need to send that is in a 2D array. I found that you send an array through post here
here but i need to send a 2D array from my javascript using post to a java servlet. Is there a way to do this?
You can use exactly the same technique as the example you link to. This is because it uses JSON to serialise the data, so it can send entire JS data structures in one go. So, taking the example, but rebuilding it for a 2d array and tweaking it to send actual JSON:
var obj=[ [1.1, 1.2], [2.1, 2.2], [3.1, 3.2] ];
$.ajax({
url:"myUrl",
type:"POST",
dataType:'json',
success:function(data){
// codes....
},
data:JSON.stringify(obj),
contentType: 'application/json'
});
Then this will send a string to your server, like:
"[[1.1,1.2],[2.1,2.2],[3.1,3.2]]"
Your Java servlet will then have to deserialise this and use it however you want. In this example, the JSON will be sent as RAW post data; if you want to get it via the request object, you can do something like:
var obj=[ [1.1, 1.2], [2.1, 2.2], [3.1, 3.2] ];
$.ajax({
url:"myUrl",
type:"POST",
dataType:'json',
success:function(data){
// codes....
},
data: {json: JSON.stringify(obj)}
});
Then you should be able to get the JSON string from:
request.getParameterValues("json");

Read json object

I'm having a problem reading JSON; my PHP server encodes an object created with the stdClass, then sends this object on my Ajax asynchronous script. I tried to alert the object and the
representation is like this:
alert(prova) //Gives {"idProva":"3","name":"test"}
Now if the variable name is prova, how can I read the value 3?
I tried using prova.idProva, but it doesn't work.
try parsing json into a object
var json = '{"idProva":"3","name":"test"}',
obj = JSON.parse(json);
alert(obj.idProva);
i hope this will help
In ajax all add dataType:'json'
$.ajax({url: '',
dataType: 'json',
type: 'GET',
success: function (prova) {
alert(prova.idProva);
}
);
This may help you,
var data = {"idProva":"3","name":"test"}
console.log(data['idProva']);

Building a json tree structure

I will be passing a json string to a servlet via an ajax request :
function add() {
$.ajax({
url: "pathToServlet" ,
dataType: "text",
data: ({
name : 'myJsonString'
}),
success: function(data) {
alert('returned!!');
});
}
To build up this json string I have a listener which when fired appends a new piece of json to string :
var json = "";
json += "{ new json ..... }"
Is this the correct way to build up the jSon String ? Should I be using jQuery methods to create a json object(if they exist) and add elements to it and then convert the json object to a string instead of creating the json string myself ?
What I would recommend doing is building up an object, and then when you're ready to send it to the server, serialize the object via JSON.stringify.
So for instance, you might have an object called data:
var data = {};
...to which you might periodically add properties:
data.foo = "bar";
data.stuff = {nifty: "stuff"};
Or perhaps data is an array:
var data = [];
...to which you add things:
data.push({nifty: "stuff"});
Then, when you're ready to send it:
function add() {
$.ajax({
url: "<%=savePortlet%>" ,
dataType: "text",
data: {
name : JSON.stringify(data)
},
success: function(data) {
alert('returned!!');
});
}
Because you're passing an object into ajax, you don't have to worry about URL-encoding the JSON string; jQuery will do it for you.
JSON.stringify is defined as part of ECMAScript5 and suppoted natively by many browsers, but of course many of us have to support outdated versions of browsers. In those cases, you can get a "JSON shim" to add JSON.stringify to an environment that doesn't have it. One of those is available from the originator of JSON, Douglas Crockford, on his github page.
If using jQuery you can use jquery-json, a really handy plugin to handle JSON with JavaScript and jQuery.
Usage:
var jsonString = $.toJSON(myObject);

Categories