POST request to the server as json, why is the format wrong?

Here is the code:

$( document ).ready(function() {
$("#btn").click(
function(){

var dataf = {
 "user": "Andrew",
 "phone": "+380685743823",
 "userID": "12342345423453",
};

jQuery.ajax({
 url: 'HERE URL',
 options: {
 'Content-Type':'application/json' },
 type: 'POST',
 dataType: 'json',
 data: dataf, 
 success: function(response) { 
 document.getElementById('result_form').innerHTML = "Data sent";
},
 error: function(response) { 
 document.getElementById('result_form').innerHTML = "Error. Data is not sent.";
}
 }); 
}
);
});


The data server accepts only post requests of json, but for some reason with this transfer of data says that the format is not json, you need json, how to do the json where the error?
July 8th 19 at 15:47
1 answer
July 8th 19 at 15:49
You are trying to pass an object. But JSON is a string.
Bring the object to a string

JSON.stringify(dataf);

$( document ).ready(function() {
$("#btn").click(
function(){

var dataf = {
 "user": "Andrew",
 "phone": "+380685743823",
 "userID": "12342345423453",
};

var jsonString = JSON.stringify(dataf);
jQuery.ajax({
 url: 'HERE URL',
 options: {
 'Content-Type':'application/json' },
 type: 'POST',
 dataType: 'json',
 data: jsonString, 
 success: function(response) { 
 document.getElementById('result_form').innerHTML = "Data sent";
},
 error: function(response) { 
 document.getElementById('result_form').innerHTML = "Error. Data is not sent.";
}
 }); 
}
);
});
Not working. Was the 500 error, now 405. - nikita.Stracke commented on July 8th 19 at 15:52
Code of action. Returns method not allowed. And what is used on the backend - Kaylah_Mraz82 commented on July 8th 19 at 15:55
: than to replace it, that would be allowed? - nikita.Stracke commented on July 8th 19 at 15:58
Read Response message.
in the Header of the response should contain the key Allow, which contains data about what methods are allowed.

Check out the URL.
Change options on headers

$( document ).ready(function() {
$("#btn").click(
function(){

var dataf = {
"user": "Andrew",
"phone": "+380685743823",
"userID": "12342345423453",
};

jQuery.ajax({
url: 'HERE URL',
headers: {
'Content-Type':'application/json'
},
type: 'POST',
dataType: 'json',
data: JSON.stringify(dataf),
success: function(response) {
document.getElementById('result_form').innerHTML = "Data sent";
},
error: function(response) {
document.getElementById('result_form').innerHTML = "Error. Data is not sent.";
}
});
}
);
}); - Kaylah_Mraz82 commented on July 8th 19 at 16:01

Find more questions by tags JSONAJAXJavaScript