161

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");
        }
    }); 
Ram
  • 3,092
  • 10
  • 40
  • 56
user4127
  • 2,397
  • 6
  • 21
  • 32
  • 9
    If you are looking for your params to be appended to the URL, you need to change type to 'GET'. 'POST' will pass parameters in the HTTP headers instead. – rob Feb 23 '14 at 21:57

12 Answers12

148

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');
Alvaro
  • 40,778
  • 30
  • 164
  • 336
68

Jquery.ajax does not encode POST data for you automatically the way that it does for GET data. Jquery expects your data to be pre-formated to append to the request body to be sent directly across the wire.

A solution is to use the jQuery.param function to build a query string that most scripts that process POST requests expect.

$.ajax({
    url: 'superman',
    type: 'POST',
    data: jQuery.param({ field1: "hello", field2 : "hello2"}) ,
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    success: function (response) {
        alert(response.status);
    },
    error: function () {
        alert("error");
    }
}); 

In this case the param method formats the data to:

field1=hello&field2=hello2

The Jquery.ajax documentation says that there is a flag called processData that controls whether this encoding is done automatically or not. The documentation says that it defaults to true, but that is not the behavior I observe when POST is used.

Stephen Ostermiller
  • 23,933
  • 14
  • 88
  • 109
64

Try using GET method,

var request = $.ajax({
    url: 'url',
    type: 'GET',
    data: { field1: "hello", field2 : "hello2"} ,
    contentType: 'application/json; charset=utf-8'
});

request.done(function(data) {
      // your success code here
});

request.fail(function(jqXHR, textStatus) {
      // your failure code here
});

You cannot see parameters in URL with POST method.

Edit:

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

Ajith S
  • 2,907
  • 1
  • 18
  • 30
19
    function FillData() {
    var param = $("#<%= TextBox1.ClientID %>").val();
    $("#tbDetails").append("<img src='Images/loading.gif'/>");
    $.ajax({
        type: "POST",/*method type*/
        contentType: "application/json; charset=utf-8",
        url: "Default.aspx/BindDatatable",/*Target function that will be return result*/
        data: '{"data":"' + param + '"}',/*parameter pass data is parameter name param is value */
        dataType: "json",
        success: function(data) {
               alert("Success");
            }
        },
        error: function(result) {
            alert("Error");
        }
    });   
}
SiwachGaurav
  • 1,918
  • 2
  • 17
  • 16
11

In a POST request, the parameters are sent in the body of the request, that's why you don't see them in the URL.

If you want to see them, change

    type: 'POST',

to

    type: 'GET',

Note that browsers have development tools which lets you see the complete requests that your code issues. In Chrome, it's in the "Network" panel.

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
8
$.ajax(
   {
      type: 'post',
      url: 'superman',
      data: { 
        "field1": "hello",
        "field2": "hello1"
      },
      success: function (response) {
        alert("Success !!");
      },
      error: function () {
        alert("Error !!");
      }
   }
);

type: 'POST', will append **parameters to the body of the request** which is not seen in the URL while type: 'GET', appends parameters to the URL which is visible.

Most of the popular web browsers contain network panels which displays the complete request.

In network panel select XHR to see requests.

This can also be done via this.

$.post('superman',
      { 
        'field1': 'hello', 
        'field2': 'hello1'
      },
      function (response) {
        alert("Success !");
      }
    );
Du-Lacoste
  • 11,530
  • 2
  • 71
  • 51
6

You can do it using $.ajax or $.post

Using $.ajax :

    $.ajax({
      type: 'post',
      url: 'superman',
      data: { 
        'field1': 'hello', 
        'field2': 'hello1'
      },
      success: function (response) {
        alert(response.status);
      },
      error: function () {
        alert("error");
      }
   });

Using $.post :

    $.post('superman',
      { 
        'field1': 'hello', 
        'field2': 'hello1'
      },
      function (response, status) {
        alert(response.status);
      }
    );
Shrinivas
  • 1,223
  • 16
  • 13
  • Thank you very much - Its working. Nevertheless, it would be great if you could add an example which calls a function to get the post parameters. Thanks! :) – gies0r Jun 25 '18 at 07:25
6

I know this answer is super late

You can also use FormData for passing your data into $.ajax({})

let formData =  new FormData()
formData.append('data1', "Hello")
formData.append('data2', "World")

$.ajax({
   url: '/',
   type: 'POST',
   data: formData,
   contentType: false,
   processData: false,
   cache: false,
   success: function(v){
       console.log(v)
   }
})
Kroi
  • 246
  • 3
  • 9
4

Your code was right except you are not passing the JSON keys as strings.

It should have double or single quotes around it

{ "field1": "hello", "field2" : "hello2"}

$.ajax(
   {
      type: 'post',
      url: 'superman',
      data: { 
        "field1": "hello", // Quotes were missing
        "field2": "hello1" // Here also
      },
      success: function (response) {
        alert(response);
      },
      error: function () {
        alert("error");
      }
   }
);
Sylvester Das
  • 164
  • 11
2
function funcion(y) {
$.ajax({
   type: 'POST',
   url: '/ruta',
   data: {"x": y},
   contentType: "application/x-www-form-urlencoded;charset=utf8",
});
}
0

For send parameters in url in POST method You can simply append it to url like this:

$.ajax({
    type: 'POST',
    url: 'superman?' + jQuery.param({ f1: "hello1", f2 : "hello2"}),
    // ...
}); 
S. Ali Mihandoost
  • 2,873
  • 3
  • 18
  • 24
  • 2
    If the questioner just wanted to send some params via POST, the other answers would be more appropriate, as that would be more standard. The question explicitly mentions POST and URL params. (E.g. I found this question because I have to set URL params altogether with those in the body, and I would like to do it in a nicer way than concatenating strings.) @user4127 accept this as the answer or reformulate your question please. – Jan Molnár Jul 12 '19 at 17:37
0

The Problem is the way Parameters Passing So used jQuery.param then it worked

This Code Worked for Me

 data: jQuery.param({ DistrictId: 5, TalukId: 0, HobliId: 0 }),
 contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
subramanya46
  • 451
  • 6
  • 9