如何发送PHP表单的AJAX请求

时间:2014-10-24 10:29:53

标签: javascript php jquery ajax

试图发送一个小时的消息,HTML:

<div  id="contactform">
<div id="contact_results"></div>
<form name="contactform" method="POST" action="contact_me.php">

<input type="text" name="name">
<input type="text"  name="telephone">    
<input type="text" name="email">
<textarea  rows="6" name="message"></textarea>    
<input type="submit" value="SEND" id="submit_btn">

</form>
</div>

JavaScript:

$(document).ready(function() {
 $('form').on('submit', function (e) {
  e.preventDefault();
//Rest of your code

    var proceed = true;
    //simple validation at client's end
    //loop through each field and we simply change border color to red for invalid fields       
    $("#contactform input[required=true], #contactform textarea[required=true]").each(function(){
        $(this).css('border-color',''); 
        if(!$.trim($(this).val())){ //if this field is empty 
            $(this).css('border-color','red'); //change border color to red   
            proceed = false; //set do not proceed flag
        }
        //check invalid email
        var email_reg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/; 
        if($(this).attr("type")=="email" && !email_reg.test($.trim($(this).val()))){
            $(this).css('border-color','red'); //change border color to red   
            proceed = false; //set do not proceed flag              
        }   
    });

    if(proceed) //everything looks good! proceed...
    {
        //get input field values data to be sent to server
        post_data = {
            'name'      : $('input[name=name]').val(), 
            'email' : $('input[name=email]').val(), 
            'telephone' : $('input[name=telephone]').val(), 
            'msg'           : $('textarea[name=message]').val()
        };

        //Ajax post data to server
        $.post('contact_me.php', post_data, function(response){  
            if(response.type == 'error'){ //load json data from server and output message     
                output = '<div class="error">'+response.text+'</div>';
            }else{
                output = '<div class="success">'+response.text+'</div>';
                //reset values in all input fields
                $("#contactform  input[required=true], #contactform textarea[required=true]").val(''); 
                $("#contactform .white-spacing").slideUp(); //hide form after success
            }
            $("#contactform #contact_results").hide().html(output).slideDown();
        }, 'json');
    }
});

//reset previously set border colors and hide all message on .keyup()
$("#contactform  input[required=true], #contactform textarea[required=true]").keyup(function() { 
    $(this).css('border-color',''); 
    $("#result").slideUp();
});
});

contact_me.php:

<?php
if($_POST)
{
$to_email       = "myemail@yahoo.com"; 

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

    $output = json_encode(array( //create JSON data
        'type'=>'error', 
        'text' => 'Sorry Request must be Ajax POST'
    ));
    die($output); //exit script outputting json data
} 

//Sanitize input data using PHP filter_var().
$name       = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
$email      = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
$telephone  = filter_var($_POST["telephone"], FILTER_SANITIZE_NUMBER_INT);
$message        = filter_var($_POST["message"], FILTER_SANITIZE_STRING);

//additional php validation
if(strlen($name)<4){ // If length is less than 4 it will output JSON error.
    $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!'));
    die($output);
}
if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //email validation
    $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
    die($output);
}
if(!filter_var($telephone, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field
    $output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number'));
    die($output);
}
if(strlen($message)<3){ //check emtpy message
    $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
    die($output);
}

//email body
$message_body = $message."\r\n\r\n-".$name."\r\nEmail : ".$email."\r\nPhone Number :". $telephone;

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

$send_mail = mail($to_email, $subject, $message_body, $headers);

if(!$send_mail)
{
    //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
    $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 your email'));
    die($output);
}
}
    ?>

如何让网站发送AJAX请求?它一直停留在第一个PHP代码中,并返回'对不起请求必须是Ajax POST'。我在基本的GoDaddy Linux服务器上运行。

感谢所有JS专家!

1 个答案:

答案 0 :(得分:4)

您正在点击按钮#submit_btn发送表单。您需要阻止表单的提交按钮的默认事件。

使用$ _SERVER ['HTTP_X_REQUESTED_WITH'],您正在检查是否通过ajax请求访问该文件,并且因为您没有通过ajax发送它,您会收到错误“抱歉请求必须是Ajax POST”。

因此,为了防止在提交按钮上实际提交表单,您需要添加

$("#submit_btn").click(function(e) { 
    e.preventDefault();
    //Rest of your code

});

你也可以这样试试

$('form').on('submit', function (e) {
      e.preventDefault();
    //Rest of your code
});

您可以在表单提交上运行代码,而不是单击“提交”按钮。