Hrabovsky Marián
Hrabovsky Marián

Reputation: 21

Write into database before redirecting

There's a button, when it is clicked(html onclick) it redirects to another page. In javascript there's a function, that writes some new values into a database table when this button is clicked. My problem is: redirecting takes place before the data is written into the database, so on the new page i still have the old values. Is there an easy way to invert these steps(redirecting, writing into database)? Thanks for your advise

Upvotes: 1

Views: 467

Answers (4)

Ann B. G.
Ann B. G.

Reputation: 302

just move the redirection into the callback of an ajax call, say you have

<a href="#" id="savedata">Save data</a>
<script type="text/javascript">
    $(document).ready(function() {
        $("#savedata").click(function() {
            $.post('/savemydata/', { mydata: 'data' }, function(data) {
                window.location.href = '/newpage/'
            });
            return false;
        });
    });
</script>

if the button actually submits the form, then you might probably want to hide the button instead and then just trigger it after your post simply by adding:

$("#buttonID").trigger('click');

Upvotes: 1

Bergi
Bergi

Reputation: 665040

That depends on how you are writing to the database. But the usual and recommended way to transport data to your server when loading a new page is the use of URL parameters. If you use something like

<form action="/next.php" method="POST">
 <input type="hidden" name="data" value="values" />
 <button type="submit" value="Next Page" />
</form>

or

<a href="/next.php?data=values">Next Page</a>
// also simply usable with
window.location = "/next.php?data=values";

you can be sure that

  1. the data reaches the server,
  2. can be processed (written to the database) before
  3. the requested page is returned.

You could also make use of cookies. Just write your data values into document.cookie, and they will be transported to the server with the same request that asks for the new page.

Upvotes: 0

Jordan
Jordan

Reputation: 32542

Move the code that redirects to a new page into the callback for your ajax save request.

Something like this:

$.post('/savemydata/', { my: 'data' }, function(data) {
    //the Ajax post has been completed successfully, so now we redirect
    window.location.href = '/newpage/'
});

Upvotes: 0

Ethan
Ethan

Reputation: 2784

Use ajax to write the data, then in the callback of the ajax throw in the redirect. This will ensure that the redirect does not happen until the information is written to the database. It would help to see some of your code to make a better answer. Also, this would most likely be best done with jQuery if you are new to ajax.

Upvotes: 0

Related Questions