rshah
rshah

Reputation: 691

AJAX request doesnt change text in div

I'm currently performing a task which involves getting the information from a file using php and returning it using AJAX. The data is getting sent as I tested this using an alert, however for some reason the line:

param.html(str);

won't change the text in the div...

Here is my function:

function updateChat(param) {
    var dataString = 'update=true';
    var str = '';
    $.ajax({
        type: "POST",
        url: "inc/chat.php",
        data: dataString,
        success: function(data) {
            str = data;
        }
    });
    param.html(str);
}

Here is how I call my method:

setTimeout(function() {
    updateChat('#chatbox');
}, 1000);

Upvotes: 0

Views: 361

Answers (2)

ShankarSangoli
ShankarSangoli

Reputation: 69905

Since you are performing an async request str will not be set until the ajax request is complete and success handler is invoked. Move param.html(str) inside the ajax success handler then it will update the text in the div.

function updateChat(param) {
    var dataString = 'update=true';
    var str = '';
    $.ajax({
        type: "POST",
        url: "inc/chat.php",
        data: dataString,
        success: function(data) {
           param.html(data);
        }
    });

}

Change this

setTimeout(function() {
    updateChat('#chatbox'); //<----
}, 1000);

to

setTimeout(function() {
    updateChat($('#chatbox'));
}, 1000);

Upvotes: 5

jparaya
jparaya

Reputation: 1339

The problem occurs because javascript uses async call in Ajax. In your case, the line that assigns param.html(str) is executed before str gets changed as a result of the delay in server call.

function updateChat(param) {
    var dataString = 'update=true';
    var str = '';
    $.ajax({
        type: "POST",
        url: "inc/chat.php",
        data: dataString,
        success: function(data) {
            str = data; ---> then it's assigned
        }
    });
    param.html(str);  ---> this is executed first
}

Move the param.html assignment inside the success function of the Ajax call.

Upvotes: 1

Related Questions