0

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?

5
  • can you log/alert the value of response in the success handler Commented Jul 16, 2015 at 4:42
  • the given code looks fine.... Commented Jul 16, 2015 at 4:43
  • 1
    Check for whitespace before and after the PHP tags in function.php. Edit: If response is always numerical, you can also do an implicit conversion by changing the if condition to == 1 instead of == '1'. Commented Jul 16, 2015 at 4:45
  • 1
    Try if(response.trim() == '1'){ and add alert(':' + response + ':') before the if stmt Commented Jul 16, 2015 at 4:45
  • @naohnu : Thanks, it appeared php was indeed adding whitespaces! Commented Jul 16, 2015 at 4:49

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.