What is the best strategie to send complex data with ajax - javascript

I have some informations in a form to send to the server as a (complex) array (or Object if you prefer) with JS/jQuery. (jQuery 1.7.2)
I'm thinking about JSON to solve the problem smartly. My code works right now, but i want to know if its possible to do it better.
So this example is pretty typical (The data are more complex irl) :
dataSend = { 'id': '117462', 'univers': 'galerie', 'options' : { 'email': 'hello#world.com', 'commenataire': 'blabla', 'notation' : '4' } };
$.ajax({
url: "/ajax/ajaxMavilleBox.php",
data: JSON.stringify(dataSend),
success: function(x){
smth();
}
});
In an another context, i have to make the exact same thing without JSON.
With the same example :
dataSend = { 'id': '117462', 'univers': 'galerie', 'options' : { 'email': 'hello#world.com', 'commenataire': 'blabla', 'notation' : '4' } };
$.ajax({
url: "/ajax/ajaxBox.php",
data: $.param(dataSend),
success: function(x){
smth();
}
});
Obviously, I missing something.
The url is :
http://www.mywebsite.com/ajax/ajaxBox.php?id=117462&univers=galerie&options=%5Bobject+Object%5D
And the url should be :
http://www.mywebsite.com/ajax/ajaxBox.php?id=117462&univers=galerie&options[email]=hello#world.com&options[commenataire]=blabla&options[notation]=3
There is any easy way to do it (I hope I don't have to edit the data myself in a loop or something)
Edit : Solution for the second part
Ok, the last part without JSON is correct. In fact, i was using an older version of jQuery in my page.
$.param is not so good with jQuery < 1.4
More information here Param Doc

I would suggest setting the type: 'POST', otherwise you will have a data limit eqvivalent of the browsers query string length.
If you use the post method, you should send the data as a json-string. Something like:
data: { DTO: JSON.stringify(dataSend) }
You need to use json2.js if window.JSON is undefined (like in ie7 for example).
If you are using PHP on the serverside, you can fetch the object using:
$data = json_decode($_POST['DTO']); //will return an associative array
or ASP.NET
public class DataSctructure
{
public string id { get; set; }
public string univers { get;set; }
//etc...
}
var data = HttpContext.Current.Request.Form['DTO'];
DataSctructure ds = new JavaScriptSerializer().Deserialize<DataSctructure>(data);
//properties are mapped to the ds instance, do stuff with it here

as mentioned by #Johan POST shouldbe used here instead of GET
you can view data you are sending by using the Developer options in the browser you are using just press f12
also make sure you are using jquery >= 1.4
the incorrect serialized string in the url is the way that $.param() used to serialize prior to 1.4 version

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)";

Accessing an array sent using JSON

I am having following array
var array = []; // It has (48.154176701412744,11.551694869995117),(48.15131361676726,11.551694869995117),(48.15555092529958,11.549291610717773) saved in it.
And thats how I am sending it via ajax to my aspx page
function result() {
var jsonText = JSON.stringify({ list: array });
$.ajax({
url: "test.aspx/Demo", type: "POST", dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonText,
success: function (data) { alert("it worked"); },
error: function () { alert("Uh oh"); }
});
return false;
}
And thats how I am accessing it in my aspx
public static void Demo(double[] list)
{
}
But when I try to print it, it gives me "0 0 0". And when I try to access it like
public static void Demo(string[] list)
{
}
The above method doesn't even accepts JSON object. So, what should the appropriate data type be used to access this array as the method doesn't even accept the JSON object? Or tell me the way to split string like (xyz,xyz),(xyz,xyz) in JS, so that I can convert it into string and sent it with JSON as a string?
My guess would be the parameter that you are accepting for your web method is of incorrect type. Change the parameter type for your web method to List<Dictionary<string,string>>, that way most objects would be deserialized correctly, especially if it is a JSON type like in your example.
Having no experience in the Google maps API yet, a quick search revealed that it might look something along these lines:
var coord = { "lat" : "xx.xxxxxxx", "long" : "yy.yyyyyyyy" };
If that is indeed the case, a parameter of type List<Dictionary<string,string>> would correctly deserialize the JSON array you are passing through the AJAX call.
Below is a sample of how to loop through the list provided to your web method and build a string of all the coordinates:
StringBuilder sb = new StringBuilder();
foreach (Dictionary<string, string> coord in list)
{
sb.Append(string.Format("({0},{1})", coord["lat"], coord["long"]));
}
You can, of course, change the format in which the string is built up to suit your requirements. Again, the assumption is that the dictionary gets deserialized with keys for "lat" and "long", of which I'm not sure. Hope it helps!
change your array with this
var array = [[48.154176701412744,11.551694869995117],[48.15131361676726,11.551694869995117],[48.15555092529958,11.549291610717773]];
hope this will help

Is this jQuery AJAX post saving data incorrectly?

$.ajax({
type: 'POST',
url: '/users',
data: {
_method : 'PUT',
user : {
guides : {
step1 : true,
step2 : true
}
}
}
});
Is this saving correctly? I want this json data in a rails serialized field but It's saving incorrectly as follows below which is causing errors.
User.guided:
--- "{\"step1\"=>\"true\", \"step2\"=>\"true\"}"
Then when I do the following in the rails view:
guides = [<%= current_user.guides.try(:html_safe)%>];
It outputs with => instead of the expected :.
First of all you could try to use JSON.stringify() otherwise jQuery will use $.param() to serialize your data. But your main issue is that you want a JSON string, and not the YAML that is generated. As far as I now something like
guides = [<%= current_user.guides.to_json %>];
should do the trick. Also, maybe I'm not 100% sure but you probably don't need to use html_safe on this, because it's already escaped, although can't tell how it will be rendered in view

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.

Send complex JavaScript object to ASP.Net MVC Action

This seems to be quite a common theme and a few people have given some very constructive answers, but I'm still struggling to get my attempt to work.
The problem is much the same as this one for example, except that I'm only trying to send a single complex object instead of an array.
My controller looks like this:
[AcceptVerbs (HttpVerbs.Put)]
[Authorize]
[JsonFilter(Param="Designer", JsonDataType=typeof(Designer))]
public JsonResult SaveProfile(Designer Profile)
{
ProfileRepository Repo = new ProfileRepository();
Designer d = Repo.GetById(Profile.ID);
d.Comments = Profile.Comments;
d.DisplayName = Profile.DisplayName;
d.Email = Profile.Email;
d.FirstName = Profile.FirstName;
d.LastName = Profile.LastName;
Repo.Update(d);
return Json(Profile);
}
The code for retrieving the page data and posting it looks like this:
$('#save-profile').click(function () {
var Profile = {};
var context = $('#profile-data')[0];
$('span', context).each(function () {
Profile[this.id] = $(this).text();
});
Profile.ID = $('h3', context).attr('id');
console.log(Profile);
//var DTO = { 'Profile': Profile };
$.ajax({
type: "PUT",
url: "/Home/SaveProfile",
data: { 'Profile': Profile },
success: function (data) {
console.log(data);
}
});
});
The object is being correctly created and posted to the server (I've tried using POST and PUT, by the way), the server appears to be receiving an object instance, but the properties are - as usual - all null.
What am I missing? I've tried using the approach (adapted) from the example question linked above, but still don't seem to be getting any closer to the solution. Any help appreciated.
As it turns out, there's nothing wrong with the ActionResult method itself and neither is there any issue with the JavaScript object or Ajax post. The problem actually lies in the custom filter that decorates the ActionResult and the parameter being set for its param value.
The following attribute has a parameter of "Designer" set for the name of the parameter I'm trying to pass in. I've supplied this as both the parameter name and the type.
[JsonFilter(Param="Designer", JsonDataType=typeof(Designer))]
The correct version should be:
[JsonFilter(Param="Profile", JsonDataType=typeof(Designer))]

Categories

Resources