【问题标题】:ajax skips response from phpajax 跳过 php 的响应
【发布时间】:2017-02-03 09:48:18
【问题描述】:

我试图通过 AJAX 传递 PHP 回显值,但在成功函数 AJAX 跳过 if 和 else 条件并执行 else 语句,即使 if 条件满足。

下面是我的php和ajax代码

process_postadd.php

if(isset($_POST['btn-postAdd'])){
$istate = strip_tags($_POST['txt_istate']);
$iname = strip_tags($_POST['txt_iname']);   
if(empty($iname)){
    echo '1'; //check if iten name is empty
}
else{
try
    {   
        if($insertItem = $postItem->postAdd($istate,$iname)){
            echo "ok"; //sucessfully inserted
        }           
    }
    catch(PDOException $e)
    {
        echo $e->getMessage();
    }   
}   
}

script.js

$('document').ready(function()
{ 
 /* validation */
 $("#postAddForm").validate({
  rules:
  {
        txt_istate: {
        required: true
        },
        txt_iname: {
            required: true
        },
   },
   messages:
   {

        txt_istate: {
        required: "state required"
        },
        txt_iname: {
            required:  "item name required"
        },
   },
   submitHandler: submitForm    
   });  
   /* validation */

   /* postadd submit */
     function submitForm()
   {        
        var data = $("#postAddForm").serialize();

        $.ajax({

        type : 'POST',
        url  : 'process_postadd.php',
        data : data,
        beforeSend: function()
        {   
            $("#error").fadeOut();
            $("#btn-postAdd").html('<span class="glyphicon glyphicon-transfer"></span> &nbsp; posting ...');
        },
        success :  function(response)
           {                        
                if(response == "ok"){

                    $("#btn-postAdd").html('<img src="btn-ajax-loader.gif" /> &nbsp; Submiting item ...');
                    setTimeout(' window.location.href = "index.php"; ',4000);
                }
                else if(response == "1"){
                    $("#error").fadeIn(1000, function(){
                        $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; Sorry, add item name</div>');
                        $("#btn-postAdd").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; SIGN U');
                        });

                }
                else{

                    $("#error").fadeIn(1000, function(){                        
            $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+response+' !</div>');
                                        $("#btn-postAdd").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Submit Item');
                                });
                }
          }
        });
            return false;
    }
   /* postadd submit */
});

HTML 代码

<div class="col-sm-12">
                        <div id="error">
                        <!-- error will be shown here ! -->
                        </div>
                            <form method= "POST" class="form-horizontal" enctype="multipart/form-data" id="postAddForm">
                                <fieldset>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label">Item condition</label>

                                        <div class="col-md-8">
                                            <label class="radio-inline" for="radios-00">
                                                <input name="txt_istate" id="radios-00" value="New"
                                                       type="radio">
                                                New</label>
                                            <label class="radio-inline" for="radios-11">
                                                <input name="txt_istate" id="radios-11" value="Used" 
                                                        type="radio">
                                                Used </label>
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label" for="Adtitle">Item Name</label>

                                        <div class="col-md-8">
                                            <input id="Adtitle" name="txt_iname" placeholder="name of item"
                                                   class="form-control input-md" type="text">
                                        </div>
                                    </div>
                                    <div class="form-group">
                                        <label class="col-md-3 control-label"></label>

                                        <button class="btn btn-success" name="btn-postAdd" id="btn-postAdd" type="submit">
                                                 <span class="glyphicon glyphicon-log-in"></span> &nbsp; Submit Item 
                                           </button>
                                    </div>
                                </fieldset>
                            </form>
                        </div>

【问题讨论】:

  • 如何在控制台中查看,console.log 响应以查看它是否确实是“ok”或“1” - 也尝试从命令行调用 PHP 并启用 PHP 错误检查和 GET代替 POST
  • 启用 PHP 错误检查后不显示错误
  • 请分享完整的 ajax 请求以提供更多帮助...以及您为 ajax 请求设置的数据类型。可能的情况是响应的格式与 ajax 所期望的不同。
  • 您是否从您的 php 中漏掉了这个 '}'?
  • 问题实际上是当 PHP 脚本回显“ok”或“1”时,ajax 响应会跳过 if 和 else if 的条件并执行 else 条件

标签: javascript php jquery ajax


【解决方案1】:

我不确定,但请尝试使用 echo json_encode 并添加一个 console.log(response) 以检查返回

   if($insertItem = $postItem->postAdd($istate,$iname)){
        echo json_encode("ok"); //sucessfully inserted
    } 

   if(empty($iname)){
        echo json_encode('1'); //check if iten name is empty
   }

【讨论】:

  • 它实际上通过 else 条件回显“ok”或“1”
【解决方案2】:

这应该可行,我认为在您的 php 中您实际上不需要检查名称是否为空,您已经使用 `jquery.validate();' 完成了该操作

如果你成功删除这个

else if(response == "1"){
                    $("#error").fadeIn(1000, function(){
                        $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; Sorry, add item name</div>');
                        $("#btn-postAdd").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; SIGN U');
                        });

                }

并且在你的 php 中删除这个

if(empty($iname)){
    echo '1'; //check if iten name is empty
}

这已经被你在validate()的规则处理了

那么您的代码将如下所示:

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>
<script type="text/javascript" src="admin_assets/js/validation.min.js"></script>// ignore this was for my test
<script type="text/javascript">

  $('document').ready(function()
{ 
 /* validation */
 $("#postAddForm").validate({
  rules:
  {
        txt_istate: {
        required: true
        },
        txt_iname: {
            required: true
        },
   },
   messages:
   {

        txt_istate: {
        required: "state required"
        },
        txt_iname: {
            required:  "item name required"
        },
   },
   submitHandler: submitForm    
   });  
   /* validation */

   /* postadd submit */
     function submitForm()
   {        
        var data = $("#postAddForm").serialize();

        $.ajax({

        type : 'POST',
        url  : 'process_postadd.php',
        data : data,
        beforeSend: function()
        {   
            $("#error").fadeOut();
            $("#btn-postAdd").html('<span class="glyphicon glyphicon-transfer"></span> &nbsp; posting ...');
        },
        success :  function(response)
           {                        
                if(response == "ok"){

                    $("#btn-postAdd").html('<img src="btn-ajax-loader.gif" /> &nbsp; Submiting item ...');
                    setTimeout(' window.location.href = "index.php"; ',4000);
                }
                else{

                    $("#error").fadeIn(1000, function(){                        
            $("#error").html('<div class="alert alert-danger"> <span class="glyphicon glyphicon-info-sign"></span> &nbsp; '+response+' !</div>');
                                        $("#btn-postAdd").html('<span class="glyphicon glyphicon-log-in"></span> &nbsp; Submit Item');
                                });
                }
          }
        });
            return false;
    }
   /* postadd submit */
});
</script>


<div id="error"></div>

<form method="POST" id="postAddForm" action="">
  <input type="text" name="txt_istate" id="txt_istate">
  <input type="text" name="txt_iname" id="txt_iname">
  <button type="submit" name="btn-postAdd" id="btn-postAdd">submit</button>
</form>

忽略我的表格,它是为了我这边的测试目的。您已经有了自己的表单

然后是你的 php

<?php

if (isset($_POST['btn-postAdd'])) {

    $istate = strip_tags($_POST['txt_istate']);
    $iname  = strip_tags($_POST['txt_iname']);

    try {
        if ($insertItem = $postItem->postAdd($istate, $iname)) {
            echo "ok"; //sucessfully inserted
        } else {

            echo "could not add item";
        }
    }
    catch (PDOException $e) {
        echo $e->getMessage();
    }
}
?>

你现在可以走了。

还要考虑 Auris 的评论。

【讨论】:

  • @Masivuyeit 仍然通过错误 ID 发送“ok”
  • 你能把表格也发一下吗@Optimistic
  • 请问你建议我做什么
猜你喜欢
  • 2012-11-26
  • 1970-01-01
  • 1970-01-01
  • 2022-07-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多