I get always the whole ajax-packet instead of simple response (true/false) as return of this function (responseJSON.success/responseText.success). Otherwise, the browser sends me an error or fault result with described content
function isUnique(inputObject) {
let type = $(inputObject).attr('id');
let res = $.ajax({
url: '/dbajax.php',
method: 'POST',
data: {[type]: $(inputObject).val()},
dataType: 'JSON',
success: function(data) { return data },
error: function(data) { }
})
console.log(res.responseJSON.success); // -> error: Cannot read property 'success' of undefined
console.log(res.responseJSON); // -> undefined
return res;
}
<?php
require('db/dbqueries.php');
if(isset($_POST['username'])){
$login_username = select_login_where_username ($_POST["username"]);
echo json_encode(array('success' => empty($login_username),));
}
if(isset($_POST['email'])){
$profile_email = select_profile_email_where_email ($email);
echo json_encode(array('success' => empty($profile_email),));
}
?>
2
Answers
Your problem is related to the fact that $.ajax is asynchronous. So if you write something after $.ajax it will be done before the request has been processed. You should do everything in the success function.
You are trying to access the responseJSON before the ajax request has completed. you need to wait for the ajax to finish before you can use it. There are two ways you can do this –
As mentioned by robinvrd use the success and error functions:
or use the callbacks on the request object: