Reputation: 7798
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?
Upvotes: 3
Views: 6222
Reputation: 712
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
Upvotes: 1
Reputation: 4015
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.
Upvotes: 1
Reputation: 12815
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.
Upvotes: 2