views:

8704

answers:

4

I am using above method & it works well with one parameter in url

e.g. Students/getstud/1 where controller/action/parameter format is applied.

now I have an action in Students controller that accepts two patameters and return json object.

so how do i post data with $.getJSON() using post method.

Similar methods are also acceptable.

point is to call action of controller with ajax.

+27  A: 

The $.getJSON() method does an HTTP GET and not POST. You need to use $.post()

$.post(url, dataToBeSent, function(data, textStatus) {
  //data contains the JSON object
  //textStatus contains the status: success, error, etc
}, "json");

In that call, dataToBeSent could be anything you want, although if are sending the contents of a an html form, you can use the serialize method to create the data for the POST from your form.

var dataToBeSent = $("form").serialize();
Erv Walter
Just want to add that $.getJSON support Jsonp(cross domain access) unfortunately $.post not.
Tomas
A: 

if you have just two parameters you can do this:

$.getJSON('/url-you-are-posting-to',data,function(result){

//do something useful with returned result// result.variable-in-result; });

mic
A: 

Again, you can do this:

$.getJSON('/url-you-are-posting-to/'+param1+ '/'+ param2,null,function(result){

 //do something useful with returned result//
  result.variable-in-result;  // result is json structure returned//

});

which may not be so elegant

mic
A: 

This is my "one-line" solution:

$.postJSON = function(url, data, func) { $.post(url+(url.indexOf("?") == -1 ? "?" : "&")+"callback=?", data, func, "json"); }

In order to use jsonp, and POST method, this function adds the "callback" GET parameter to the URL. This is the way to use it:

$.postJSON("http://example.com/json.php",{ id : 287 }, function (data) {
   console.log(data.name);
});

The server must be prepared to handle the callback GET parameter and return the json string as:

jsonp000000 ({"name":"John", "age": 25});

in which "jsonp000000" is the callback GET value.

In PHP the implementation would be like:

print_r($_GET['callback']."(".json_encode($myarr).");");

I made some cross-domain tests and it seems to work. Still need more testing though.

lepe