jquery not posting array data - javascript

ive tried 10 different solutions to this issue on stackoverflow and none of them work, heres the issue, i need to post a array via ajax to a url
simple right?
the array comes from post values like this $_post[xxx] which i store in a var.
i mocked up a js function, that has the same error, instead of passing the array i just included as a var in the function, problem is the data is not gettin posted to the url.
pastebin link: http://pastebin.com/8ivWqJ8g
function generateImage() {
var Imagedata = [];
Imagedata['id'] = 1;
Imagedata['type'] = 'some type';
var url = '';
$.ajax({
url: url,
processData: false,
dataType: 'JSON',
data: JSON.stringify(Imagedata) ,
method:'POST',
async: false
});

Named properties of arrays do not get serialised when you convert the data to JSON.
Arrays are supposed to hold an ordered set of values, not an arbitrary set of name:value pairs.
Use a plain object ({}) not an array.
Asides:
Don't use processData: false unless you are passing something that isn't a string or an object to data (e.g. a FormData object). Since you are passing a string, it is harmless, but pointless. If you were passing an object (which you probably should be, see below), it would break things.
Don't use async: false. It is deprecated, and harms the user experience (since it locks up the JS thread until the response arrives).
If you want to populate PHP's $_POST then don't format your data as JSON. Pass the object directly to data: without using JSON.stringify.
If you do want to make a JSON formatted request, then don't forget to set the contentType.
function generateImage() {
var Imagedata = {
id: 1,
type: "some type"
};
var url = '';
$.ajax({
url: url,
dataType: 'JSON',
data: Imagedata,
method: 'POST'
});
// or …
$.ajax({
url: url,
dataType: 'JSON',
contentType: "application/json",
data: JSON.stringify(Imagedata),
method: 'POST'
});
}

data should be an Object like this:
$.ajax({
url: 'http://...',
dataType: 'JSON',
data: {id: 1, type: 'some type'} ,
method:'POST',
async: false
});

Related

Sending empty array to webapi

I want to POST an empty javascript array [] to webAPI and have it create an empty list of integers. I also want it so if I post javascript null to webAPI that it assigns null to the list of integers.
JS:
var intArray = [];
$.ajax({
type: 'POST',
url: '/api/ListOfInts',
data: {'' : intArray},
dataType: 'json'
});
c# webapi
[HttpPost]
public void ListOfInts([FromBody]List<int> input)
Problem 1) Jquery refuses to send data {'' : []} as the post payload. As soon as I add something in the array it works such as {'' : [1,2,3]}
Problem 2) Passing empty js array to controller gives null Based on what i read even if I do get it to post an empty array, it will initialize the list as null. Discussed solutions have it so that the list is always initializes as empty but I don't want that. I want it to be null in some case (when null/undefined is sent to it) and when [] is sent it should initialize as empty.
Edit: See https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-1 about why I am using {'' : []}
Use JSON.stringify(intArray) and contentType: 'application/json' works for me:
$.ajax({
url: "/api/values",
method: "POST",
contentType: 'application/json',
data: JSON.stringify([])
});
$.ajax({
url: "/api/values",
method: "POST",
contentType: 'application/json',
data: null
});
$.ajax({
url: "/api/values",
method: "POST",
contentType: 'application/json',
data: JSON.stringify([1, 2, 3])
});
data: {'' : intArray},
a blank key name is not allowed in JSON.
Just send the array itself.
data: intArray,
1. Use JSON.stringify() to convert javascript object to JSON string.
2. Use contentType: 'application/json' as it is correct MIME media type for JSON. What is the correct JSON content type?
3 dataType is not necessary
data: JSON.stringify(intArray),
contentType: 'application/json'

How to transfer json string to another page using jquery's ajax method?

I have a JSON string (stringified array of objects in javascript) which i intend to post to another page and then retrieve it from the $_POST variable. I used json =JSON.stringify(array).
The result gave me the following string
json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}]
Now I use
$( "#other").click(function() {
$.ajax({
url: 'some.php',
type: 'POST',
data: { kite : json}
});
On the page some.php I use
$kite=json_decode($_POST['kite'],true);
print_r($kite)
But nothing shows up. I have read many links on this topic and tried adding ContentType,dataType,processData parameters to the $.ajax() function but nothing helped.
What about this:
$( "#other").click(function() {
var json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
,{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}];
$.ajax({
url: 'test.php',
type: 'POST',
data: "kite=" + JSON.stringify({ kite : json }),
success: function(msg){
alert(msg);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
And on your php code:
<?php
$obj=json_decode($_POST['kite']);
print_r($obj->{'kite'});
?>
Not in an elegant way on passing the json..
but this way you can still capture "kite" as post variable and decode your desired json string.

JavaScript array getting encoded when posting jQuery

I'm trying to post part of my Knockout viewmodel to our server using jQuery.Ajax.
When I build the data object it looks fine in the console, but when it gets sent via the jQuery Ajax Post the array within gets encoded. The results on the other end are readable by the server, so it works, but it disturbs me greatly (the payload is bigger for one thing).
Here's the code:
var items = $.map(self.Items(), function (item) {
return item.Key() ? {
Key: item.Key(),
PromoCode: item.PromoCode,
Qty: parseInt(item.Qty(), 10)
} : undefined;
}),
data = {
"InEditMode": true,
"Items": items
};
$.ajax({
url: '/api/order/',
type: 'POST',
data: data,
dataType: "json",
success: function (order) {
<snip>
The result as seen by FireBug is this.
Here's the decoded JSON Object
InEditMode true
Items[0][Key] 2730M0ARAX1111AAAAX0
Items[0][PromoCode]
Items[0][Qty] 3
Items[1][Key] 2730M0ARCX1111AAAAX0
Items[1][PromoCode]
Items[1][Qty] 5
Here's the Raw view
InEditMode=true&
Items%5B0%5D%5BKey%5D=2730M0ARAX1111AAAAX0&
Items%5B0%5D%5BPromoCode%5D=&
Items%5B0%5D%5BQty%5D=3&
Items%5B1%5D%5BKey%5D=2730M0ARCX1111AAAAX0&
Items%5B1%5D%5BPromoCode%5D=&
Items%5B1%5D%5BQty%5D=5
Like #codenoire said in his comment, you aren't specifying the content type. Add contentType: 'application/json; charset=utf-8' to your $.ajax call, like so:
$.ajax({
url: '/api/order/',
type: 'POST',
data: data,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (order) {
<snip>
I think you need to stringify your JSON object before you post it. Use JSON.stringify(data) before you post it.
I was so close! The answer is a combination of rwisch45 and Saeedses
I had already tried adding the contentType before, but that caused it to break and I hadn't pursued it any further then that.
the solution is to add the content type AND JSON.stringify it, as so.
$.ajax({
url: '/api/order/',
type: 'POST',
data: JSON.stringify(data),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (order) {
Thanks all for your help!

Send JavaScript Variables with AJAX

can someone point me out how can I send JavaScript variables with AJAX.
JavaScript:
var d=new Date();
document.write(d);
AJAX:
$.ajax
({
type: 'POST',
url: 'save.php',
cache: false,
data: { document.write(d); // Just for example
},
Everything else works great. Thanks.
You can't send "variables". You can only send strings (or things which can be turned into strings). (You can store those strings in variables).
A date object (which you store in d) can be converted into a string, so you could send that.
The return value of document.write() will always be undefined, so it doesn't make much sense to send that.
You appear to be using jQuery. The data property expects a standard JavaScript object. An object consists of a bunch of key/value pairs. You need to provide a key for your value.
data: { date: d }
you could pass the value to any parameter name you want like date parameter in this example:
$.ajax({
type: 'POST',
url: 'save.php',
cache: false,
data: { date: new Date()}
});
Or you could just use the variable like this:
var d = new Date();
$.ajax({
type: 'POST',
url: 'save.php',
cache: false,
data: { date: d}
});
Use JSON.stringify() to convert your objects to JSON format:
$.ajax
({
type: 'POST',
url: 'save.php',
cache: false,
data: JSON.stringify(d)
},
On the server side, of course, you would have to use a JSON parser to interpret the data.

Can't query JSON using jQuery

I'm using jQuery to grab some JSON data. I've stored it in a variable called "ajaxResponse". I cant pull data points out of it; I'm getting ajaxResponse.blah is not defined. typeof is a string. Thought it should be an object.
var getData = function (url) {
var ajaxResponse = "";
$.ajax({
url: url,
type: "post",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
return ajaxResponse;
},
...
typeof ajaxResponse; // string
ajaxResponse.blah[0].name // ajaxResponse.blah is not defined
make sure you specify option dataType = json
$.ajax({
url: url,
type: "post",
dataType: "json",
async: false,
success: function (data) {
ajaxResponse = data;
}
});
Q8-coder has the right of it, but to give you some details: your server is really passing back a string that you've formatted into JSON. You'll need to tell jQuery what to expect, otherwise it just assumes it received a string.
Add the following to your $.ajax options:
dataType: "json"
Also, refer to the jQuery API for examples and documentation for these options.

Categories