I'm new with AJAX. I'm sending a request to start a PHP code on another page where couple of things need to happen. I have an algorithm on that page checking if all the things were done properly in right order. What I need is to return that boolean back to AJAX file, so that it would know that request was not only received, but finished in an intended way, so that I can add a success: function that would give a OK/NEY experience to the user.
you can return (true for success or false for unsuccess) variable in success function of AJAX. On the basis of that you can proceed next.
Dummy Example :
$.ajax({
url: '',
type:'POST',
data: {'id':id},
dataType:'json',
beforeSend:function(){
},
error : function(xhr, textStatus, errorThrown) {
alert('An error occurred!');
},
success:function(response){
if(response){
console.log('yes');
}
else{
console.log('no');
}
}
complete: function() {
}
});
Your folder:
AnyFolderName
|--- index.php
|--- script.php
Index.php:
<!DOCTYPE html>
<html>
<head>
<title>AJAX Request Sample</title>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
function submitform(){
//get value of input whos id is username
var username = $('input#username').val();
//data to post to script.php
var post = {username: username};
$.ajax({
url: "script.php", //<-- PHP Script where you want to post your data
type: "POST",
data: post,
success: function(data){
//callback when request is finished.
//in our script.php, we just echoed the posted username, so it alerts whatever username you have input.
alert(data);
}
});
}
</script>
</head>
<body>
<form id="myForm">
<input id="username" name="username">
</form>
<button onclick="submitform();"></button>
</body>
</html>
script.php:
<?php
//print out the posted data you have passed from the AJAX request
echo $_POST['username'];
?>
Oh it was my mistake. Went through dozens of pages, but finally found the answer on another thread (so mine is kind of a duplicate) :
How to return data from PHP to a jQuery ajax call
Have to use echo(); instead of return(); in PHP file! And, of course, the corresponding dataType, which in this case "text".