A
A
anon131992016-06-08 12:11:54
JavaScript
anon13199, 2016-06-08 12:11:54

POST request to json server, why format is wrong?

Here is the code itself:

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

var dataf = {
  "user": "Андрей",
  "phone": "+380685743823",
  "userID": "12342345423453",
};

          jQuery.ajax({
                    url: 'ТУТ ЮРЛ',
                    options: {
                    'Content-Type':'application/json' },
                    type: 'POST',
                    dataType: 'json',
                    data: dataf,  
        success: function(response) { 
        	document.getElementById('result_form').innerHTML = "Данные отправлены";
    	},
    	error: function(response) { 
    		document.getElementById('result_form').innerHTML = "Ошибка. Данные не отправлены.";
    	}
 	}); 
    }
  );
});


The server accepts data only post requests in the json format, but for some reason, with such data transfer, it answers that the format is not json, but json is needed, how to make it json, where is the error?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
devian3000, 2016-06-08
@devian3000

You are trying to pass an object. And JSON is a string.
Cast the object to a string
JSON.stringify(dataf);

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

var dataf = {
  "user": "Андрей",
  "phone": "+380685743823",
  "userID": "12342345423453",
};

var jsonString = JSON.stringify(dataf);
          jQuery.ajax({
                    url: 'ТУТ ЮРЛ',
                    options: {
                    'Content-Type':'application/json' },
                    type: 'POST',
                    dataType: 'json',
                    data: jsonString,  
        success: function(response) { 
        	document.getElementById('result_form').innerHTML = "Данные отправлены";
    	},
    	error: function(response) { 
    		document.getElementById('result_form').innerHTML = "Ошибка. Данные не отправлены.";
    	}
 	}); 
    }
  );
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question