Search code examples
jqueryapihttp-headers.post

How to send query parameters through $.post method?


I have an issue how to send my JSON string to $.post call. Since $.post default ContentType is application/x-www-form-urlencoded but my server accepts only application/json header

The reason why I need help in $.post call is I want fast end result

Here my sample code for reference :

var jqxhr = $.post(url, sendData, function(data) {

    console.log(data);
  })
  .done(function() {

  })
  .fail(function(data) {
    console.log("Failed");
    console.log(data);
  })
  .always(function() {

  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.always(function() {

});

var obj = {
  "timeout": "5s",
  "_source": false,
  "query": {
    "nested": {
      "path": "demo",
      "query": {
        "multi_match": {
          "query": request,
          "type": "phrase",
          "operator": "and",
          "fields": ["name"]
        }
      },
      "inner_hits": {

        "highlight": {
          "fields": {
            "name": {},
          }
        }
      }
    }
  }
};

var sendData = JSON.stringify(obj);

Solution

  • $.post is a shorthand Ajax function

    You can use $.ajax() directly

    $.ajax({
      url: url,
      type: 'post',
      dataType: 'json',
      contentType: 'application/json',
      data: sendData  // JSON string
    });
    

    OR use $.ajaxSetup()

    Sets default values for future Ajax requests. Its use is not recommended.

    $.ajaxSetup({
      contentType: 'application/json',
    });
    
    $.post(url, sendData, function(data) {
    
    });
    

    Note: jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks is deprecated in jQuery 1.8