0

I'm struggling for a while now, I cannot find the reason why this code won't work.

When the #submitmsg is clicked it should trigger another function which gets time from a php file. This is sorta chat-box and it should display Name (which is Ja) in this case and time next to it which is varible "tajm". Though undefined is showing instead of time.

Any idea why doesnt this work?

Code snippet below:

var tajm;

$(document).ready(function () {
    $("#submitmsg").click(function () {
        time();
        var newtext = $("#textmsg").val();
        var oldtext = document.getElementById("textbox").innerHTML;
        document.getElementById("textbox").innerHTML = oldtext + "<br/><div id='name'>Ja:     " + tajm + "</div><div id='red'>" + newtext + "</div>";
        $("#textbox").scrollTop($("#textbox")[0].scrollHeight);
    });
});

function time() {
    var ajax = new XMLHttpRequest();
    ajax.onreadystatechange = function () {
        if (ajax.readyState == 4) {
            tajm = ajax.responseText;
        }
    };
    ajax.open("GET", "r.php", true);
    ajax.send(null);
}
4
  • Asynchronous HTTP requests take time.
    – Pointy
    Apr 22, 2012 at 14:57
  • If the code was executed in "normal" order, you would not have to provide a callback (ajax.onreadystatechange). Apr 22, 2012 at 15:01
  • I've fixed this by adding setTimeout and delaying it for a bit. Is there any more efficient way I could do this with?
    – xtra
    Apr 22, 2012 at 15:11
  • @xtra Yes--by doing the work in the callback where it belongs. Apr 22, 2012 at 15:36

2 Answers 2

2

AJAX is asynchronous.

Your callback only runs some time after the rest of the code finishes.

0

As ajax is asynchronous, java script never wait to execute time method. In this case, u need to write below code snippet format

$(document).ready(function () {
    $("#submitmsg").click(function () {
        $.load("r.php",function(){
            var newtext = $("#textmsg").val();
            var oldtext = document.getElementById("textbox").innerHTML;
            document.getElementById("textbox").innerHTML = oldtext + "<br/><div id='name'>Ja:     " + tajm + "</div><div id='red'>" + newtext + "</div>";
            $("#textbox").scrollTop($("#textbox")[0].scrollHeight);
        }

    });
});

Note: Set time out is working, because u r giving wait to load your ajax call.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.