提交到PHP时出现AJAX错误

时间:2013-01-22 04:24:29

标签: php jquery ajax

我有一个基本表单,我提交了一个facebook朋友的ID,php返回我的名字,我的FB照片,我朋友的名字和我朋友的fb照片。这是我的相关代码

HTML

<form name="input">
<input type="text" name="name" id="name"/>
<input id="submit" type="submit" class="btn btn-info" value="Submit"/>
</form>

<div class="row" id="graphArea"></div>

JAVASCRIPT

$('#submit').click(function(e){
    e.preventDefault();
    var formData = $('form').serialize();
    submitForm(formData);
});

function submitForm(formData){
$.ajax({    
    type: 'POST',
    url: 'graph.php',        
    data: formData,
    dataType: 'json',
    cache: false,
    timeout: 7000,
    success: function(data) { 
        $("#graphArea").load("graph.php");
        $(window).scrollTop($("#graphArea").offset().top);
        $("#graphArea").fadeIn(500);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("There was an error");          
    },              
    complete: function(XMLHttpRequest, status) {            

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

graph.php

<?php
    require 'resources/plugin/facebook-php-sdk/src/facebook.php';
    //..some facebook authentication stuff
    $friend = $_POST['name'];
    $basicInfo = $fb->api('me?fields=friends.uid(' . $friend . ').fields(first_name,name),first_name,name');
 ?>
<hr>
<br />
<div class="span2 offset2"><h3>
<?php
    echo $basicInfo['name'] . "</h3></div><div class=\"span2\">";
    echo "<img src='https://graph.facebook.com/" . $user . "/picture?type=large'>";
    echo "</div><div class=\"span2\">";
    echo "<img src='https://graph.facebook.com/" . $friend . "/picture?type=large'></div>";
    echo "<div class=\"span2\"><h3>" . $basicInfo['friends']['data'][0]['name'];
?>
</h3>
</div>

每当我提交表单时,我都会收到错误部分,警告“发生了错误”。然而,通过Google Chrome Javascript控制台查看,然后点击网络然后预览,我看到了我想要的结果!这是我第一次处理PHP和AJAX,我很感激能得到的所有帮助。谢谢!

2 个答案:

答案 0 :(得分:2)

在您的javascript ajax调用中,您将dataType: 'json',称为php,而html将返回html,这将引发错误。如果您希望响应位于html中,请将数据类型更改为{{1}}。

答案 1 :(得分:1)

您对graph.php的ajax调用包括dataType: 'json',但graph.php似乎会输出HTML片段。此外,您的AJAX成功处理程序再次调用graph.php - 这是不必要的,因为您刚刚调用graph.php来提交表单。您应该取回返回的HTML并将其注入DOM:

$.ajax({    
    type: 'POST',
    url: 'graph.php',        
    data: formData,
    // REMOVED dataType
    cache: false,
    timeout: 7000,
    success: function(data) { 
        $("#graphArea").html(data);   // CHANGED
        $(window).scrollTop($("#graphArea").offset().top);
        $("#graphArea").fadeIn(500);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        alert("There was an error");          
    },              
    complete: function(XMLHttpRequest, status) {            

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