jaynp
jaynp

Reputation: 3325

refresh page after jquery ajax

I am trying to refresh the page after a jQuery AJAX call. It appears that the page is refreshing (only sometimes) before all the data has been transmitted. Can anyone see why by this snippet below. I have the refresh code in the success function so I am confused.

I tried adding async = false and that didn't seem to work either.

function sendRating(rating, reload_on_return) {

$.ajax({
    type: "POST",
    dataType: 'json',
    url: window.url_root + cid + "/",
    data: {
        "rating": rating.r2 / 100.0
    },
    success: function(data) {
        if (data.hasOwnProperty('success')) {
            console.log("data was sent!");

            if (reload_on_return) {
                    location.reload();

            }

        }
    },
    error: function() {
        console.log("Data didn't get sent!!");
    }
})

Upvotes: 10

Views: 90064

Answers (1)

broguyman
broguyman

Reputation: 1426

You could possibly do a setTimeout, to make it wait for a split second before the refresh can execute.

function sendRating(rating, reload_on_return) {

$.ajax({
    type: "POST",
    dataType: 'json',
    url: window.url_root + cid + "/",
    async: false,
    data: {
        "rating": rating.r2 / 100.0
    },
    success: function(data) {
        if (data.hasOwnProperty('success')) {
            console.log("data was sent!");

            if (reload_on_return) {
                setTimeout(
                  function() 
                  {
                     location.reload();
                  }, 0001);    
            }

        }
    },
    error: function() {
        console.log("Data didn't get sent!!");
    }
})

Upvotes: 18

Related Questions