skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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 // XHR will read the content-type from the FormData object (which it needs to do in order to determine the boundary paramater), putting 'false' here stops jQuery overriding it
         // ...
     })
    

    or, for JSON

     $.ajax({
         type: 'POST',
         url : 'https://...',
         data:  JSON.stringify(myVar), // This will be a JSON text representing a string
         contentType: 'application/json'
         // ...
     })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search