douhao5280 2015-04-15 17:28
浏览 67

POST表单异步调用php文件

Could anyone help me at this? I'm trying to make an AJAX contact form, here's what I want to do:

  1. Validate certain format on HTML POST form through JS.
  2. If valid, enable form submit button; and after being pressed.
  3. Make a XML request to a mail.php file that processes the post request.
  4. Modify the DOM according to the mail.php response.

Here's my code:

<?php
// bool mail( string $to, string $subject, string $message [, string $additional_headers [, string $additional_parameters ] ] )
if(isset($_POST['email'])) {
    $email_to = "my_test_mail@gmail.com";
    $email_subject = "Correo de pruebas";

    $email = $_POST['email'];
    $name = isset($_POST['nombre']) ? $_POST['nombre'] : "Sin nombre";
    $telephone = isset($_POST['telefono']) ? $_POST['telefono'] : "Sin numero";
    $nopal = isset($_POST['tor-nopal']) ? "Si" : "No";
    $maiz = isset($_POST['tor-maiz']) ? "Si" : "No";
    $harina = isset($_POST['tor-harina']) ? "Si" : "No";
    $message = $_POST['mensaje'];

    function clean_string($string) {
        $bad = array("content-type", "bcc:", "to:", "cc:", "href");
        return str_replace($bad, "", str_replace("
", "
", $string));
    }

    $email_message = "Nombre: ".clean_string($name)."
";
    $email_message .= "Correo electronico: ".clean_string($email)."
";
    $email_message .= "Telefono: ".clean_string($telephone)."
";
    $email_message .= "Nopal: ".clean_string($nopal)."
";
    $email_message .= "Maiz: ".clean_string($maiz)."
";
    $email_message .= "Harina: ".clean_string($harina)."

";
    $email_message .= "Mensaje:
".clean_string($message)."
";

    $headers = "MIME-Version: 1.0
".
    "Content-Type: text/plain;charset=UTF-8
".
    "From: Pruebas <juanc_94_konoha@hotmail.com>
".
    "Reply-To: ".$email."
".
    "Subject: Contacto tortillas
".
    "X-Mailer: PHP/".phpversion();

    if( mail($email_to, $email_subject, $email_message, $headers) )
        echo "0";
    else
        echo "1";
} else
    echo "-1";
?>

My HTML form:

<form method=post action="./mail.php">
    <fieldset><label for=email>Correo el&eacute;ctronico:</label>
    <input type=email name=email id=email placeholder="usuario@ejemplo.com.mx" required></fieldset>
    <fieldset><label for=nombre>Nombre:</label>
    <input type=text name="nombre" id=nombre></fieldset>
    <fieldset><label for=telefono>Telefono:</label>
    <input type=tel name="telefono" id=telefono></fieldset>
    <fieldset><label><input type=checkbox name="tor-nopal"> Nopal</label>
    <label><input type=checkbox name="tor-maiz"> Ma&iacute;z</label>
    <label><input type=checkbox name="tor-harina"> Harina</label></fieldset>
    <fieldset><label for="mensaje">Mensaje</label>
    <textarea max-width=500 name="mensaje" id=mensaje max-length=498 required></textarea></fieldset>
    <br /><br />
    <input type=submit value=Enviar>
</form>

And here's the basic draft of my JS code:

function contactSubmitStatus() {
    var form = document.forms[0];
    if(request.readyState === 4)
        if(request.status === 200)
            if(request.responseText == "0") {
                document.getElementsByTagName("h3")[0].innerHTML = "&iexcl;Gracias por contactarnos!";
                fade("out", 1500, form, IE_check());
                form.remove;
            } else if(request.responseText == "1") {
                var explanation = document.createElement("p");
                explanation.innerHTML = "Tus datos est&aacute;n aparentemente bien pero hubo un problema en el servidor. Por favor intenta mas tarde o envianos un correo electr&oacute;nico desde tu cliente de correos. (i.e: https://mail.google.com/)";

                explanation.setAttribute("id", "warning-node");
                form.appendChild(explanation);
                fade("in", 1000, explanation, IE_check());
            }
}

function contactForm() {
    document.getElementsByName("email")[0].addEventListener("blur", isEmail);
    document.getElementsByName("mensaje")[0].addEventListener( "blur", isMsgValid);
    document.getElementsByName("submit")[0].addEventListener("click", function() {
        var request = createRequest(),
        form = document.forms[0],
        p = document.createElement("p");

        if(request == null) {
            alert("Tu navegador no permite transacciones asincronas, prueba con otro navegador.");
            return;
        } else {
            request.onreadystatechange = contactSubmitStatus;
            request.open("POST", form.action, true);
            request.send(new FormData(form));

            p.setAttribute("id", "contact-status");
            p.innerHTML = "Procesando datos...";
            form.appendChild(p);
        }
    });
}

The script worked. Only the form redirected me to /mail.php and only displayed 0. Which means the mail should have been sent but the email was not even in my spam mailbox. I'm guessing I have to configure a mail server on my workstation to test this kind of things, and I don't have a hosting yet to use for testing.

On regards to the browser loading redirecting to '/mail.php', do you think I need to use GET instead? 'Cuz I'm actually expecting a result to act upon. And since I would be using GET my php would need to use $_REQUEST instead of $_POST, right?

I'm sorry, maybe this is overwhelming but php is not my forte.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 R语言Rstudio突然无法启动
    • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
    • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
    • ¥15 用windows做服务的同志有吗
    • ¥60 求一个简单的网页(标签-安全|关键词-上传)
    • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
    • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
    • ¥100 为什么这个恒流源电路不能恒流?
    • ¥15 有偿求跨组件数据流路径图
    • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值