在AJAX查询中返回PHP响应

时间:2014-11-06 02:38:53

标签: php jquery ajax

我想将一个表单提交给PHP脚本,让脚本发挥其魔力,然后将所述魔法返回到div中,作为其成功/失败/状态变化的直观指示。

我提交了一份表格(我已经删除了很多无关的输入/文本区域等代码并不重要):

HTML:

<form name="ajaxform" id="ajaxform" method="post" action="ajax.php">
<table>
<tr class="left"> 
<td>Reporter:</td>
<td>//list of people</td>
</tr>
<tr class="left"> 
<td width="75%">
<p><label for="start">Start:</label>
<input type="text" name="start" id="start"></p>
<p><label for="end">End:</label>
<input type="text" name="end" id="end"></p>
</td>
</tr>
<tr>
<td>
<input name="sid" type="hidden" id="sid" value="<?=$sid?>"> 
<input name="table" type="hidden" id="table" value="add"> 
<input name="submit" type="submit" id="submit" value="Submit" class="submitForm"> 
</td>
</tr>
</form>
<div id="messageResponse"></div>

在提交时,以下JS运行:

JS:

$(function() {
    $('#ajaxform').validate({ // initialize the plugin
        errorClass: "invalid", 
        submitHandler: function (form) {

        $.ajax({
                type:'POST',
                url:'ajax.php',
                data: $(form).serialize(),
                success: function() {
                    $('#messageResponse').fadeIn(500);
                    $('#messageResponse').addClass('ui-state-highlight ui-corner-all').removeClass('ui-state-error');
                    $('#messageResponse').text('Success!' + result);                        
                },
                error: function (xhr, ajaxOptions, thrownError) {
                    $('#messageResponse').fadeIn(500);
                    $('#messageResponse').addClass('ui-state-error ui-corner-all').removeClass('ui-highlight-error');
                    $('#messageResponse').text(xhr.status + ' ' + thrownError + ': Something went wrong - check your inputs and try again.');
                }

        });

        setTimeout(function(){ $('#messageResponse').fadeOut(500); }, 5000);

        // resets fields
        $('#ajaxform')[0].reset();
    }
});

});

然后我根据从表单的隐藏表输入传递的表变量,从几个PHP脚本列表中挑选出脚本:

PHP:

if($_POST['table'] == "add"){

// Do mysql query which gives me an array

    $result = array("foo" => "bar", "captain" => "coke");
    echo(json_encode($result));
}

我想提交我的表单,让它在ajax.php中找到相应的代码并执行它,然后将该PHP脚本的结果返回给messageResponse div。这种悲惨的失败在哪里?

3 个答案:

答案 0 :(得分:3)

您应该在result方法中传递success变量:

success: function (result) {
    console.log(result);
}

另外:

  1. 设置您希望从服务器返回的数据类型:

    dataType: 'json'
    
  2. 将结果标题设置为JSON(在PHP文件中):

    header('Content-Type: application/json; charset=utf-8');
    

答案 1 :(得分:0)

只需添加:

$.ajax(...,dataType: "json",...);

答案 2 :(得分:0)

只需从表单中移除操作即可使用此

<form name="ajaxform" id="ajaxform" method="post" action="#">