繁体   English   中英

如何发送对PHP表单的AJAX请求

[英]How to send an AJAX request for PHP form

尝试发送消息数小时的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专家!

您正在通过单击#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
});

您可以在表单提交上运行代码,而无需单击提交按钮。

暂无
暂无

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

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