Reputation: 163
I have index.php file which is as following :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="ajax.js"></script>
</head>
<body>
<div id="summary">The returned value will go here</div>
</body>
</html>
The content of ajax.js which is supposed to keep calling/invoking function.php until function.php returns '1' :
function check(){
return $.ajax({
url: 'function.php',
type:'POST',
success: function(response){
if(response == '1'){
$('#summary').html(response);
}else{
check();
}
},
failure: function(jqXHR, textStatus, errorThrown){
console.log(textStatus);
}
});
}
check();
And Finally function.php :
<?php
echo "1";
?>
I expected that function.php would only be invoked once since function.php returns "1". However it keeps calling function.php endlessly.
Can someone point me out how to get this working properly?
Upvotes: 0
Views: 474
Reputation: 388316
The code looks fine, but 1 probable reason is the response might have leading or trailing spaces.
A solution could be is to trim the response value before comparing it
if (response.trim() == '1') {//use $.trim(response) if wants to support < IE9 or use a [polyfill](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/trim#Polyfill)
$('#summary').html(response);
} else {
check();
}
Upvotes: 1