This question already has an answer here:
I trying to get data from data base via ajax code. PHP code works well but ajax reponse always is undefined. I tried json bat resuls is same. here are codes:
var email = $('#email').val();
function getAjax(p, m) {
$.ajax({
url: '../lib/checkmail.php',
type: 'post',
data: {val : p, column : m},
success: function (data) {
return data.toString();
}
});
}
if (email.length > 0){
alert(getAjax(email, 'youremail'));
}
</div>
Try using Accept and content-type attribute of Ajax method.
An ajax call works asynchroneously. So when you call getAjax(p, m)
if will start to get the url, which takes time, but the function returns immediately. Only after the url has been retrieve will the success
function of the ajax call be executed. So what you could test is this:
var email = $('#email').val();
function getAjax(p, m) {
$.ajax({
url: '../lib/checkmail.php',
type: 'post',
data: {val : p, column : m},
success: function (data) {
alert(data.toString());
}
});
}
if (email.length > 0){
getAjax(email, 'youremail');
}
this should give you an alert with the correct response.
Another, obvious, problem is, which you might now realize, that getAjax(p, m)
does not return a value, ever. The return
belongs to the success
function. Hence the return value of getAjax(p, m)
will always be 'undefined'.
You will have to learn how to work with an event driven asynchroneous programming language. Better use a good book, or course.