Question

How can I redirect to another page in PHP upon successful form submission? Right now I have the code that shows a Green Message under Submit button: Your message was successfully submitted!

I'd like to redirect to success.php and in case of an error to resubmit.php

//try to send a message     
if(mail(MY_EMAIL, EMAIL_SUBJECT, setMessageBody($fields_req), "From: $email")) {
echo json_encode(array('message' => 'Your message was successfully submitted.'));
} else {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(array('message' => 'Unexpected error while attempting to send e-mail.'));
}

When I use:

{
header('location: success.php');
}
else {
header('location: resubmit.php');

}

I'm getting an error message here: Uncaught type error: Cannot read property 'message' of undefined. It shows up under the contactform.addAjaxMessage. Do I need to update that code as well? This is my contact-form.js file:

    $(document).ready(function() {
    $("#feedbackSubmit").click(function() {
    //clear any errors
    contactForm.clearErrors();

    //do a little client-side validation -- check that each field has a value and e-mail field is in proper format
    var hasErrors = false;
    $('#feedbackForm input,textarea').not('.optional').each(function() {
      if (!$(this).val()) {
        hasErrors = true;
        contactForm.addError($(this));
      }
    });
    var $email = $('#email');
    if (!contactForm.isValidEmail($email.val())) {
      hasErrors = true;
      contactForm.addError($email);
    }

    var $phone = $('#phone');
    if (!contactForm.isValidPhone($phone.val())) {
      hasErrors = true;
      contactForm.addError($phone);
    }

    //if there are any errors return without sending e-mail
    if (hasErrors) {
      return false;
    }

    //send the feedback e-mail
    $.ajax({
      type: "POST",
      url: "library/sendmail.php",
      data: $("#feedbackForm").serialize(),
      success: function(data)
      {
        contactForm.addAjaxMessage(data.message, false);
        //get new Captcha on success
        $('#captcha').attr('src', 'library/securimage/securimage_show.php?' + Math.random());
      },
      error: function(response)
      {
        contactForm.addAjaxMessage(response.responseJSON.message, true);
      }
   });
    return false;
  });
});

    //namespace as not to pollute global namespace
    var contactForm = {
  isValidEmail: function (email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
  },
  /**
   * Validates that phone number has 10 digits.
   *
   * @param  {String}  phone phone number to validate
   * @return {Boolean} if phone number is valid
   */
  isValidPhone: function (phone) {
    phone = phone.replace(/[^0-9]/g, '');
    return (phone.length === 10);
  },
  clearErrors: function () {
    $('#emailAlert').remove();
    $('#feedbackForm .help-block').hide();
    $('#feedbackForm .form-group').removeClass('has-error');
  },
  addError: function ($input) {
    $input.siblings('.help-block').show();
    $input.parent('.form-group').addClass('has-error');
  },
  addAjaxMessage: function(msg, isError) {
    $("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ? 'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() + '</div>');
  }
};
Was it helpful?

Solution 2

Easy! Just use the PHP header function like so. Just be sure to replace the value of success.php with the actual final location you want users to end up in:

//try to send a message     
if(mail(MY_EMAIL, EMAIL_SUBJECT, setMessageBody($fields_req), "From: $email")) {
  // echo json_encode(array('message' => 'Your message was successfully submitted.'));
  header('Location: success.php');
  exit;
} else {
  header('HTTP/1.1 500 Internal Server Error');
  echo json_encode(array('message' => 'Unexpected error while attempting to send e-mail.'));
}

You can also set the specific HTTP response code by changing this:

header('Location: success.php');

To this:

header('Location: success.php', false, 200);

The 200 response code means “OK” which means the page will be loaded as expected; 100% OK. But you might want to change that to 302 which means the URL has moved temporarilly.

OTHER TIPS

You can simple use header function:

Success case:

Header('location:success.php');

Error case:

Header('location:error.php');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top