Error sending a POST request via ajax

Asked

Viewed 312 times

1

Good morning, I am trying to send a POST request to a URL but am having the following error:

Syntaxerror: Unexpected end of JSON input JSON is correct in formatting because I have validated it. The code is like this:

function salvaDados(){
  var myData = JSON.stringify('{ "name":"John", "age":30, "city":"New York"}')
  $.ajax({
    url: "http://localhost:81/adm/dados",
    type: "POST",
    dataType: 'json',
    contentType: 'application/json',        
    data: myData,
    success: function(data){
        alert('ok')
    },
    error: function(XMLHttpRequest, textStatus, errorThrown){
        alert(errorThrown)
    }
  })
}

the REST server is normal because I can save this same JSON via Postman.

  • Face the method JSON.stringify() is used to turn a valid Json into a string, note that what you are inserting into the method is already a string!

  • Thanks for the answer, when I do JSON.parse, the same error happens.

  • 1

    What @Leandrade said is that you should remove ' in the example you gave, because you are trying to convert a string and not an object... test var myData = JSON.stringify({ "name":"John", "age":30, "city":"New York"});

  • @Sergio, I did as you said and the error changed, now it is giving (Syntaxerror: Unexpected token < in JSON at position 0)

1 answer

2


Well I think you don’t quite understand the concept of these methods for JSON, to send data to the back-end using the JSON.stringify() Json needs to be in a valid format, note that in your code what is actually passing to the method is a string, therefore the mistake:

var myData = JSON.stringify('{"name":"John", "age":30, "city":"New York"}')

When the correct would be to pass a valid Json:

var myData = JSON.stringify({"name":"John", "age":30, "city":"New York"})

OR:

var myData = {"name":"John", "age":30, "city":"New York"}
var jsonSt = JSON.stringify(myData)

As you can see in the example below passing the data correctly the methods work:

var myData = { "name":"John", "age":30, "city":"New York"};
var jsonSt = JSON.stringify(myData);

console.log('Tipo do myData: ', typeof myData);
console.log('myData: ', myData);

console.log('-------');

console.log('Depois do stringify: ', typeof jsonSt);
console.log('jsonSt: ', jsonSt);

The same goes for the JSON.parse():

var myData = { "name":"John", "age":30, "city":"New York"};
var jsonSt = JSON.stringify(myData);
var jsonPa = JSON.parse(jsonSt);

console.log('Depois do stringify: ', typeof jsonSt);
console.log('jsonSt: ', jsonSt);
console.log('-------');
console.log('Parseando para objeto: ', typeof myData);
console.log('jsonPa: ', jsonPa);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.