Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/477.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何发送PHP表单的AJAX请求_Javascript_Php_Jquery_Ajax - Fatal编程技术网

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

Javascript 如何发送PHP表单的AJAX请求,javascript,php,jquery,ajax,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"> &

已尝试发送邮件数小时,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();
});
});
联系人_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专家

单击“提交”按钮即可发送表单。您需要防止表单的“提交”按钮出现默认事件

使用$\u服务器['HTTP\u X\u REQUESTED\u 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
});

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

您正在单击“提交”按钮发送表单。您需要防止表单的“提交”按钮出现默认事件

使用$\u服务器['HTTP\u X\u REQUESTED\u 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
});

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

对于AJAX,您不必使用method=POST action=contact_me.php进行表单提交。在您的JavaScript.Echo$_服务器['HTTP\u X\u REQUESTED\u WITH']中应该注意这一点,并查看您是否获得了AJAX的正确内容,您不必使用method=POST action=contact\u me.php提交表单。在你的JavaScript.Echo$_服务器['HTTP\u X\u REQUESTED\u WITH']中应该注意这一切,看看你是否得到了正确的东西。我在我的JS上添加了代码,经过测试,仍然一无所获。完整的JS在你这边看起来如何?我把它放在我的结束体标签之前。用我在答案中添加的第二个选项试试。使用表单提交事件。阻止它,并用ajax发送表单。谢谢-这解决了发送问题,现在我看到它没有得到文本区域中的值,它一直输出“太短消息”。我尝试删除strlen检查器,但现在提交时什么也没有发生@博扬,我很高兴为你的努力付出,我真的很感激!我们在这里的时候,你不需要付钱给我,所以。至于您的问题,请尝试打印$message。看看这个变量中存储了什么:我在我的JS上添加了代码,经过测试,仍然一无所获。完整的JS在你这边看起来如何?我把它放在我的结束体标签之前。用我在答案中添加的第二个选项试试。使用表单提交事件。阻止它,并用ajax发送表单。谢谢-这解决了发送问题,现在我看到它没有得到文本区域中的值,它一直输出“太短消息”。我尝试删除strlen检查器,但现在提交时什么也没有发生@博扬,我很高兴为你的努力付出,我真的很感激!我们在这里的时候,你不需要付钱给我,所以。至于您的问题,请尝试打印$message。查看该变量中存储的内容: