-1

I am trying to create an instant messaging site. Every ten seconds I want a javascript/ajax script to check if there are new messages. I thought that I could have a php page output 1 if there are. I have done the php coding, but can not get the javascript side to work. I have tried using $.get and am having a bit of trouble. Any help would be greatly appreciated.

Here is my ajax code:

var check;
function checkForMessages() {
    $.get("/checkmsg.php", function(data) {
        if(data == 1) {
            alert("There is a new message");
        }
    });
}

check = setInterval(checkForMessages, 10000);

My php code always outputs 1 for testing purposes

6
  • 1
    What code do you have already? Post the PHP code and your attemps at the js code Commented May 29, 2012 at 2:16
  • Okay there is the javascript code Commented May 29, 2012 at 2:22
  • get firebug or use the debuggger in chrome; look at the ajax/xhr responses and see what it's telling you. it won't return 1 for instance...I think it's a string, possibly something different depending on what you set for dataType. Commented May 29, 2012 at 2:22
  • Are you sure the url is correct? Commented May 29, 2012 at 2:31
  • try to use developer tools and firebug first to check if there are errors Commented May 29, 2012 at 2:38

1 Answer 1

1

I'm guessing at the end of your php code you have this:

echo '1';

For your JS i suggest $.post():

jQuery.post( '/checkmsg.php', function(data) { 
    if (data.search('1') !== -1) {
        alert("There is a new message");
    } else {
        alert("Something went wrong.");
    }
});
Sign up to request clarification or add additional context in comments.

13 Comments

That doesn't work either :( - doesn't output anything even though the page outputs 1
@ethanh - wut browser r u using, and does it echo "1" or echo 1
Also your code gives me TypeError: Object bound: function () { return document.getElementById.apply(document, arguments) } has no method 'post' in the Chrome javascript console
@ethanh - Do you have jquery set up?
@ethanh - You need to include it in the page, I updated the script, try it now.
|

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.