How to use getJSON, sending data with post method?

Jqueryasp.net MvcPostHttp PostGetjson

Jquery Problem Overview


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.

Jquery Solutions


Solution 1 - Jquery

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();

Solution 2 - Jquery

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.

Solution 3 - Jquery

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, https://stackoverflow.com/questions/1924939/php-request-vs-get-and-post)

This is simpler than @lepe's solution.

Solution 4 - Jquery

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
    } 

Solution 5 - Jquery

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!");
    });

Solution 6 - Jquery

$.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');

Solution 7 - Jquery

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;
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVikasView Question on Stackoverflow
Solution 1 - JqueryErv WalterView Answer on Stackoverflow
Solution 2 - JquerylepeView Answer on Stackoverflow
Solution 3 - JqueryLerin SonbergView Answer on Stackoverflow
Solution 4 - JqueryStan BashtavenkoView Answer on Stackoverflow
Solution 5 - JqueryFusca SoftwareView Answer on Stackoverflow
Solution 6 - JqueryTonyView Answer on Stackoverflow
Solution 7 - JquerymicView Answer on Stackoverflow