Javascript没有在表单提交上调用

时间:2017-04-07 21:08:41

标签: javascript php jquery html forms

我在html中有一个非常简单的表单,我正在尝试发送电子邮件。我在网上查了一些教程唱歌js,但大多数都不能正常工作。这是我的代码表单,但是当我按下提交时,js function没有被调用,而是在html表单上没有做任何事情。

<form class="form-inline" id="contact-form" onSubmit="return false">
<center><p><input style="height:3vw;width:40vw;font-size:1.2vw;" type="text" class="form-control" size="30" placeholder=" Name" name="name" id="name" required></p>

<p><input style="height:3vw;width:40vw;font-size:1.2vw;" type="email" class="form-control"  size="30" placeholder=" E-mail Address" name="email" id="email" required></p>

<p><input style="height:3vw;width:40vw;font-size:1.2vw;" type="text" class="form-control"  size="30" placeholder=" Subject" name="subject" id="subject" required></p>

<p><textarea style="height:10vw;width:40vw;font-size:1.2vw;" placeholder=" Message..." class="form-control"  name="message" id="message"></textarea></p>

<p><button type="submit" class="button" name="btn_submit" id="btn_submit">Send</button></p></center>   

</form>

我已经在表单的<div>结尾之后包含了js文件

<script src="js/jquery-2.1.4.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/functions.js"></script>

functions.js文件如下

//Contact Us
  $("#btn_submit").click(function() { 
        //get input field values
        var user_name       = $('input[name=name]').val(); 
        var user_email      = $('input[name=email]').val();
        var user_message    = $('textarea[name=message]').val();

        //simple validation at client's end
        var proceed = true;
        if(user_name==""){ 
            proceed = false;
        }
        if(user_email==""){ 
            proceed = false;
        }
        if(user_message=="") {  
            proceed = false;
        }

        //everything looks good! proceed...
        if(proceed) 
        {
            //data to be sent to server
            post_data = {'userName':user_name, 'userEmail':user_email, 'userMessage':user_message};

            //Ajax post data to server
            $.post('contact_me.php', post_data, function(response){  

                //load json data from server and output message     
                if(response.type == 'error')
                {
                    output = '<div class="alert-danger">'+response.text+'</div>';
                }else{
                    output = '<div class="alert-success">'+response.text+'</div>';

                    //reset values in all input fields
                    $('.form-inline input').val(''); 
                    $('.form-inline textarea').val(''); 
                }

                $("#result").hide().html(output).slideDown();
            }, 'json');

        }
    });

我的电子邮件处理程序如下:

<?php
if($_POST)
{
    $to_Email       = "email.com"; //Replace with recipient email address



    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

        //exit script outputting json data
        $output = json_encode(
        array(
            'type'=>'error', 
            'text' => 'Request must come from Ajax'
        ));

        die($output);
    } 

    //check $_POST vars are set, exit if any missing
    if(!isset($_POST["userName"]) || !isset($_POST["userSubject"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Input fields are empty!'));
        die($output);
    }

    //Sanitize input data using PHP filter_var().
    $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_Subject       = filter_var($_POST["userSubject"], FILTER_SANITIZE_STRING);
    $user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);

    //additional php validation
    if(strlen($user_Name)<3) // If length is less than 3 it will throw an HTTP error.
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
        die($output);
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
        die($output);
    }

    if(strlen($user_Message)<5) //check emtpy message
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
        die($output);
    }

    $subject = $user_Subject;

    $message_Body = "<strong>Name: </strong>". $user_Name ."<br>";
    $message_Body .= "<strong>Email: </strong>". $user_Email ."<br>";
    $message_Body .= "<strong>Message: </strong>". $user_Message ."<br>";



    $headers = "From: " . strip_tags($user_Email) . "\r\n";
    $headers .= "Reply-To: ". strip_tags($user_Email) . "\r\n";
    $headers .= "MIME-Version: 1.0\r\n";
    $headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";



    //proceed with PHP email.
    /*$headers = 'From: '.$user_Email.'' . "\r\n" .
    'Reply-To: '.$user_Email.'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();
    */


    $sentMail = @mail($to_Email, $subject, $message_Body, $headers);

    if(!$sentMail)
    {
        $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
        die($output);
    }else{
        $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_Name .' Thank you for contacting us.'));
        die($output);
    }
}
?>

在按下提交时,没有调用js文件,控制台也没有错误。任何人都可以帮我解决我犯错误的地方。谢谢。

3 个答案:

答案 0 :(得分:0)

您需要阻止默认表单提交操作,即刷新页面。

您需要在函数中添加一个可以跟踪事件的参数,然后从该参数中调用preventDefault()

$("#btn_submit").click(function(e) { 
    e.preventDefault();

    ...
}

答案 1 :(得分:0)

尝试替换

length-1

$("#btn_submit").click(function() {

答案 2 :(得分:0)

您需要阻止表单提交,否则它将直接提交并转向服务器端。

你可以使用jQuery做这样的事情:

$("#btn_submit").click(function(e) { 
    e.preventDefault(); 
 //your code goes here after preventing submission
}