Passing Javascript Object Array to MVC Controller w/ POST - javascript

So I have an array of javascript objects that is constructed using JQuery across multiple table rows. It has the following form:
obj_rows = [
{"param1":value11, "param2":value12, "param3":value3},
{"param1":value21, "param2":value22, "param3":value23},
//more objects with the same parameters
]
What I would like is a way for an AJAX POST request to a Controller method SomeController/SomeAction that takes in this array and can iterate over all objects. I was trying to figure out a way to do this using JSON, but to no success.
NOTE: Even though I am using MVC, I do not have a model class corresponding to these objects. Ideally, I would like to end up with some structure like a List of 3 Tuples.

actually the solution is to take the object and stringify it into a string and then send it over the ajax request.
just do:
JSON.stringify(obj_rows)
and you will get on the other endpoint an array (stringified of course), you have to parse it back and you will have your array.

You can use javascript method JSON.stringify() to convert you object into a string and assign its result to a hidden field in your view and once you recieve this in your controller you can then deserialize it to an object or parse it yourself.

Related

Converting JS object to json string using JSON.stringify

I have four textboxes which contain json string which I create by calling json.stringify on various js objects..
eg. '["users.name","users.username"]' (This is the value of one textbox)
What I want to do is create a single json string from these four json strings and send them to the backend using POST..
So I create a object and add them like this
tmp = {}
tmp["columns"] = $("#sc").val();
/*adding more data....*/
$.ajax("/api/backend", {
data: JSON.stringify(tmp),
/* more ajax code...*/
});
The data that gets sent is of the following format..
{"columns":"[\"users.name\",\"users.username\"]"}
This is not a string but a json object...
Now when I do the following..
tmp1= JSON.stringify(tmp)
and Post using..
$.ajax("/api/backend", {
data: JSON.stringify(tmp1),
/*more code below..*/
The data that gets sent is of the following format and is string..
"{\"columns\":\"[\\\"users.name\\\",\\\"users.username\\\"]\"}"
This string has a lot of '\' characters which needs to be taken into account in the backend.
Is this the right way of handling my problem or am I doing something wrong?
Thanks
It depends on what you are trying to achieve.
If you want to send to the server a JSON that combines all JSON in your inputs, you'd better parse the JSON in your inputs, prior to adding them to you tmp object. That way, you get an object containing objects, rather than an object containing JSON strings.
Retrieving JSON from inputs would be like this:
tmp["columns"] = JSON.parse($("#sc").val());
See that you are storing objects within your tmp object, rather than JSON strings. Then, you can just send that object as JSON to your server.
Thus, your server would receive this:
"{\"columns\":\"[\"users.name\",\"users.username\"]\"}"
Which, I believe, looks much better. I hope that helps.

how to send string array as a response to ajax call from servlet

I made a ajax call from my jsp to servlet. when I want to return string then it is working fine. But I want to send response as a String array then its not working. Is it possible that I can send string array from servlet as a ajax response.
String[] roleAccess=null;
response.setContentType("text/html");
try{
roleAccess=new String[23];
roleAccess[0]="";
roleAccess[1]="checked";
roleAccess[2]="";
response.getWriter().write(roleAccess.toString());---this part I need to change.
Send the ajax response in json format by encoding the array in json and return it.
You can use Gson and then encode your array like:
String jsonRoleAccess = new Gson().toJson(roleAccess, roleAccess.class);
response.getWriter().write(jsonRoleAccess);
// OR do a one liner:
response.getWriter().write(new Gson().toJson(roleAccess, roleAccess.class));
And on the Javascript end, you can access it as a json object
// Assuming you've read the ajax response into var roleAccess
var checked = roleAccess[1];
You want to marshall the array as a JSON data type. The format returned by Java's array class is not in a format that JavaScript understands.
You should also wrap your array inside of an Object because of a security issue of passing top-level arrays back as JSON.
See Why are top level json arrays a security risk
Write it out to JSON instead. Javascript can't understand the result of a Java array's toString() method ([Ljava.lang.String;#5527f4f9), but I know it can understand JSON.
If you're only ever going to be using a string array and you don't want to use any more libraries:
public static String toJSON(String[] array)
{
String json = "[\"";
for (String s : array)
{
json += s + "\",\"";
}
return json.substring(0, json.length() - 2) + "]";
}
Depending on what Javascript framework you're using on your client-side, your JSON will be available as the xmlHttpRequestObject.responseText. AngularJS stores it in the $http.get().success method's first data parameter. jQuery stores it in the $.ajax({success}) method's first data parameter. Angular and jQuery automatically validate and eval it to an [object Object] for you, but xmlHttpRequestObject.responseText doesn't.

Passing JavaScript array to input in PHP

I'm trying to pass an array from JavaScript to a PHP input. I want to pass my array as an array inside my input, not a string.
My array is this:
["0_1","0_2"]
And this is how I pass my array to my input:
$('#movefile_id').val(JSON.stringify(allfiledata));
Can I pass the array to the input file without making it a string?
read this:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
you can convert your array to JSON
var arrayJavascript = JSON.stringify(["0_1","0_2"]);
and with PHP, read this:
http://php.net/manual/es/function.json-decode.php
$arrayPHP = json_decode($_POST["arrayJavascript"]);
Here is the step by step process given below
1- Covert the Javascript Array to JSON
2- Post that JSON string to PHP using jquery post or jquery get
This is possible through only using Ajax. Because javscript is a Client side language and PHP is a server side language.We can only connect both using Ajax.

js get elements from array of a serialized form object

Im using JS for a quick web form, all is working fine, I place the responses of the form in a serialized js object into an array,
var myCars = new Array($('#popup-form').serialize());
console.log(myCars);
which gives me on the console:
["name=asfe&email=juan234%40gmail.com&phone=&password=&options=discuss-offer&other=", $family: Object, each: function, clean: function, associate: function, link: function…]
so the question is, this is not behaving like a normal array?
is the array the best way to take the elements?, I tried with mycars[0], but is not working,
Im just coming back to JS!, what is missing to get the elements for the form?, thanks!
jQuery has a serializeArray() method as well.
The .serializeArray() method creates a JavaScript array of objects,
ready to be encoded as a JSON string. It operates on a jQuery object
representing a set of form elements.

Function to convert GridView and Repeater in a JSON string

I need a JavaScript function which will take the ASP.NET Repeater as input. The function must then parse through the object and return the data in the rows of the object as JSON.
Then, I can send the JSON back to the server to be interpreted/parsed and saved to the DB.
your best bet is probably traversing the elements rendered by the Repeater and gathering the values into a javascript object. when you have that you can use json2's stringify() or jquery's serialize() or something similar to produce a json representation.

Categories

Resources