Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET: jQuery AJAX 'data' param problem

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; }
}
like image 319
Andre Gallo Avatar asked Jun 30 '09 05:06

Andre Gallo


2 Answers

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.

like image 65
Sam Avatar answered Oct 13 '22 23:10

Sam


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];
like image 39
Fermis Avatar answered Oct 13 '22 23:10

Fermis