I have been developing a registration form and slowly but surely I have been learning some javascript and jquery along the way, to further support my knowledge of that and all. I have come across a problem however, the problem is I can’t get the response from a AJAX request.
My AJAX request is in a separate function, I have multiple purposes for it. I have put alert();’s in the code for debugging purposes.
function validate_input ( input, type ) {
$.ajax({
type:'post',
url: 'ajax_request.php',
data: "type=" + type + "&input=" + input,
success: function( response ) {
if( response == "true" || response == "false" ) {
alert( "working" );
console.log(response);
return response;
} else {
alert( "AJAX/jQuery Error" );
alert( "Reponse !== true or false" );
}
}
});
}
I can confirm that the ajax_request.php file is echoing true or false correctly, however, for those interested here is the coding.
if (!defined('BASEPATH') &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest')
exit('Direct Access to this file has been disabled.');
include('core/db.php');
$validateType = intval( $_POST['type'] );
$input = escape_string( $_POST['input'] );
if( $validateType == 1 ) // validate username
{
echo ( user_exists( $input ) ? "true" : "false" );
} else if( $validateType == 2 ) // validate email
{
echo "true"; // not coded yet
}
Finally, I call the function when it is necessary( using .blur() ), you can see below;
var username_value = "Jake"; // for debugging purposes, var definitely contains something
validate_input( username_value, 1 );
alert( validate_input( username_value, 1 ) ); alerts "undefined"
I am just wondering if anyone can see any issues with the code that would be causing this, and please don’t suggest for me to use a validator plugin, that is not an answer to the question.
Thanks,
Ajax calls are asynchronous, you can’t return the response like that. Using ajax you define a callback function which is called when the response is received. Code execution does not stop and wait for the response before continuing.
So you need to do whatever you want to do within the success function, or call another function from there.