Home > Software design >  Jquery ajax call wrong payload
Jquery ajax call wrong payload

Time:08-26

I have some troubles whit jquery ajax call, infact I tried to perform a post call passing like data a string variable:

 myVar = 'Hello';

  $.ajax(
     type: 'POST',
     url : 'https://...',
     data:  myVar,
     success : function(data) {

     },
     complite: function() {...},
     error: function(err) {...}
  )

If I inspect the http call I can see that the payload is:

  'Hello': ""

I don't know how it is possible and how fix the problem.

CodePudding user response:

i think you are passing payload in the wrong formate.

myVar = 'Hello';

$.ajax(
     type: 'POST',
     url : 'https://...',
     data: {
        'name':myVar
        },
     success : function(data) {

     },
     complite: function() {...},
     error: function(err) {...}
  )

On the server side you will get the value in the key 'name' you can fetch the value using 'name' key.

CodePudding user response:

jQuery, by default, will put a Content-Type: application/x-www-form-urlencoded header on data it sends via Ajax.

You, however, are passing a plain text string.


You need to either change the Content-Type to match the data you are sending or the data you are sending to match the Content-Type. (Or you could change both).

The important things are:

  • The data and content-type need to match
  • The server needs to be able to handle data in the format you are sending

So you might:

 $.ajax({
     type: 'POST',
     url : 'https://...',
     data:  myVar,
     contentType: 'text/plain'
     // ...
 })

or, since jQuery will encode objects as URL encoded data:

 $.ajax({
     type: 'POST',
     url : 'https://...',
     data:  { myVar },
     // ...
 })

or, if you want multipart data:

 const data = new FormData();
 data.append('myVar', myVar);

 $.ajax({
     type: 'POST',
     url : 'https://...',
     data,
     contentType: false
     // ...
 })

or, for JSON

 $.ajax({
     type: 'POST',
     url : 'https://...',
     data:  JSON.stringify(myVar), // This will be a JSON text representing a string
     contentType: 'application/json'
     // ...
 })
  • Related