Function to convert GridView and Repeater in a JSON string - javascript

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.

Related

Passing Javascript Object Array to MVC Controller w/ POST

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.

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.

How should i save the response data in a object(json) to have better manipulation and performance?

what i am doing is:
1. Get values from ajax response(which is in json format) for listing rows of data which
response = {"categories":[{"name":"General","id":"6305","pop":"show when clicked"},{"name":"Navigation","id":"6043","pop":"show when clicked"},{"name":"New","id":"6051","pop":"show when clicked"},{"name":"Time","id":"6117","pop":"show when clicked"},{"name":"Reesh","id":"6207","pop":"show when clicked"}]}
2 . I will parse the json and store in a object like this
ex:
object= {6305:{"name":"General","id":"6305","pop":"show when clicked"},
6043:{"name":"Navigation","id":"6043","pop":"show when clicked"},
6051:{"name":"New","id":"6051","pop":"show when clicked"},
6117:{"name":"Time","id":"6117","pop":"show when clicked"},
6207:{"name":"Reesh","id":"6207","pop":"show when clicked"}};
why i am doing this is because i can get the data using the id
ex: object[6305] will give me the data.
3 .So that i can retrieve the data and also make changes to values in the object using the id when changes occur in db.
ex: object[6350].pop="changed";
Please tell me:
-->whether is this the correct method or i can do it in a much simpler or efficient way?
-->whether i can store the json response as it is and parse data as it is? if so please explain with example.
Yes, of course you would not need to build the object:
function getObject(id) {
for (var i=0; i<response.categories.length; i++)
if (response.categories[i].id == id)
return response.categories[i];
return null;
}
However, if you often need to access objects by their ids this function would be slow. Creating the lookup table as you did will not create much memory overhead, but make retrieving data much faster.
BTW: Your title question "save data as object or json" is confusing. Serializing manipulated objects back to JSON makes no sense, as you always will use the parsed objects. Of course, if you just needed to manipulate a JSON string, and knew exactly what to do, (simple) string manipulation could be faster than parsing, manipulating and stringifying.

Categories

Resources