Toubi
Toubi

Reputation: 2509

MVC4 Ajax call using Jquery, should it be Post or Get?

In a application I m using Jquery with MVC4 and I need to query data on server. I understand JQuery provide multiple methods for Ajax request but I m not getting which particular method I should use ?

I will pass parameter and receive some data and also in case of request failure or timeout I need to do something. Please advice which method I should go with.

Cheers

Upvotes: 1

Views: 11771

Answers (5)

Péter
Péter

Reputation: 2181

If any data change in the request than I should use post method. If only fetch some data use the get method.
Technically You can use any method you wish. Syntactically it will work, but semantically it's wrong. If You change the state of any method, you should use POST method, because the GET method can be invoked simply type the request url in the browser address bar. For example you have a delete method in you controller which allow invoked by get method. A web crawler (google or any search engine) hit your page: http://myurl.com/user/delete/1 and boom. Your user with id 1 deleted from your database.
When I said change that mean if you run delete, update or insert method on your persistent data, you should use post method, or in case of webapi the appropriate method(DELETE, PUT, PATCH, POST).
I think this article could help to dig a little deeper.

Upvotes: 0

Sakthivel
Sakthivel

Reputation: 1938

Since you're requesting some data and in response you get some data from data base, you can use Ajax post or getJson. I feel its good to use getJson in which you will serialize the data and send it back to view or you simple use JsonResult that's provided in MVC itself.

The difference between Http Get and Http Post are always confusing to many developers. Get method requests data from a specified resource and post method submits data to be processed to a speicified resource. Where parameters passed via get methods are attached in url and post method parameters wont.

<script type="text/javascript">
  $(document).ready(function () {
    $('#btnGetValue').click(function () {
       //Requesting controller action from getJson
        $.getJSON("/Home/GetJsonData", null, function (data) {
            var div = $('#ajaxDiv');
            div.html("<br/> " + "Persons received from server: " + "<br/>");
            $.each(data, function (i, item) {
                //This is where you'll get all the items returned from the controller.
                printPerson(div, item);
            });
        });
    });
});
</script>

and in controller,

 public JsonResult GetJsonData()
    {
        var persons = new List<Person>
                          {
                              new Person{Id = 1, FirstName = "F1", 
                                  LastName = "L1", 
                                  Addresses = new List<Address>
                                                  {
                                                      new Address{Line1 = "LaneA"},
                                                      new Address{Line1 = "LaneB"}
                                                  }},

                              new Person{Id = 2, FirstName = "F2", 
                                  LastName = "L2", 
                                  Addresses = new List<Address>
                                                  {
                                                      new Address{Line1 = "LaneC"},
                                                      new Address{Line1 = "LaneD"}
                                                  }}};

        return Json(persons, JsonRequestBehavior.AllowGet);
    }

you can use getJson for loading dropdownlist, populating other controls, list or whatever. further reading on getJson and Json result are JSON with MVC 4 JsonResult

Upvotes: 0

Zruty
Zruty

Reputation: 8667

Regarding the POST vs GET dilemma, this is a question of design, not availability. As you know, jQuery allows you to issue both POST and GET requests.

I list some connotations of using GET request:

  • Server's response to GET request may get cached by the browser, so don't use GET if you may return different content on subsequent request.
  • According to HTTP spec, GET request shouldn't cause any side-effect on the server side.
  • All the information you transmit via GET request is encoded as a part of URL. Be prepared that this URL may be accessed from somewhere else (like another website, forum, or by a web crawler).
  • Because of the above, with GET you don't have any reliable means of protecting from cross-site request forgery.
  • By default, ASP.NET MVC prohibits the server from responding to AJAX GET requests.You can disable this behavior (see this question for code sample).
  • Browsers (and sometimes servers) impose limitations on the length of the URL. As a rule of thumb, 2000 characters is safe. (see this question for details).

This question gives more information on the topic, and so does Wikipedia on HTTP protocol.

If you are not sure that your AJAX API satisfies the requirements for GET requests, use POST.

Upvotes: 4

Sumit Chourasia
Sumit Chourasia

Reputation: 2434

For getting data from server side we should be using GET while for updating the data on server side we should be using POST method.

try using like this.

function yourFunc() {


$.ajax({
    type : 'POST',
    url : 'yourcontroller/action',
    contentType : "application/json; charset=utf-8",
    dataType : 'json',
    data : param,
    async : false,
    cache: false,
    success : function(dataList) {
        //alert("dataList ---> "+dataList); 



    },

    error : function(XMLHttpRequest, textStatus, errorThrown) {
        //alert(XMLHttpRequest + " - " + errorThrown);
    }
});


}

pass parameters in param variable like this.

var param;      
param={param1:"val",param2:"val", param3:"val"};

Hope this will help you.

Upvotes: 0

Rituraj ratan
Rituraj ratan

Reputation: 10378

use $.ajax

   var fruit = 'Banana';

$.ajax({
        url: ajaxurl,//your url
        type"'POST',//also can set GET             
        data: {//passing parameter
            'action':'example_ajax_request',
            'fruit' : fruit
        },
        success:function(data) {
            // This outputs the result of the ajax request
            console.log(data);
        },
        error: function(errorThrown){
            console.log(errorThrown);
        }
    });

see more about ajax sample

Upvotes: 1

Related Questions