【问题标题】:post php response into div using ajax not working使用ajax将php响应发布到div中不起作用
【发布时间】:2015-12-16 15:42:55
【问题描述】:

您好,我目前正在做一个项目。当用户提交表单时,它会将响应加载到 div 中,而不是加载新页面。我在网上查看了与 PHP 一起工作的 ajax 表单的其他示例,但它并没有帮助我解决我的问题。 (我对此比较陌生)。

当我点击提交时,不是将回复发布到同一页面并发送电子邮件到所选的电子邮件地址,而是将我带到 php 文件并在那里回显回复,但不发送任何电子邮件。

谁能看出这是哪里出了问题?

表格代码:

<form name="contactform" id="contact-form" action="mailer.php">

            <input type="text" class="textbox" name="name" value="Name" required="required" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name';}">

            <input type="text" class="textbox" name="email" value="Email" required="required" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email';}">

            <textarea name="message" value="Message:" required="required" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Message';}">Message</textarea>

           <input type="submit" value="Send Now">

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

Javascript 代码:

<script>
 $("#contactform").submit(function(event) 
 {
     /* stop form from submitting normally */
     event.preventDefault();

     /* get some values from elements on the page: */
     var $form = $( this ),
         $submit = $form.find( 'button[type="submit"]' ),
         name_value = $form.find( 'input[name="name"]' ).val(),
         email_value = $form.find( 'input[name="email"]' ).val(),
         message_value = $form.find( 'textarea[name="message"]' ).val(),
         url = $form.attr('action');

     /* Send the data using post */
     var posting = $.post( url, { 
                       name: name_value, 
                       email: email_value, 
                       message: message_value 
                   });

     posting.done(function( data )
     {
         /* Put the results in a div */
         $( "#response" ).html(data);

     });
});
</script>

PHP 代码:(我的 php 存储在一个名为 mailer.php 的单独文件中)我正在尝试将 PHP $response 变量回发并放入响应 div。

<?php


    // Get the form fields and remove whitespace.
    $name = $_POST["name"];
    $email = $_POST["email"];
    $message = $_POST["message"];

    $to = "your-emailaddresshere@email.com";
    $subject = "New DPS Email from $name";

    // Build the email content.
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    // Build the email headers.
    $email_headers = "From: $name <$email>";

    $mailed = (mail($to, $subject, $email_content, $email_headers));

    if( isset($_POST['ajax']) )
    $response = ($mailed) ? "1" : "0";
    else
    $response = ($mailed) ? "<h2>Thank You! Your message has been sent.</h2>" : "<h2>Oops! Something went wrong and we couldn't send your message.</h2>";

    echo $response; 

?>

提前感谢您的帮助!

【问题讨论】:

  • 您是否在浏览器的控制台中查看过错误?
  • $.post 中有 var url。愚蠢的问题,但我猜你的代码中的其他地方设置为你的 php 脚本的 url
  • @Y.Hermes 我试过了,不幸的是它似乎并没有改变结果
  • @IWebb 我不确定它是否真的正常工作,但它应该从表单上的 action 变量中获取 php 脚本的 url。我刚刚意识到我的帖子中没有包含它,现在会更新它
  • 我知道这个网站是关于一个 JQuery 插件的,但是有一个很好的部分介绍了如何在 chrome 中调试 ajax 请求。 datatables.net/manual/tech-notes/7 诊断位是适用于所有 ajax 请求的有趣位

标签: javascript php jquery html ajax


【解决方案1】:

纠正此问题并报告发生的情况,

您的表单 ID 是“contact-form”,并且您的 JQ 选择器已设置为“contactform”。

$("#contactform")

$("#contact-form")

【讨论】:

  • 非常感谢,这似乎是让它发布到 div 的答案!总是错字!出于某种原因,它仍然没有发送电子邮件:S
【解决方案2】:

您可以执行以下操作: 表单代码

<form name="contactform" id="contact-form">
    <!--Your form elements here -->
</form>

javascript 代码(使用 #contact-form 而不是 #contactform

<script>
$("#contact-form").submit(function(event) 
{
 /* stop form from submitting normally */
 event.preventDefault();

 /* get some values from elements on the page: */
 var $form = $( this ),
     $submit = $form.find( 'button[type="submit"]' ),
     name_value = $form.find( 'input[name="name"]' ).val(),
     email_value = $form.find( 'input[name="email"]' ).val(),
     message_value = $form.find( 'textarea[name="message"]' ).val(),
     url = 'your_url_here';

 /* Send the data using post */
 var posting = $.post( url, { 
                   name: name_value, 
                   email: email_value, 
                   message: message_value 
               });

 posting.done(function( data )
 {
     /* Parse JSON */
     var response = JSON.parse(data);
     $("#response").html(response.msg);

    });
 });
</script>

您的 PHP 代码:

<?php


// Get the form fields and remove whitespace.
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];

$to = "your-emailaddresshere@email.com";
$subject = "New DPS Email from $name";

// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Email: $email\n\n";
$email_content .= "Message:\n$message\n";

// Build the email headers.
$email_headers = "From: $name <$email>";

$mailed = mail($to, $subject, $email_content, $email_headers);

if( $mailed )
$response = json_encode(array("status"=>true,"msg"=>"<h2>Thank You! Your message has been sent.</h2>"));
else
$response = json_encode(array("status"=>false,"msg"=>"<h2>Oops! Something went wrong and we couldn't send your message.</h2>"));

echo $response; 

?>

【讨论】:

  • 非常感谢!这比我的原始代码更好,它对消息进行编码和解码,然后将其发布到数组中。我仍然遇到的唯一问题是,让电子邮件实际发送。虽然我想知道这是否是由于我使用了 cloud 9 ide
  • 欢迎@HipHipArray。对于邮件问题,您可以咨询您的托管服务提供商
【解决方案3】:

这是因为你调用的是 post 函数,而不是 ajax。

试试这个:

$.ajax({
   url: <your_url>,
   type:'GET',
   data: {'name': name_value, 'email' : email_value, 'message': message_value},
   success: function(data){
        yourdivcontent =  eval(data)
        $( "#response" ).html(yourdivcontent);
   }, 
   error: function(){
        console.log("error");
   }
})

在您的 php 函数中,只需将您的响应编码为 json

返回 json_encode(响应);

【讨论】:

  • 感谢您的评论,无论出于何种原因,我在此行“数据:{'name': name_value, 'email': email_value, 'message': message_value}," 另外我假设您放置了您的 div 内容的部分,这需要替换为我从 php 邮件程序脚本传回的变量吗?最后,如果我是JSON_encoding,我需要解码吗?抱歉所有问题,我对此很陌生,并试图了解每个部分在做什么
  • 我忘记在 ajax 调用中添加“类型”值。我编辑了我的答案。是的,您必须将变量放入您的 div 中。数据将返回一个 json 字符串
  • 由于某种原因,它一直给我那个意外的令牌错误。关于可能导致这种情况的任何想法?提前致谢
  • 尝试取消引用数据行,比如这个数据:{ name: name_value, and so on }
【解决方案4】:

echo json_encode($response) 在 php 函数的末尾

【讨论】:

  • 不幸的是,这只是在 php 页面上仍然存在
猜你喜欢
  • 1970-01-01
  • 2016-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多