Jump to content

Unable to get ajax to work at all


bozebo

Recommended Posts

I have never been able to get ajax to work, I have followed about 50 tutorials and nothing ever happens, I need some help.

 

I have vastly simplified what I am trying to do into a test, Ill I want it to do is alert if the page it reads has "1" in it... Shouldn't that be simple?

 

My most recent attempt is modeled closely on the tutorial on ajaxfreaks.com ("Simple Introduction to AJAX and XMLHttpRequest")

 

      function createRequestObject() {
         var req;
         if(window.XMLHttpRequest){
            // Firefox, Safari, Opera...
            req = new XMLHttpRequest();
         } else if(window.ActiveXObject) {
            // Internet Explorer 5+
            req = new ActiveXObject("Microsoft.XMLHTTP");
         } else {
            // There is an error creating the object,
            // just as an old browser is being used.
            alert('Problem creating the XMLHttpRequest object');
         }
         return req;
      }
      // Make the XMLHttpRequest object
      var http = createRequestObject();
      function sendRequest(act) {
         // Open PHP script for requests
         http.open('get', 'other/is_in_game.php?gameid='+act);
         http.onreadystatechange = handleResponse;
         http.send(null);

      }
      function handleResponse() {
         if(http.status == 200){
           if(http.readyState == 4){
            // Text returned FROM the PHP script
            var response = http.responseText;
             if(response) {
               // UPDATE ajaxTest content
               alert('IT WORKED!!!');
             }
           }
         } else {
           alert('Something went wrong');
         }
      }

 

The page it reads (http://www.bozebo.com/knightlands/other/is_in_game.php) contains simple php to set the headers correctly, and it prints "1" on the page.. so the whole file through http is jus "1".. So my ajax script should work every time without fail?? It doesn't.

 

You can find my test here: http://www.bozebo.com/knightlands/ajaxtest.html

 

Can anyone help me? Or am I just cursed...

 

 

Link to comment
https://forums.phpfreaks.com/topic/74182-unable-to-get-ajax-to-work-at-all/
Share on other sites

I have recently had troubles with getting AJAX going for the first time.

I dropped the check for http.status == 200. I only wait for http.readystate to reach 4. Then it worked for me.

In the code you posted, I see where you are creating the XMLHttpRequest object, but I don't see you ever send the request. The function to send the request is there, but it doesn't get called.

What are function are you calling from the page?

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.