开发者

AJAX/PHP/Jquery Issue with callback

I can't seem to figure out why this won't work. I have stripped all elements out and have striped this done to a base example. can someone please tell me what I am doing wrong. When I click on the button on the html page I get my initial alert, but never get an alert from my call backs.

Here is the code for my html file. test.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="开发者_如何学Ctext/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://code.jquery.com/jquery-1.5.js"></script>

<script language="javascript" type="text/javascript"> 
$(document).ready(function()
{
$("#test").click(function()
{
    alert("!st");
    $.ajax({

        type : 'POST',

        url : 'test_ajax.php',

        dataType : 'json',

        data: {

        email : 'Jeremy'

        },

        success : function(data){

            alert(data.msg);

        },

        error : function(XMLHttpRequest, textStatus, errorThrown) {
            alert("error");
        }

    });
    return false;
});
});
</script>
</head>
<body>
<input name="test" id="test" type="button" value="Click Me"/>
<div id="results">
  Hello
</div>
</body>
</html>

Now for the php: test_ajax.php

<?php

if (empty($_POST['email'])) {

    $return['error'] = true;

    $return['msg'] = 'You did not enter you email.';

}

else {

    $return['error'] = false;

    $return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';

 }


 echo json_encode($return);
?>

Please any assistance would be much appreciated.

Thanks Jeremy


The code looks clean. Try to use php buffering. Put ob_start() at the very beginning of PHP file and in the code

// cleans the buffer
ob_clean();    
echo json_encode($return);
die();


I've just tried the exact code and it works ok. You've missed the opening php brackets (<?php) from the code listed above, but was that just a mistake?


I think you missed the opening of the php file and the declaration of $return as array. I tried this and it works fine:

<?
$return = array();
if (empty($_POST['email'])) {
    $return['error'] = true;
    $return['msg'] = 'You did not enter you email.';
}
else {
    $return['error'] = false;
    $return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
?>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜