如何将成功的表单提交重定向到PHP中的另一个页面 [英] How to redirect successful form submission to another page in PHP

查看:99
本文介绍了如何将成功的表单提交重定向到PHP中的另一个页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在成功提交表单后,如何重定向到PHP中的另一个页面? 现在,我的代码在提交"按钮下显示绿色消息:您的消息已成功提交!

我想重定向到success.php,并在重新提交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.'));
}

当我使用时:

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

}

我在这里收到一条错误消息:未捕获的类型错误:无法读取未定义的属性"message".它显示在contactform.addAjaxMessage下.我还需要更新该代码吗?这是我的contact-form.js文件:

    $(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>');
  }
};

解决方案

容易!像这样使用PHP header 函数.只需确保将success.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.'));
  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.'));
}

您还可以通过更改以下内容来设置特定的HTTP响应代码:

header('Location: success.php');

对此:

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

200 响应代码表示确定",表示该页面将以预期的; 100%可以.但是您可能希望将其更改为 302 ,这意味着URL临时移了. >

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>');
  }
};

解决方案

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.

这篇关于如何将成功的表单提交重定向到PHP中的另一个页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆