使用php提交ajax表单

Posted

技术标签:

【中文标题】使用php提交ajax表单【英文标题】:ajax form submission with php 【发布时间】:2012-12-17 23:59:57 【问题描述】:

我在发送电子邮件时遇到问题,我确定这是因为 php,但这里也是 js ajax..它显示了我未正确填写的表单字段的错误消息,然后显示了我的处理栏一旦提交,但提交后我收到错误消息。任何帮助将不胜感激。

html

<form method="post" action="feedback.php" id="contactform">
            <fieldset class="first">


            <div id="response"></div>  


            <div id="name_input">

            <input id="name" name="name" placeholder="Name" class="required" type="text" maxlength="128" />

            </div>



            <div id="email_input">

            <input id="email" name="name" placeholder="Email"  class="required" type="text"  maxlength="128" />

            </div>



            <div id="budget_input">
            <label for="budget">Budget</label>
            <select id="mydropdown">
            <option value="none" selected=“”> -- choose one --</option>
            <option value="firstchoice">$0 - $1,000</option>
            <option value="secondchoice">$1,000 - $2,000</option>
            <option value="thirdchoice">$3,000 +</option>
            </select>
            </div>



            <div id="button">

            <input type="submit" class="button" name="Submit" value="" />
            </div>


            </fieldset>


        </form>

更新:

<?php 

$name = trim(stripslashes(htmlspecialchars($_POST['name'])));           
$email = trim(stripslashes(htmlspecialchars($_POST['email'])));
$mydropdown = trim(stripslashes(htmlspecialchars($_POST['mydropdown'])));  
$recipient = "blake.harrison1@cox.net";  
$humancheck = $_POST['humancheck'];
$honeypot = $_POST['honeypot'];



    if ($honeypot == 'http://' && empty($humancheck))  

    //Validate data and return success or error message
    $error_message = '';    
    $reg_exp = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]2,4$/";

    if (!preg_match($reg_exp, $email)) 

                $error_message .= "<p>A valid email address is required.</p>";             
    
    if (empty($name)) 

                $error_message .= "<p>Please provide your name.</p>";              
    

    if (empty($mydropdown)) 

                $error_message .= "<p>Please select an item from the list.</p>";
                   

    if (!empty($error_message)) 
                $return['error'] = true;
                $return['msg'] = "<h3>Oops! The request was successful but your form is not filled out correctly.</h3>".$error_message;                 
                echo json_encode($return);
                exit();
         else 

        //send to  an email


        $emailSubject = 'Top Contact Form';
        $webMaster = 'blake.harrison1@cox.net';

 $body="
 <br><hr><br>
 <strong>Name:</stong> $name <br>
 <br>
 <strong>Email:</stong> $email <br>
 <br>
 <strong>Budget:</strong> $mydropdown <br>
 <br>
 ";      

        $headers = "From: $email\r\n";
        $headers .= "Content-type: text/html\r\n";


        //send email and return to user
        if(mail($webMaster, $emailSubject, $body, $headers)) 

            $return['error'] = false;
            $return['msg'] = "<p>Message sent successfully. Thank you for your interest " .$name .".</p>"; 
            echo json_encode($return);
        
       
  else 

$return['error'] = true;
$return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>";  
echo json_encode($return);
 

?> 



$(document).ready(function() 

$('form #response').hide();

$('#submit').click(function(e) 

    // prevent forms default action until
    // error check has been performed
    e.preventDefault();

    // grab form field values
    var valid = '';
    var required = ' is required.';
    var name = $('form #name').val();
    var email = $('form #email').val();
    var mydropdown = $('form #mydropdown').val();
    var honeypot = $('form #honeypot').val();
    var humancheck = $('form #humancheck').val();


    // perform error checking
    if (name == '' || name.length <= 2) 
        valid = '<p>Your name' + required +'</p>';  
    

    if (!email.match(/^([a-z0-9._-]+@[a-z0-9._-]+\.[a-z]2,4$)/i)) 
        valid += '<p>Your email' + required +'</p>';                                                  
    

    if (mydropdown == '') 
        valid += '<p>An item from the list' + required +'</p>';

    

    if (honeypot != 'http://') 
        valid += '<p>Spambots are not allowed.</p>';    
    

    if (humancheck != '') 
        valid += '<p>A human user' + required + '</p>'; 
    


    // let the user know if there are erros with the form
    if (valid != '') 

        $('form #response').removeClass().addClass('error')
            .html('<strong>Please correct the errors below.</strong>' +valid).fadeIn('fast');           
    
    // let the user know something is happening behind the scenes
    // serialize the form data and send to our ajax function
    else 

        $('form #response').removeClass().addClass('processing').html('Processing...').fadeIn('slow');                                      

        var formData = $('form').serialize();
        submitForm(formData);           
               

);
);


function submitForm(formData) 

$.ajax(    
    type: 'POST',
    url: 'send.php',        
    data: formData,
    dataType: 'json',
    cache: false,
    timeout: 12000,
    success: function(data)            

        $('form #response').removeClass().addClass((data.error === true) ? 'error' : 'success')
                    .html(data.msg).fadeIn('fast'); 

        if ($('form #response').hasClass('success')) 

            setTimeout("$('form #response').fadeOut('fast')", 12000);
        

    ,
    error: function(XMLHttpRequest, textStatus, errorThrown) 

        $('form #response').removeClass().addClass('error')
                    .html('<p>There was an<strong> ' + errorThrown +
                          '</strong> error due to a<strong> ' + textStatus +
                          '</strong> condition.</p>').fadeIn('fast');           
    ,              
    complete: function(XMLHttpRequest, status)             

        $('form')[0].reset();
    
); 
;

【问题讨论】:

您从 ajax 请求返回的确切消息是什么? 我收到超时条件,或者有时我收到“糟糕!请求成功,但您的表单未正确填写。需要有效的电子邮件地址。需要留言。” 半新的 php,以为我在某处读到它是为了离线目的,我删除了它但没有改变 【参考方案1】:

你可以试试 $.post 而不是 $.ajax

$.post(url, argument_name: value, ... , function(data)

// callback function..

, 'json'

【讨论】:

所以你的意思是 $.post( type: 'POST', url: 'feedback.php', data: formData, dataType: 'json', cache: false, timeout: 7000, success : 函数(数据) 将其更改为发布,现在它只是继续说正在处理,但仍然没有提交电子邮件 不,试试这个 $.post("feedback.php", name: value_to_be_posted, email: email_to_be_posted, message: message_to_be_posted, fucntion(data), 'json' 你可以在这里查看一些实例:api.jquery.com/jQuery.post 嘿,谢谢您的回复。我今天早上看到了这些电子邮件。我更新了我的代码。我相信只有最上面的横幅联系表单会抛出错误,并且联系人页面现在正在工作,所以我把代码放在那里【参考方案2】:

使用 php 页面执行此操作...

  sleep(2);
  //Sanitize incoming data and store in variable
  $name = trim(stripslashes(htmlspecialchars($_POST['name'])));           
  $email = trim(stripslashes(htmlspecialchars($_POST['email'])));
  $message = trim(stripslashes(htmlspecialchars($_POST['message']))); 
  $recipient = "info@internetmarketingtrio.com";



//Validate data and return success or error message
$errors = array();   
$reg_exp = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9-]+\.[a-zA-Z.]2,4$/";

if (!preg_match($reg_exp, $email)) 

            $errors[] = "<p>A valid email address is required.</p>";             

if (empty($name) || $name == '') 

            $errors[] = "<p>Please provide your name.</p>";              
           
if (empty($message) || $message == '') 

            $errors[] = "<p>A message is required.</p>";

if(empty($errors)) 
    $return['success'] = true;
    $return['message'] = "<p>Thanks for your feedback " .$name. ".</p>";
 else 
    $return['success'] = false;
    $return['message'] = "<h3>Oops! The request was successful but your form is not filled out correctly.</h3>";
    foreach($errors as $error) 
        $return['message'] .= $error ."<br />";
    

然后在你的调用中获取这个页面……ajax调用……

$.ajax(    
type: 'POST',
url: 'feedback.php',        
data: formData,
dataType: 'json',
cache: false,
success: function(data)  
    if(data.success) 
        $("form#response").removeClass().addClass('success').html(data.message).fadeIn('fast');
        removeResponse(5000);
     else 
        $("form#response").removeClass().addClass('error').html(data.message).fadeIn('fast'); 
    
        
); 

function removeResponse(time) 
    setTimeout(function() 
        $("form#response").fadeOut('fast');
    , time);

你应该这样做

【讨论】:

嗯,它仍然只是坐在那个正在处理的蓝色盒子上,没有给我我添加的成功课程或电子邮件:( 你在 chrome 中运行吗?如果是这样,在点击提交之前点击 F12 并打开网络选项卡,然后点击提交,您应该会看到您的 php 页面出现在那里。单击它,然后单击预览并将输出粘贴到此处 有趣,它没有给我任何输出预览 您的网络标签中的页面名称是否为红色?如果没有,那么 php 根本没有完成或者正在悄悄地出错。如果页面不是红色,那么在您的 php 页面顶部添加 error_reporting(E_ALL);哦,顺便说一句,删除睡眠(2) 通知未定义索引:第 4 行 D:\hosting\10203437\html\feedback.php 中的电子邮件通知第 5 行 D:\hosting\10203437\html\feedback.php 中的消息【参考方案3】:

如果有人阅读此内容,将其添加到我的 php 底部最终解决了我的问题

        $emailSubject = 'Contact Form';
        $webMaster = 'blake.harrison1@cox.net';

$body="
<br><hr><br>
<strong>Name:</stong> $name <br>
<br>
 <strong>Email:</stong> $email <br>
 <br>
 <strong>Message:</stong> $message 
";      

        $headers = "From: $email\r\n";
        $headers .= "Content-type: text/html\r\n";


        //send email and return to user
        if(mail($webMaster, $emailSubject, $body, $headers)) 

            $return['error'] = false;
            $return['msg'] = "<p>Message sent successfully. Thank you for your intrest " .$name .".</p>"; 
            echo json_encode($return);
        
       
 else 

$return['error'] = true;
$return['msg'] = "<h3>Oops! There was a problem with your submission. Please try again.</h3>";  
echo json_encode($return);
 

 ?> 

【讨论】:

以上是关于使用php提交ajax表单的主要内容,如果未能解决你的问题,请参考以下文章

使用 AJAX 向 PHP Web 服务提交基本表单数据

与 PHP 相呼应的表单未使用 ajax 提交

如何使用 AJAX 和 php 从 HTML 提交表单

使用 AJAX 和 PHP 提交表单并带有成功响应文本而不刷新页面

PHP symfony 4 ajax 表单提交

使用 php 和 ajax 调用在表单提交上上传单张图片