How to use getJSON, sending data with post method?
Asked Answered
C

7

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.

Chaschase answered 15/4, 2009 at 11:15 Comment(2)
get in getJSON means use GET to get some json.Calie
@Majid Fouladpour When I asked this question, I wasn't knowing that..!Chaschase
H
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();
Hour answered 15/4, 2009 at 11:59 Comment(4)
Just want to add that $.getJSON support Jsonp(cross domain access) unfortunately $.post not.Corporeity
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.Eta
Not true, JSONP also requires server support to parse the callback parameter.Citral
When I am using the above function, I am receiving a string object instead of a json object.Quintessa
B
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.

Brigandage answered 29/9, 2010 at 3:49 Comment(3)
This will never bypass the limit GET has while POST maximum size can be redefined.Laughton
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!Unable
@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"); }Brigandage
S
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.

Spiritless answered 15/3, 2015 at 18:8 Comment(1)
This didn't work with the done() and fail() methods that you can normally apply to getJSON.Branle
F
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
    } 
Filling answered 27/9, 2013 at 14:38 Comment(0)
H
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!");
    });
Hijack answered 16/11, 2016 at 11:23 Comment(0)
H
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');
Halfassed answered 5/9, 2014 at 19:58 Comment(0)
S
-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;
});
Singleaction answered 20/7, 2010 at 18:35 Comment(1)
i think this is not the answer to what has been asked.Hefner

© 2022 - 2024 — McMap. All rights reserved.