gabriel garcia
gabriel garcia

Reputation: 367

Problems getting response

I'm having some troubles trying to execute an ajax call. It is stored in chat.js (added in the html head) and it does a call to getChatHistory.php

chat.js:

function getChatHistory(user1, user2){  
var response = 'fail';
var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function()
{
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
    {
        response = response + xmlhttp.responseText;
    } else {
        response = "Error:" + hmlhttp.status;
    }

    xmlhttp.open('GET', 'getChatHistory.php?user1=' + user1 + '&user2=' + user2);
    xmlhttp.send();
}
return response;}

getChatHistory.php:

<?php
echo "the php talks";
?>

index.html:

<script>
(function(){
  alert(getChatHistory('user1', 'user2');
})()

I checked with alert() and the onreadystatechange event doesn't work.

Upvotes: 0

Views: 76

Answers (1)

Jesse Kernaghan
Jesse Kernaghan

Reputation: 4634

You're not sending the request due to the fact that your .open and .send functions are inside of your callback, try this instead:

function getChatHistory(user1, user2){  
    var response = 'fail';
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            response = response + xmlhttp.responseText;
        } else {
            response = "Error:" + hmlhttp.status;
        }
    }

    xmlhttp.open('GET', 'getChatHistory.php?user1=' + user1 + '&user2=' + user2);
    xmlhttp.send();
    return response;
}

Note, that you are also going to run into issues getting the response to return due to the fact that it's an async request. The response will return undefined unless you either a) make it a synchronous request (generally a bad idea) or b) set your action requiring the response to fire after the ready state has completed. Here is a basic example of how you could do so:

function getChatHistory(user1, user2, onComplete){  
    var response = 'fail';
    var xmlhttp = new XMLHttpRequest();

    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            response = response + xmlhttp.responseText;
        } else {
            response = "Error:" + hmlhttp.status;
        }

        onComplete(response);
    }

    xmlhttp.open('GET', 'getChatHistory.php?user1=' + user1 + '&user2=' + user2);
    xmlhttp.send();
}

index.html

<script>
(function(){
  getChatHistory('user1','user2', function(resp){
     alert(resp);
  });
})();
</script>

Upvotes: 2

Related Questions