120

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 parameters and return a JSON object.

So how do I post data with $.getJSON() using post method?

Similar methods are also acceptable.

The point is to call an action of the controller with AJAX.

BenMorel
  • 34,448
  • 50
  • 182
  • 322
Vikas
  • 24,082
  • 37
  • 117
  • 159

7 Answers7

230

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
  • 13,737
  • 8
  • 44
  • 57
  • 7
    Just want to add that $.getJSON support Jsonp(cross domain access) unfortunately $.post not. – Tomas Sep 28 '10 at 12:24
  • 2
    Actually .getJSON() supports cross domain access in two ways. JSONP, which doesn't use GET or POST but script injection; but also CORS - and .post() also supports CORS. However CORS requires that the server also support it whereas JSONP does not. – hippietrail Dec 22 '11 at 08:55
  • 2
    Not true, JSONP also requires server support to parse the callback parameter. – Shrulik May 31 '13 at 18:47
  • When I am using the above function, I am receiving a string object instead of a json object. – Pratik Singhal Jun 22 '16 at 14:04
12

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.

Sahil Mahajan Mj
  • 11,033
  • 8
  • 53
  • 100
lepe
  • 24,677
  • 9
  • 99
  • 108
  • 1
    This will never bypass the limit GET has while POST maximum size can be redefined. – Rafael Herscovici Nov 12 '12 at 14:39
  • Why did you add `?callback`? in url? That made the callback not to be called for me. I also added `JSON.stringify(data)`. +1, helpful post! – Ionică Bizău Nov 08 '14 at 18:38
  • @IonicăBizău: thanks. In order to return an object, we need to add "callback" parameter to the URL and the server needs to return the same object name generated by JQuery. I also use an override function for getJSON(): `jQuery.getJSON = function(url, data, func) { return $.get(url+(url.indexOf("?") == -1 ? "?" : "&")+"callback=?", data, func, "json"); }` – lepe Nov 10 '14 at 02:55
8

Just add these lines to your <script> (somewhere after jQuery is loaded but before posting anything):

$.postJSON = function(url, data, func)
{
    $.post(url, data, func, 'json');
}

Replace (some/all) $.getJSON with $.postJSON and enjoy!

You can use the same Javascript callback functions as with $.getJSON. No server-side change is needed. (Well, I always recommend using $_REQUEST in PHP. http://php.net/manual/en/reserved.variables.request.php, Among $_REQUEST, $_GET and $_POST which one is the fastest?)

This is simpler than @lepe's solution.

Community
  • 1
  • 1
Lerin Sonberg
  • 623
  • 7
  • 11
3

I had code that was doing getJSON. I simply replaced it with post. To my surprise, it worked

   $.post("@Url.Action("Command")", { id: id, xml: xml })
      .done(function (response) {
           // stuff
        })
        .fail(function (jqxhr, textStatus, error) {
           // stuff
        });



    [HttpPost]
    public JsonResult Command(int id, string xml)
    {
          // stuff
    } 
Stan Bashtavenko
  • 1,025
  • 11
  • 16
3

I just used post and an if:

data = getDataObjectByForm(form);
var jqxhr = $.post(url, data, function(){}, 'json')
    .done(function (response) {
        if (response instanceof Object)
            var json = response;
        else
            var json = $.parseJSON(response);
        // console.log(response);
        // console.log(json);
        jsonToDom(json);
        if (json.reload != undefined && json.reload)
            location.reload();
        $("body").delay(1000).css("cursor", "default");
    })
    .fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log("Request Failed: " + err);
        alert("Fehler!");
    });
Fusca Software
  • 709
  • 6
  • 11
2

$.getJSON() is pretty handy for sending an AJAX request and getting back JSON data as a response. Alas, the jQuery documentation lacks a sister function that should be named $.postJSON(). Why not just use $.getJSON() and be done with it? Well, perhaps you want to send a large amount of data or, in my case, IE7 just doesn’t want to work properly with a GET request.

It is true, there is currently no $.postJSON() method, but you can accomplish the same thing by specifying a fourth parameter (type) in the $.post() function:

My code looked like this:

$.post('script.php', data, function(response) {
  // Do something with the request
}, 'json');
Vince Bowdren
  • 8,326
  • 3
  • 31
  • 56
Tony
  • 91
  • 4
-8

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;
});
robert
  • 33,242
  • 8
  • 53
  • 74
mic
  • 1