Ajax post request string data instead of object - javascript

Similar to this question I need to send a string as data in a post request.
Unlike that one, I can't use an object because I have repeated items. As you can see in my sample data sn1, sn2 and sn3 are repeated several times on different datetimes.
Sample data:
&sn3=2013-2-4T12:43:52&sn3=2013-2-4T12:43:55&sn1=2013-2-4T12:43:59&sn1=2013-2-4T12:44:0&sn2=2013-2-4T12:44:0&sn3=2013-2-4T12:44:2&sn2=2013-2-4T12:44:3&sn3=2013-2-4T12:44:19&sn3=2013-2-4T12:44:19&sn3=2013-2-4T12:44:19&sn2=2013-2-4T12:44:19&sn3=2013-2-4T12:44:21&sn2=2013-2-4T12:44:22&sn2=2013-2-4T12:46:39&sn3=2013-2-4T12:46:42&sn2=2013-2-4T12:46:44&sn2=2013-2-4T12:46:45&sn2=2013-2-4T12:46:46&sn2=2013-2-4T12:47:27&sn2=2013-2-4T12:47:27&sn2=2013-2-4T12:49:44&sn2=2013-2-4T12:50:21&sn2=2013-2-4T12:52:21&sn2=2013-2-4T12:52:24&sn2=2013-2-4T12:57:35&sn3=2013-2-4T12:57:38&sn3=2013-2-4T12:57:39&sn2=2013-2-4T12:57:39&sn2=2013-2-4T12:57:40&sn3=2013-2-4T12:57:46&sn3=2013-2-4T13:21:30
I tried using the following
console.log(screens); //logs my sample data posted above.
$.ajax({
url : url,
type: "POST",
dataType : 'text',
data : screens,
success : function(data) {
console.log("sucessfull sending:")
console.log(data);
},
error : function() {
console.log('failed');
}
});
But it always triggers failed.
Can I send it as a string? If not, how can I send multiple items with the same key?

console.log(screens); //logs my sample data posted above.
$.ajax({
url : url,
type: "POST",
dataType : 'text',
data : {screens:screens},
success : function(data) {
console.log("sucessfull sending:")
console.log(data);
},
error : function() {
console.log('failed');
}
});
See data : {screens:screens},, if you do something like that, on server you will be able to get it like: screensString = Request["screens"]. After that, screensString will contain a single string with all screens.

When you don't specify contentType in the ajax options, your request will default to 'application/x-www-form-urlencoded; charset=UTF-8'.
However, when your post data is just text, you should make the server aware of that fact by specifying a contentType 'text'.
As opposed to the contentType, the dataType specifies the type of response data that you expect back from the server.

I think what you need is to use [] in your parameters.
instead of sending &sn3= multiple times (which is rewriting itself) send it as an array like this &sn3[]=
if you are getting this data from an form input use name="sn3[]" and if this is the case, I would recommend you use $('#yourform').serialize() as data sent

Related

Issue posting a large amount of data when using json in a query string

I'm posting four JSON objects to the server using a jQuery ajax request. Each object can be up to 30k characters. When all of the parameters are large the last parameter or even the last two parameters do not show up on the server. Everything works fine when the parameters are smaller though.
In chrome's network tab I see all of the parameters in their entirety. In fiddler I see the parameters in their entirety but the parameters that don't show up on the server will not have a name.
Fiddler
The structure of my request is as follows:
var formData = "json0=" + JSON.stringify(json0) + "json1=" + JSON.stringify(json1); //etc
$.ajax({
type: 'POST',
url: url,
data: formData,
success: function (result) {},
error: function() {}
});
I wouldn't think there would be a limit on a POST but it's acting like the data is being truncated for some reason. Server side I'm in Java using ParameterAware to retrieve the data but I think the issue is before it gets there since fiddler doesn't have the parameters' names.
Query strings are not made for large amounts of data, you should pass your data to your Ajax call in an object:
$.ajax({
type: 'POST',
url: url,
dataType: "JSON",
data: {
json0: json0,
json1: json1
// etc
},
success: function (result) {},
error: function() {}
});
Have a look at this article discussing the maximum length of query strings.
jQuery AJAX documentation: http://api.jquery.com/jQuery.ajax/

POSTing JSON data to Server URL

I am facing problem when I am posting a JSON data to the server using Ajax call in jQuery the function does not enter success mode. When I post using the POSTER Plugin of Firefox it gets posted successfully. Sharing the code snippet and screenshot of the same:
function showSubscribeContent()
{
alert("*1*------- SUB CLICKED");
var myJSONData = '{"data":{"mode" : "subscribe","technologyareas":[1],"assettypes":["podcast","documents"]}}';
alert("*2*------- POSTING--------->"+myJSONData);
$('#subscribePage').html('<h1>POSTING...</h1>');
$.ajax({
type: 'POST',
url: 'https://tt.s2.acc.com/tt/subscribe-service/uid=sagar_mate',
data: myJSONData,
dataType: 'application/xml',
success: function(data) {
alert("*3*------- POSTED SUCCESSFULLY TO THE SERVER");
$('#subscribePage').html('<h1>POSTED</h1>');
} // Success Function
}); // Ajax Call
}
I am getting alert number 1 and 2 but not 3.
Also when I post using POSTER plugin of Firefox, it gets posted easily.
The Response is success.
I am unable to post the same data using AJAX call.
Thanks,
Ankit
Unless and until the URL in your AJAX call is of the same Domain, I don't think it will get posted successfully. POSTER plugin of Firefox doesn't put any such restriction on the domain, but browser will put this restriction on the application.
Try checking in the error: function(){alert(4);}
to see if it reaches the error handler atleast
Please clearify what you want, when using POSTER Plugin of Firefox you have specified datatype as json where as when using ajax you are using xml.
If you what to post data as JSON use JSON.stringify which accepts JSON object and convert it to string.
Try with this code
function showSubscribeContent()
{
alert("*1*------- SUB CLICKED");
var myJSONData = {"data":{"mode" : "subscribe","technologyareas":[1],"assettypes":["podcast","documents"]}};
alert("*2*------- POSTING--------->"+myJSONData);
$('#subscribePage').html('<h1>POSTING...</h1>');
$.ajax({
type: 'POST',
url: 'https://tt.s2.acc.com/tt/subscribe-service/uid=sagar_mate',
data: myJSONData,
dataType: 'application/json',
success: function(data) {
alert("*3*------- POSTED SUCCESSFULLY TO THE SERVER");
$('#subscribePage').html('<h1>POSTED</h1>');
} // Success Function
}); // Ajax Call
}
Here I have changed the following lines
Converted myJSONData to a JSON object from string
var myJSONData = {"data":{"mode" : "subscribe","technologyareas":[1],"assettypes":["podcast","documents"]}};
Note: try with the string(the way you were doing) if this is not working for you
Changed datatyle to JSON
dataType: 'application/json',
Adding a header in beforeSend Function worked fine for me. Security reasons of CORS.

Post JSON string made from JavaScript array to server with jQuery [duplicate]

Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

javascript json request with some parameters

So a simple question:
JavaScript needs to send to server that request:
myserver/scipt.php?LANG=EN&AGENT={"Login":{"name":"user","pass":"user"}}
How I need to form url and data in Ajax?
Is this right?
var formData = {
"login":$("#field1").val(),
"pass":$("#field2").val()
};
$.ajax({
url:'http://myserver/scipt.php?LANG=EN&',
type:'GET',
data:'AGENT=' + $.toJSON(formData),
success: function(res) {
alert(res);
}
});
Thank you!
I'd recommend sending JSON via POST instead of GET. GET has some limitations that you want to avoid.
A part from that, yes, your code seems ok.
EDIT:
Sorry, your code is not ok.
Change the data line to:
data: $.toJSON(formData),
You need to send the data to the server in the form of a map ..
Your data is already in json format.. You need not do $.toJSON again
Instead of
data:'AGENT=' + $.toJSON(formData),
send it this way
data:{ 'AGENT' : {'Login' : formData } },
You need to URL encode any strings you want to pass through Ajax.
If jQuery works anything like a normal form, you also need to put all your query string data into data to avoid the existing query string being destroyed.
url:'http://myserver/scipt.php',
type:'GET',
data: {
"AGENT": $.toJSON(formData),
"LANG": "EN"
},
Note, you should use POST requests if you are transmitting user credentials. You don't want them cached or stored in server access.log files.

How to send JSON instead of a query string with $.ajax?

Can someone explain in an easy way how to make jQuery send actual JSON instead of a query string?
$.ajax({
url : url,
dataType : 'json', // I was pretty sure this would do the trick
data : data,
type : 'POST',
complete : callback // etc
});
This will in fact convert your carefully prepared JSON to a query string. One of the annoying things is that any array: [] in your object will be converted to array[]: [], probably because of limitations of the query sting.
You need to use JSON.stringify to first serialize your object to JSON, and then specify the contentType so your server understands it's JSON. This should do the trick:
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
contentType: "application/json",
complete: callback
});
Note that the JSON object is natively available in browsers that support JavaScript 1.7 / ECMAScript 5 or later. If you need legacy support you can use json2.
No, the dataType option is for parsing the received data.
To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.
$.ajax({
url: url,
type: "POST",
data: JSON.stringify(data),
processData: false,
contentType: "application/json; charset=UTF-8",
complete: callback
});
Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"
Original post here
Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

Categories

Resources