jQuery on success, reload the page and then append?

14,603

Solution 1

location.reload() will reload your page, which creates a new request to your server and the browser then loads the response. You could add a parameter to the query string for the message, e.g.

$.ajax({
        type: 'GET',
        url: 'edit_slides.php',
        data: { user_id: user_id },
        success: function() { 
            window.location = "?message=success";
        }
    });

Then in server side code, you could display the message if the parameter exists. In ASP.NET MVC, it would look like this:

@if(Request["message"] == "success")
{
    <p>success</p>
}

If you don't have server side scripting available, you can also parse the querystring with javascript.

Solution 2

You can have some delay before you reload the page. Try this

$.ajax({
        type: 'GET',
        url: 'edit_slides.php',
        data: { user_id: user_id },
        success: function() { 
            $('#messageContent').append('<p>success</p>'); 
            setTimeout(function(){
               location.reload(); 
            }, 500);
        }
    });

Solution 3

Send it to a location but with a hash in the url to indicate a success:

$.ajax({
    type: 'GET',
    url: 'edit_slides.php',
    data: { user_id: user_id },
    success: function() { 
        window.location = window.location + "#success";
    }
});

Now when the page loads, check for the hash:

$(document).ready(function(){
    if(window.location.hash) {
        $("#messageContent").append("<p>success</p>");
    }
Share:
14,603
Drew
Author by

Drew

My name is Drew and I am a front end web developer always looking to learn more!

Updated on June 04, 2022

Comments

  • Drew
    Drew almost 2 years

    I have the following code:

    $.ajax({
            type: 'GET',
            url: 'edit_slides.php',
            data: { user_id: user_id },
            success: function() { 
                location.reload(); 
                $('#messageContent').append('<p>success</p>'); 
            }
        });
    

    What happens right now is that it appends and then reloads real quick so it loses the message.

    Now, I could take out the reload and it will append but in order for my changes to take affect, the page needs to be reloaded.

    Is there anything else I can do? I want to show a success message after reloading the page.

    Thanks!

  • doogle
    doogle over 12 years
    500ms wouldn't really give the user a sufficient amount of time to read the message.