K
K
kr_ilya2018-07-16 10:13:08
PHP
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?
Ajax:

$(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);
}
}
    })
.done(function(data){
console.log(data);
      alert('Успех!!!');
});
    
event.preventDefault();

  });


Handler (raw version without checks):
ini_set('display_errors','On');
error_reporting('E_ALL');
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)
V
Vlad, 2018-07-16
@kr_ilya

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.

A
Alexey P, 2018-07-16
@lynxp9

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