How to pass parameters in $ajax POST?

user4127 picture user4127 · Sep 9, 2013 · Viewed 717.3k times · Source

I have followed the tutorial as stated in this link. In the code below for some reason the data is not appended to the url as parameters, but if I set them directly to the url using /?field1="hello" it works.

$.ajax({
        url: 'superman',
        type: 'POST',
        data: { field1: "hello", field2 : "hello2"} ,
        contentType: 'application/json; charset=utf-8',
        success: function (response) {
            alert(response.status);
        },
        error: function () {
            alert("error");
        }
    }); 

Answer

Alvaro picture Alvaro · Sep 9, 2013

I would recommend you to make use of the $.post or $.get syntax of jQuery for simple cases:

$.post('superman', { field1: "hello", field2 : "hello2"}, 
    function(returnedData){
         console.log(returnedData);
});

If you need to catch the fail cases, just do this:

$.post('superman', { field1: "hello", field2 : "hello2"}, 
    function(returnedData){
         console.log(returnedData);
}).fail(function(){
      console.log("error");
});

Additionally, if you always send a JSON string, you can use $.getJSON or $.post with one more parameter at the very end.

$.post('superman', { field1: "hello", field2 : "hello2"}, 
     function(returnedData){
        console.log(returnedData);
}, 'json');