Search code examples
phpajaxformspost-redirect-get

How-To: Post-Redirect-Get: AJAX with no form action


I would like to stop the form resubmission on page refresh for a form on a users profile where they are able to update some basic profile information and a query is made with an ajax request. The request works fine and all is well, but if they refresh they get the classic form resubmission warning which I want to avoid in this scenario. I understand to do this you can use post-redirect-get but I'm having trouble because my form as no "action", when the submit button is clicked it simply reloads with profile page(current page) with the updated user information from the DB.

I tried using:

if(isset($_POST)) {
   unset($_POST);
   header('Location: profile.php');
}

At the very top of the current page before anything, but it resulted in a redirect loop. Is there a simple way to do this in my situation? The form, ajax request, and script that is executed from the ajax request are below.

The form:

<form id="info-form" method="post">
            <div class="form-group">
                <label for="location">From:</label>
                <input type="text" class="form-control" name="location" id="fromVal" value="<?php if(isset($location)) echo $location; ?>">
            </div>
            <div class="form-group">
                <label for="gender">Gender:</label>
                <input type="text" class="form-control" name="gender" id="genderVal" value="<?php if(isset($gender)) echo ucwords($gender); ?>">
            </div>
            <div class="form-group">
                <label for="email">Email:</label>
                <input type="text" class="form-control" name="email" id="emailVal" value="<?php if(isset($email)) echo $email; ?>" >
            </div
            <div class="buttonHolder">
                <button id="update" name="submit" type="submit" >Update</button>
                <button type="button" class="action" id="update-cancel" data-dialog-close>Cancel</button>
            </div>  
</form>

The AJAX:

$('#update').click(function(){
        var emailVal = $("#emailVal").val();
        var genderVal = $("#genderVal").val();
        var locVal = $("#fromVal").val();
        $.ajax({
            url: 'updateProfile.php',
            type: 'POST', // GET or POST
            data: { email: emailVal, location : locVal, gender : genderVal }, // will be in $_POST on PHP side
            success: function(data) { // data is the response from your php script
                // This function is called if AJAX query was successful
            },
            error: function() {
                // This callback is called if AJAX query has failed
            }
        });
});

updateProfile.php

<?php

require_once 'config.php';

  try {
     $mysqli= new mysqli($host, $username, $password, $dbname); 
     if ($mysqli->connect_error) {
         die('Connect Error (' . $mysqli->connect_errno . ') '
             . $mysqli->connect_error);
      }
  } catch (mysqli_sql_exception $e) { 
      throw $e; 
  }


  $stmt = $mysqli->prepare( "UPDATE users SET email=?,location=?,gender=? WHERE fbuid = ?");
  session_start();
  $stmt->bind_param("sssi", $email, $location, $gender, $_SESSION['fbuid']);

  $email = $_POST['email'];
  $location = $_POST['location'];
  $gender = $_POST['gender'];

  $stmt->execute();
  $stmt->free_result();
  $stmt->close();
  $mysqli->close();

?>

Solution

  • $_POST will always be set when the page loads (even if it isn't a POST request).

    Unsetting it won't help because when you redirect, you load a new page and it is set again.

    Test to see if it is an actual POST request or test to see if a specific piece of form data exists in $_POST.