简体   繁体   English

留在页面上并且在php中发出Javascript警报时不要重置表单字段

[英]Stay on page and don't reset form fields when Javascript alert in php

I am having troubles with a form in php and some Javascript code embedded in it. 我在php中有某种形式的麻烦,并且在其中嵌入了一些Javascript代码。

I would like to stay on the page and don't reset the form fields after a Javascript alert. 我想停留在页面上,并且在Javascript警报后不重置表单字段。 When the alert is shown, the page reloads and all the fields in the form are reset. 显示警报时,页面将重新加载,并且表单中的所有字段都将重置。

Here is the code: 这是代码:

if (!empty($_REQUEST['captcha'])) {
if (empty($_SESSION['captcha']) || trim(strtolower($_REQUEST['captcha'])) != $_SESSION['captcha']) {

      echo "<script type=\"text/javascript\">

      alert(\"El texto no coincide, por favor vuelva a intentarlo\");

      return false;

      </script>"; 


} else {

     $para = 'xxx';
     $asunto = 'Mensaje de mi sitio xxx';
     $nombre = $_GET['nombre'];
     $email = $_GET['email'];
     $contenido = "Mensaje enviado por " . $nombre . " \r\n";
     $contenido .= "e-mail es: " . $email . " \r\n";
     $contenido .= "Mensaje: " . $_GET['texto'] . " \r\n";
     mail($para, $asunto, $contenido);
     echo "<script type=\"text/javascript\">

     alert(\"Gracias por contactar con nosotros, nos pondremos en contacto lo antes posible.\");
     document.contacto.captcha.select();
     return false;

     </script>"; 

}
$request_captcha = htmlspecialchars($_REQUEST['captcha']);

unset($_SESSION['captcha']);

}

Thanks so much in advance for your help. 在此先感谢您的帮助。

Have a great day. 祝你有美好的一天。

Is your form posting to this php? 您的表单发布到此php吗? I presume you've trimmed the form HTML out of your question. 我想您已经从您的问题中删除了HTML表单。 If you want to validate the form this way, you'll need to fill in values in the form HTML based on $_REQUEST. 如果要以这种方式验证表单,则需要基于$ _REQUEST在HTML表单中填写值。

A better solution would be to validate the form using AJAX. 更好的解决方案是使用AJAX验证表单。

Your PHP code should grab the data on the $_POST request, and send it back to the page after reload. 您的PHP代码应获取$ _POST请求中的数据,并在重新加载后将其发送回页面。 Then, the inside the form, you should check for each variable, and if its not empty, prepopulate the fields on the form. 然后,在表单内部,应检查每个变量,如果变量不为空,则预填充表单上的字段。

This is time consumin for you as a developer if you are not using a framework (as the code suggest). 如果您不使用框架(如代码所示),那么这对于开发人员来说是很费时间的。 Try one of the most popular ones, that make an excelent work handling forms and validations for you like Symfony2, Laravel, Zend Framework2. 尝试其中一种最受欢迎​​的工具,例如Symfony2,Laravel,Zend Framework2,它们可以为您提供出色的处理表单和验证工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM