passing json array ajax - javascript

Trying to pass a array using ajax call.
info = [];
info[0] = 'hi';
info[1] = 'hello';
$.ajax({
type: "POST",
data: {info: info, "action": "getPatientRecords"},
url: "/mobiledoc/jsp/ccmr/webPortal/carePlanning/servicePatientmilestoneModal.jsp",
success: function(msg) {
$('.answer').html(msg);
}
});
However when i try to catch it on the server side using :
request.getParameter("info"); //Displays null**
Also, if i wish to send an array of arrays ? is it possible?
I tried using serialize however my IE throws error that serialize : object doesnt support this property i Did include jquery lib.

You can use JSON.stringify(info) to create a JSON representation of the object/array (including an array of arrays). On the server side you should be able to get the string via getParameter and then unserialize it from JSON to create constructs JSP can use.

Yes,It is Possible to send arrays.
var info_to_send = ['hi','hello'];
$.ajax({
type: "POST",
data: {info: info_to_send, "action": "getPatientRecords"},
url: "/mobiledoc/jsp/ccmr/webPortal/carePlanning/servicePatientmilestoneModal.jsp",
success: function(msg) {
$('.answer').html(msg);
}
});

You can only provide strings in a request url.
You could encode the array like so:
info = JSON.stringify(info);
// results in "['hi', 'hello']"
Then send it to the server, also JSON parse on the server.
You will need to go to http://www.json.org/ to get a Java implementation of JSON parsing.

Related

In Javascript array there are items, but when I pass an array to an MVC Controller, list/array is empty

I'm using ajax POST method
to send objects stored in an array to Mvc Controller to save them to a database, but list in my controller is allways empty
while in Javascript there are items in an array.
here is my code with Console.Log.
My controller is called a ProductController, ActionMethod is called Print, so I written:
"Product/Print"
Console.Log showed this:
So there are 3 items!
var print = function () {
console.log(productList);
$.ajax({
type: "POST",
url: "Product/Print",
traditional: true,
data: { productList: JSON.stringify(productList) }
});}
And when Method in my controller is called list is empty as image shows:
Obliviously something is wrong, and I don't know what, I'm trying to figure it out but It's kinda hard, because I thought everything is allright,
I'm new to javascript so probably this is not best approach?
Thanks guys
Cheers
When sending complex data over ajax, you need to send the json stringified version of the js object while specifying the contentType as "application/json". With the Content-Type header, the model binder will be able to read the data from the right place (in this case, the request body) and map to your parameter.
Also you do not need to specify the parameter name in your data(which will create a json string like productList=yourArraySuff and model binder won't be able to deserialize that to your parameter type). Just send the stringified version of your array.
This should work
var productList = [{ code: 'abc' }, { code: 'def' }];
var url = "Product/Print";
$.ajax({
type: "POST",
url: url,
contentType:"application/json",
data: JSON.stringify(productList)
}).done(function(res) {
console.log('result from the call ',res);
}).fail(function(x, a, e) {
alert(e);
});
If your js code is inside the razor view, you can also leverage the Url.Action helper method to generate the correct relative url to the action method.
var url = "#Url.Action("Print","Product)";

How can I iterate this json?

"This" is what I retrieve from a server:
after an ajax call in jQuery:
$.ajax({
type: "POST",
url: URL + "/webservices/WS.asmx/MyFunction",
data: JSON.stringify({ "ID": ID }),
contentType: 'application/json; charset=utf-8',
success: function (json) {
},
error: function (jqxhr, text, error) {
}
});
and I want to iterate the items inside data (which is an array). Tried with:
for (i in json.data) {
var feed = json.data[i];
console.log(feed.message);
}
but it prints nothing. Where am I wrong?
If what you've shown is really what you're getting in your success method, you have an object with a property, d, which contains a JSON string. You can parse it like this:
success: function(response) {
var data = $.parseJSON(response.d).data;
// use the data, which is an array
}
From your comment below:
But why I need to use $.parseJSON? Can't just manage it with the request? dataType for example, but still not works.
You don't need dataType, it would appear the server is returning a correct MIME type and so jQuery is already handling the first level of parsing (deserialization) correctly.
Whatever is sending you the data appears to be sending it double-encoded: First it encodes the array, then creates an object and assigns the array to it as a data property, serializes that object to JSON, then puts that string on a d property of another object, and serializes that. So although jQuery is automatically handling the first parsing (deserializing) step for you, it doesn't know about the need for the second one. I suspect you can fix this at the server level; you might want to post a separate question asking how to do that.
From your further comment:
It retuns from a .NET webservice method. I download the JSON from Facebook, after a call. And I store it inside a json variable. Then I just return it as string. I think webservice serialize that already serialized json, right?
Ah, so that's what's going wrong. You have three options:
Keep doing what you're doing and do the explicit $.parseJSON call above.
Do whatever you need to do in your web method to tell it that you're going to send back raw JSON and it shouldn't encode it; in that case, jQuery will have already parsed it for you by the time you receive it in success and you can drop the parseJSON call.
Parse the string you get from Facebook, then put the resulting array in the structure that your web method returns. Then (again) jQuery will parse it for you and you can use response.d.data directly without further parsing.
As #T.J.Crowder has pointed out your problem is related to the way you serialize your data on your backend, which is not a good practice to send the json as a string, in a real json object.
you should do it like:
success: function (json) {
var jsonObject = JSON.parse(json.d);
//then iterate through it
for(var i=0;i<jsonObject.data.length;i++){
var feed = jsonObject.data[i];
console.log(feed);
}
},
The point is using for(var key in jsonObject.data), is not safe in JavaScript, because additional prototype properties would show up in your keys.
Try using
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(i+" "+feed);
}
where
i = Key &
feed = value
I assume json is an object not string and already converted to json object. Also used json.d.data not json.data
use var in for loop and print feed not feed.message:
for (var i in json.d.data) {
var feed = json.d.data[i];
console.log(feed);
}
because I can not see {feed:{message:''}} there

Why can I not parse json string using jQuery.parseJSON(json)?

I am trying to parse a response of a string which is a json string. In another page of my web app following code is working fine. but its not working for my current page i am working with. Following is the code:
$.ajax({
type: 'POST',
url: 'http://mywebapp.com/sendnames',
data: {},
success: function(result) {
alert('result: '+result);
var obj = jQuery.parseJSON(result);
alert('obj: '+obj);
// doing rest of stuff
}
});
first alert comes and shows right result. result is:
[
"Richard",
"Eric",
"John"
]
but second alert does not come.
i checked it, its a valid json. why can not i parse this json with jQuery.parseJSON(). Thanks in advance.
Try to add return type: dataType : json
$.ajax({
type: 'POST',
url: 'http://mywebapp.com/sendnames',
data: {},
dataType:'json',
success: function(result) {
console.log('result: '+result);
// doing rest of stuff
}
});
"json":
Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
"jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true.
http://api.jquery.com/jQuery.ajax/
Replace $.ajax by $.getJSON. This is guaranteed to trigger $.parseJSON internally, so result will already be the desired JS object.
$.getJSON({
type: 'POST',
url: 'http://mywebapp.com/sendnames',
data: {},
success: function(obj) {
alert('obj: '+obj);
// doing rest of stuff
}
});
Try with adding dataType:'text', it will return string as result. and your code will run as you expect.
See the accepted answer here
You're parsing an object. You parse strings, not objects;
jQuery.parseJSON only takes strings.
Because $.ajax already parsed the data, result is Javascript object not a string. parseJSON expects a string parameter.
FROM DOCS (more on .ajax() data types here):
The json type parses the fetched data file as a JavaScript object and
returns the constructed object as the result data. To do so, it uses
jQuery.parseJSON() when the browser supports it; otherwise it uses a
Function constructor
.

pass array and individual string to php file using ajax call

I try to implement the following code
var flag = new Array();
var name = $("#myselectedset").val();
$.ajax({
type: 'post',
cache: false,
url: 'moveto.php',
data: {'myselectset' : name,
'my_flag' : flag
},
success: function(msg){
$("#statusafter").ajaxComplete(function(){$(this).fadeIn("slow").html(msg)});
}
});
You can see that the name is a single string and the flag is an arry, am I using the right format for passing them throw ajax call, anyone could help me, thanks
It is impossible to pass arrays in a POST request. Only strings.
You will either need to stringify your array, or consider posting as JSON instead.
You should be able to do something quite simple, like replace your "data" property with:
data : JSON.stringify( { myselectset : name, my_flag : flag } )
That will convert the data into a JSON string that you can turn into PHP on the other side, using json_decode($_POST["my_flag"]);
Very important note:
For JSON.stringify to work, there can't be any functions in the array - not even functions that are object methods.
Also, because this is a quick example, make sure that you're testing for null data and all of the rest of the best-practices.

How to pass a nested JavaScript object to ASP.NET MVC Action Method?

I would like to pass a nested JavaScript object to my ASP.NET MVC Action Method.
Here is the code(simplified):
$.getJSON('some/url',
{
index: pageIndex,
pageSize: pageSize,
filter:{one:'one',two:'two',three:'three'}
}, someCallBack(msg)
);
I'm using jQuery and implemented my plugin which lazily fetches paginated data from the server. It works all charm but now I need to pass a JavaScript Filter object with a variable number of properties-filters. On the server-side, I get an object array where the first item is a string, containing the [Object object] literal.
Obviously, my nested object (filter) is not being expanded and transformed into an object (hash) on the server-side. Is this possible at all?? I don't want to hard code my filters, since the plugin is meant to be universally applied.
Thank you very much.
You can use System.Web.Script.Serialization.JavaScriptSerializer to send/receive JSON serialized data:
JavaScriptSerializer js = new JavaScriptSerializer();
Filter f = js.Deserialize<Filter>(json_str);
More details here. To encode the JSON data to send to the server, use a JSON serialization library for JavaScript like json2.js. Then send the query like this:
var filter = {field1: 'value1', field2: 'value2'}
$.ajax({
type: "POST",
url: '/server/path',
data: { filter: JSON2.stringify(filter) },
dataType: "json",
success: function(data) {
// do something
}
});
JSON would be perfect for this. Basically, you'll want to convert your object to it's JSON representation and then send that across the wire. Once it's available on the server, you can process it however you like.
Crockford has a great article on what JSON is, how to understand the notation, and he provides a tool to convert your objects to JSON notation.
You can use the following js lib json2 library, you can then use the stringify method to ensure your json is in the correct format for the service.
var data0 = {one:'one',two:'two',three:'three'}
var json = JSON2.stringify(data0 );
$.ajax({
type: "POST",
url: someServiceUrl,
data: json,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
}
});

Categories

Resources