I'm new to AJAX so I found a tutorial and hacked it up to fit my PHP code. It's a "like" button tutorial and inside of my code it works okay by adding the "like" count total to the database.
The problem is that once I click the "like", the number of likes doesn't update (on the page).
The original tutorial code works fine, so obviously I did something stupid.
Here's my code for index.php
function cwRating(id,type,target){
$.ajax({
type:'POST',
url:'rating.php',
data:'bt_id='+id+'&type='+type,
success:function(msg){
if(msg == 'err'){
alert('Some problem occured, please try again.');
}else{
$('#'+target).html(msg);
}
}
});
}
And this is the spot where it shows the like and like count:
<span class="like" onClick="cwRating(<?php echo $row_bt['bt_id']; ?>,1,'like_count<?php echo $row_bt['bt_id']; ?>')"></span>
<span class="counter" id="like_count<?php echo $row_bt['bt_id']; ?>"><?php echo $row_bt['like_num']; ?></span>
This is the entire rating.php page:
include_once("likes.php");
$likes = new Likes();
if($_POST['bt_id']){
//previous tutorial data
$prev_record = $likes->get_rows($_POST['bt_id']);
//previous total likes
$prev_like = $prev_record['like_num'];
//calculates the numbers of like or dislike
if($_POST['type'] == 1){
$like = ($prev_like + 1);
$return_count = $like;
}else{
$like = $prev_like;
}
//store update data
$data = array('like_num'=>$like,'like_date'=>date("Y-m-d H:i:s"));
//update condition
$condition = array('bt_id'=>$_POST['bt_id']);
//update tutorial like dislike
$update = $likes->update($data,$condition);
//return like or dislike number if update is successful, otherwise return error
echo $update?$return_count:'err';
}
I want to have the response in the .counter class, I'm assuming it's just the AJAX code that needs tweaking.
Probably you have an error in your PHP code, use the Google Chrome to see this.
1. Right click on your page and then select inspect element;
2. Click on the "Network" tab;
3. Find and click on your ajax request in "Name Path" column (rating.php);
4. Go to "Response" tab;
5. See the response of your ajax request.
Solved! I checked the "Network" tab in Chrome and saw a few errors, mainly it was "xmlhttprequest cannot load no 'access-control-allow-origin'". In my AJAX post url I removed the www. from the domain and everything works now.