kr_ilya2018-07-16 10:13:08
kr_ilya, 2018-07-16 10:13:08

Ajax error Requested JSON parse failed how to fix?

When executing ajax, it gives an error Requested JSON parse failed. At the same time, the handler is triggered (there is a record in the database). What to do?

$(document).on('click', '#btn_reg',function() {
    var formData = {
    'login' 	: $("input[name='reg_login']").val(),
    'password' 	: $("input[name='reg_pass']").val(),
    'email'		: $("input[name='reg_email']").val()
    $.ajax ({
      type: 'POST',
      url: '/api/ajax.php',
      data: formData,
      dataType : 'json',
      encoding: true,
      error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);


Handler (raw version without checks):
function __autoload($name){ include($_SERVER['DOCUMENT_ROOT']."/classes/_class.".$name.".php");}
$func = new func();
$config = new config;
$db = new db($config->HostDB, $config->UserDB, $config->PassDB, $config->BaseDB);
$login = htmlspecialchars($_POST["login"]);
$pass = htmlspecialchars($_POST["password"]);
$time = time();
$ip = $func->UserIP;
$email = htmlspecialchars($_POST["email"]);

$db->Query("INSERT INTO db_users_a (user, email, pass, referer, referer_id, date_reg, ip) 
VALUES ('$login','$email','$pass','admin','1','$time',INET_ATON('$ip'))");

Answer the question

In order to leave comments, you need to log in

2 answer(s)
Vlad, 2018-07-16

You don't have PHP side response for ajax request. You insert data into the database, and the javascript handler waits for valid JSON in response. Write at the end of the php file echo json_encode(1); and you will have a working script.

Alexey P, 2018-07-16

See what the server returns to you in the Network tab in your browser or make a curl request to the server. The specified error indicates that an unexpected JSON was received from the server, or nothing was received at all.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question