在AJAX中捕获PHP文件响应

时间:2018-02-12 12:52:45

标签: php jquery ajax

标题说明了一切,我需要验证数据并允许用户进入我的模态中的下一步。我正在向PHP文件发送AJAX请求。 PHP文件应该如何返回数据?

        <script type="text/javascript">
            $('#reg_btn').on('click', function(){
              $.ajax({
                      type: "POST",
                      url: 'checksubscriber.php',
                      dataType: 'json',
                      data: {
                        email: $('# .email').val(),
                      },
                      success: function(response) {
                        // User has been successfully subscribed
                        // Do something here
                      },
                      error: function (jqXHR, textStatus, errorThrown) {

                  }

                    });

                    e.preventDefault();
                    return false;
                });
    </script>

Checksubscriber.php

        <?php
    require("vendor/autoload.php");

    use \DrewM\MailChimp\MailChimp;
    $mc = new MailChimp('api_key_goes_here'); 

    $email = $_POST['email'];
    $subscriber_hash = $mc->subscriberHash($email);

    $response = [];
    $list_id = 'list_id_goes_here';

    $resp = $mc->get("/lists/$list_id/members/$subscriber_hash";

    if ($mc->success()) {

        // User successfully subscribed - set HTTP status code to 200
        http_response_code(200);
    } else {

        // User not subscribed - set HTTP status code to 400
        http_response_code(400);
    }

    // Return json-formatted response
    echo json_encode($response); 
    ?>

模式的HTML + JS

    <button type="submit" onclick="document.getElementById('id01').style.display='block'" > HERE IS MY BUTTON </button>
    <!-- multistep form -->
    <div id="id01" class="modalx modalx-style_set">
    <form id="msform">
    <!-- progressbar -->
    <ul id="progressbar">
    <li class="active">LOG IN</li>
    <li>TERMS</li>
    <li>INFO</li>
    </ul>
    <!-- fieldsets -->
    <fieldset>
    <input type="text" name="email" placeholder="Email" />
    <input type="button" name="next" class="next action-button" value="Next" />
    </fieldset>
    <fieldset>
    <input type="text" name="address" placeholder="Complete address" />
    <input type="button" name="previous" class="previous action-button" value="Back" />
    <input type="button" name="next" class="next action-button" value="Next" />
    </fieldset>
    <fieldset>
    <input type="button" name="previous" class="previous action-button" value="Back" />
    </fieldset>
    </form>

        <script>
//jQuery time
   $(document).ready(function(){
     var modalx = document.getElementById('id01');

     // When the user clicks anywhere outside of the modal, close it
     window.onclick = function(event) {
         if (event.target == modalx) {
             modalx.style.display = "none";
         }
     }

   var current_fs, next_fs, previous_fs; //fieldsets
   var left, opacity, scale; //fieldset properties which we will animate
   var animating; //flag to prevent quick multi-click glitches

   $(".next").click(function(){
     if(animating) return false;
     animating = true;

     current_fs = $(this).parent();
     next_fs = $(this).parent().next();

     //activate next step on progressbar using the index of next_fs
     $("#progressbar li").eq($("fieldset").index(next_fs)).addClass("active");

     //show the next fieldset
     next_fs.show();
     //hide the current fieldset with style
     current_fs.animate({opacity: 0}, {
       step: function(now, mx) {
         //as the opacity of current_fs reduces to 0 - stored in "now"
         //1. scale current_fs down to 80%
         scale = 1 - (1 - now) * 0.2;
         //2. bring next_fs from the right(50%)
         left = (now * 50)+"%";
         //3. increase opacity of next_fs to 1 as it moves in
         opacity = 1 - now;
         current_fs.css({'transform': 'scale('+scale+')'});
         next_fs.css({'left': left, 'opacity': opacity});
       },
       duration: 800,
       complete: function(){
         current_fs.hide();
         animating = false;
       },
       //this comes from the custom easing plugin
       easing: 'easeInOutBack'
     });
   });
   </script>

我需要在这里写一些内容才能发布代码的最后一部分。我的问题主要是代码......

3 个答案:

答案 0 :(得分:2)

无论您返回什么或从Checksubscriber.php回显数据,它都会记录为响应。响应函数中的警报数据就像我在下面的代码中所做的那样。

<script type="text/javascript">
                $('#reg_btn').on('click', function(){
                  $.ajax({
                          type: "POST",
                          url: 'checksubscriber.php',
                          dataType: 'json',
                          data: {
                            email: $('# .email').val(),
                          },
                          success: function(response) {
                            alert(response); 
                      },
                          error: function (jqXHR, textStatus, errorThrown) {

                      }

                        });

                        e.preventDefault();
                        return false;
                    });
        </script>

答案 1 :(得分:1)

读取响应值,如

success: function(response) {
    var msg = response.message;
    // do with msg whatever you want
},

是的,你的PHP代码看起来很好,除了Vinod指出的语法错误。 使用http_response_code(400);让ajax知道它不是很成功!

修改:将response['message']替换为response.message

答案 2 :(得分:1)

<script type="text/javascript">
    $('#reg_btn').on('click', function(event){
         $.ajax({
           type: "POST",
           url: 'checksubscriber.php',
           dataType: 'json',
           data: {
             email: $('# .email').val(),
           },
           success: function(response) {
             $('#block1').hide(); //Adds display:none
             $('#block2').show(); //Removes display:none
           },
           error: function (jqXHR, textStatus, errorThrown) {
             console.log(jqXHR, textStatus, errorThrown); 
           }
         });
         event.preventDefault();
         return false;
   });
</script>

尝试将console.log(响应)放入成功函数中。在执行任何操作之前,重新加载页面并打开浏览器控制台。之后单击该元素。

现在,您应该能够在浏览器控制台中看到PHP文件响应的输出。

您可以使用 response.message 访问来自回复对象的邮件。

Dot(。)运算符可用于访问JSON对象内的参数。您无法像回复['消息']那样访问它。因为您从PHP文件发送JSON对象。

使用以下代码替换您的字段集

<!-- fieldsets -->
<fieldset id="block1">
    <input type="text" name="email" placeholder="Email" />
    <input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset id="block2" style="display:none">
    <input type="text" name="address" placeholder="Complete address" />
    <input type="button" name="previous" class="previous action-button" value="Back" />
    <input type="button" name="next" class="next action-button" value="Next" />
</fieldset>
<fieldset id="block3" style="display:none">
     <input type="button" name="previous" class="previous action-button" value="Back" />
</fieldset>