【问题标题】:How to send an AJAX request for PHP form如何为 PHP 表单发送 AJAX 请求
【发布时间】:2014-10-24 20:29:54
【问题描述】:

已经尝试发送消息几个小时了,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 专家!

【问题讨论】:

  • 对于 AJAX,您不必使用 method="POST" action="contact_me.php" 来提交表单。这一切都应该在你的 JavaScript 中得到照顾。
  • 回显 $_SERVER['HTTP_X_REQUESTED_WITH'] 看看你是否得到正确的结果

标签: javascript php jquery ajax


【解决方案1】:

您通过点击按钮#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
});

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

【讨论】:

  • 我在我的 JS 上添加了代码,经过测试,仍然没有。完整的 JS 看起来如何?我在结束正文标记之前有它。
  • 试试我在答案中添加的第二个选项。使用表单提交事件。阻止它,并使用 ajax 发送表单。
  • 谢谢 - 解决了发送问题,现在我看到它没有获取文本区域中的值,它一直在输出“消息太短”
  • 我尝试删除 strlen 检查器,但现在提交时没有任何反应。 @bojan,我非常乐意为您的努力付出代价,我真的很感激!
  • 当我们在这里的时候,你不需要付钱给我。至于你的问题,尝试打印出$message。查看该变量中存储的内容:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-11
  • 1970-01-01
  • 2013-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-06
相关资源
最近更新 更多