Reputation: 960
I have an ajax function that should post some data to another page but it doesnt seem to be posting for some reason.
I have no idea why this is not working i have been looking at it for the past hour.
The Ajax function
$(document).ready(function()
{
$('.rate').click(function(){
var ratingId = $('#ratingID').val();
var clickBtnValue = $(this).val();
var ajaxurl = 'ProcessRating.php',
data = {'action': clickBtnValue, 'ratingID': ratingId};
$.post(ajaxurl, data, function (response)
{
alert("action performed successfully");
});
});
});
On the main page
<?php
session_start();
echo $_SESSION["messege"];
?>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js">
</script>
<script>
//The Ajax function is here
</script>
</head>
<body>
<form>
<input type="hidden" class="rate" id="ratingID" name="ratingID" value =
"<?php echo $article->getId()?>" />
<input type="submit" class="rate" name="1" value="1" />
<input type="submit" class="rate" name="2" value="2" />
<input type="submit" class="rate" name="3" value="3" />
<input type="submit" class="rate" name="4" value="4" />
<input type="submit" class="rate" name="5" value="5" />
</form>
</body>
On the page ProcessRating.php
<?php
session_start();
$_SESSION["messege"] = "got This far";
if (isset($_POST['action']))
{
$id = $_POST['ratingID'];
switch ($_POST['action']) {
case '1':
updateRating($db, $id, "oneStar");
break;
case '2':
updateRating($db, $id, "twoStar");
break;
case '3':
updateRating($db, $id, "threeStar");
break;
case '4':
updateRating($db, $id, "fourStar");
break;
case '5':
updateRating($db, $id, "fiveStar");
break;
}
$rating = getAvgRating($db, $id);
updateArticleRating($db, $id, $rating);
}
Upvotes: 0
Views: 64
Reputation: 230
As suggested in the comment, please check what is being returned to your script via the console. you can use console.log(response)
in such way
jQuery.ajax({
type: "POST",
url: "http://url",
data: "action=foobar",
success: function(response){
console.log(response);
}
});
Now, you can check your console for the return response.
Upvotes: 0
Reputation: 72299
1.Since all button type is submit
and they are inside the <form></form>
.So you have to use preventDefault()
to prevent normal form posting.
Do like below:-
$(document).ready(function(){
$('.rate').click(function(e){
e.preventDefault();
var ratingId = $('#ratingID').val();
var clickBtnValue = $(this).val();
var ajaxurl = 'ProcessRating.php',
data = {'action': clickBtnValue, 'ratingID': ratingId};
$.post(ajaxurl, data, function (response){
alert("action performed successfully");
});
});
});
2.Make sure that ajaxurl
is correct there.(check console for this,if there is error in URL you will see that in console forsure)
Important Note:-
Check your browser console to see any error is there? If yes tell us.
Upvotes: 2