Why my Ajax posting script not working?
I have barely created a script (as I'm just a beginner in ajax), in fact I have copied some part (ajax script) of it from somewhere. But when I click on the the link (vote up / vote down) nothing happens not even the value in Mysql database changes, but on click the submit button I got a change in my MySql Database! Here is my code --
-:::- HTML PART (test.php) -:::-
<html>
<title>
TEST
</title>
<head>
<script type="text/javascript" src="jquery.1.4.4.js"></script>
<script type="text/javascript">
function vote(type)
{
$.ajax({
'url': 'test.func.php',
'type': 'POST',
'dataType': 'json',
'data': {type: type},
'success': function(data)
{
if(data.status)
{
if(data.voted)
{
$(document).ready(function () {
$("span#status"+type).attr("innerHTML","You have voted up!");
});
}
else
{
$(document).ready(function () {
$("span#status"+type).attr("innerHTML","You ha开发者_如何学Cve voted Down!");
});
}
}
},
beforeSend: function()
{
$(document).ready(function () {
$("span#status"+type).attr("innerHTML","Voting....");
});
},
'error': function(data)
{
$(document).ready(function () {
$("span#status"+type).attr("innerHTML","An error occureed");
});
}
});
}
</script>
</head>
<body>
<a href="#" onclick="vote('up')" > Vote Up </a>
<span id="status_up" ></span>
<br>
OR
</br>
<a href="#" onclick="vote('down')" > Vote Down </a>
<span id="status_down" ></span>
</body>
</html>
-:::- PHP PART (test.func.php) -:::-
<?php
function db_connect($i)
{
if(isset($i))
{
if(mysql_connect('localhost', 'root', 'root'))
{
if(mysql_select_db($i))
{
return;
}
else
{
echo 'ERROR';
}
}
else
{
echo 'ERROR';
}
}
else
{
echo 'ERROR';
}
}
if($_POST)
{
db_connect('tests');
$vote_type=$_POST['type'];
$post_id = '123';
$query = mysql_query("SELECT * FROM test WHERE post_id='$post_id'");
$cur_vote_get = mysql_fetch_array($query);
$vote_up = $cur_vote_get['votes']+1;
$vote_down = $cur_vote_get['votes']-1;
if($vote_type=='up')
{
mysql_query("UPDATE test SET votes='$vote_up' WHERE post_id='$post_id'");
return json_encode(array("status" => true, "voted" => true));
}
elseif($vote_type=='down')
{
mysql_query("UPDATE test SET votes='$vote_down' WHERE post_id='$post_id'");
return json_encode(array("status" => true, "voted" => false));
}
}
?>
JavaScript Error solved!
Everything Solved!
As I'm very new to Ajax so I'm not able to find any solution to this.
If that's STRICTLY your code, (I mean, if you've just literally copy/pasted it from your real .php file), there's a typo error in the second script block of the first .php document.
javasript -> javasCript
Give it a try.
You're not echoing the json, you're echoing random text ('Vote up'), which will break the ajax json parser.
Remove the echo 'Voted!';
and try echo json_encode(array("status" => true, "voted" => false));
.
Also you can skip the SELECT
query and do : UPDATE test SET votes=votes+1 WHERE post_id='$post_id'
精彩评论