带有ajax的表单-没有刷新页面的消息表单php

时间:2018-07-02 11:50:15

标签: javascript ajax

我想使用ajax调用发送表单而不刷新页面

HTML

<form id="form">
<input type="radio" name="radio" value="radio1">
<input type="radio" name="radio" value="radio1">

<input type="checkbox" name="box" value="box1">
<input type="checkbox" name="box" value="box2">

<input type="text" name="text" value="box2">

<input type="submit" id="submit" name="submit" class="embtn btn-1" value="Send" onclick="submitform()">

</form>

这是JS代码

function submitform(e) {
    e.preventDefault();
    $.ajax({
        url : 'assets/php/brief-wiz.php', 
        type: 'post', 
        data: $('form').serialize() 
    }).done(function(html) {
        $( ".form-message" ).append( html );
    });
};

PHP

<?php

$errors = [];

if (empty($_POST["radio"])) {
    $errors[] = "Complete radio ";
} else { 
    $radio = implode($_POST['radio']);
}

if (empty($_POST["box"])) {
    $errors[] = "Complete box ";
} else { 
    $box = implode($_POST['box']);
}

$text = ($_POST['text']);   

$body = "";

$body .=  "<div><b>1:</b> " . $profil . "</div>";
$body .=  "<div><b>2:</b> " . $box . $text . "</div>";

$to       = 'mymail@com.pl';
$subject  = 'Contact;
$message  =  $body;

$headers = "From: webmaster@example.com" . "\r\n";
$headers .= "Reply-To: " . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=UTF-8\r\n";

$success = mail($to, $subject, $message, $headers);


echo $success ? "Mail sended" : "Error";


?>

现在我的页面正在重新加载而没有消息。

没有此代码:

(e) {
    e.preventDefault();
}

消息显示一秒钟,但是页面正在重新加载。 如何在不刷新页面的情况下使用PHP加载消息。

3 个答案:

答案 0 :(得分:2)

使用Javascript事件:

HTML

Import-Csv

JAVASCRIPT

<form id="form" action="assets/php/brief-wiz.php">
    <input type="radio" name="radio" value="radio1">
    <input type="radio" name="radio" value="radio1">

    <input type="checkbox" name="box" value="box1">
    <input type="checkbox" name="box" value="box2">

    <input type="text" name="text" value="box2">

    <input type="submit" id="submit" name="submit" class="embtn btn-1" value="Send">
</form>

答案 1 :(得分:0)

将提交输入类型更改为按钮。

答案 2 :(得分:0)

这是因为按钮的类型为Submit! 我建议您改用它:

<button id="submit" class="embtn btn-1" onclick="submitform()">Send</button>