I've been having problems with this code I had spent the last 3 hours digging around and trying to find an answer. As I wasn't successful, I will just post the code and ask which kind of parameters I should have on my web service to handle this request:
var args = [{ key: 'myId', value: 'myValue' }, { key: 'myOtherId', value: 'myOtherValue'}];
var dataToSend = { name: 'fooId', value: 'fooValue', args: args };
$.ajax({
type: 'POST',
url: 'fooURL',
data: dataToSend,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: OnSuccess,
error: OnError
});
Now, which kind of signature I should have to be able to get my "dataToSend"?
I've tried:
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Foo(string name, object value, List<Args> args)
{
return "OK";
}
public class Args
{
public string key { get; set; }
public object value { get; set; }
}
and
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Foo(string name, object value, object[] args)
{
return "OK";
}
and also
[WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string Foo(dataToSend dataToSend)
{
return "OK";
}
public class dataToSend
{
public string name { get; set; }
public object value { get; set; }
public List<Args> args = new List<Args>();
}
public class Args
{
public string key { get; set; }
public object value { get; set; }
}
Try passing the data as a string, not an object, ie:
$.ajax( { ... data : '{ a: 2, b: 3 }', ... } );
The reasoning for this is that if you specify an object as data then jQuery serializes the data using query string format, whereas the server is expecting JSON format directly.
This happens despite telling jQuery to use JSON as the data type - it seems to only relate to the result, not the request payload sent to the server.
Everything else you have there looks correct to me.
Although this is an older post I thought I would contribute. I have been sending an associative array same idea an the accepted post I just find it easier to write.
Javascript
postData[0] = 'data!';
postData[1] = 'moar data!';
postData[2] = 'and some data';
$.ajax({
type: 'POST',
url: 'postUrl',
data: { data: postData },
});
PHP
$data = $_POST['data'][0];
$moar_data = $_POST['data'][1];
$and_some_data = $_POST['data'][2];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With