I have this HTML:
<a href="#" ><div class="menu"><img src="<?php echo $value->capa; ?>" class="img-rounded" id="item" alt="Cinque Terre" alt="Lights"></a></div>
I have that part to have the ID from img hidden:
<input type="hidden" id="idLivro" name="idLivro" value="<?=$value->id?>">
And this script:
$(document).ready(function(){
$(".menu").click(function(){
var idLivro = document.getElementById("idLivro");
$.ajax({
url: 'updateBadge.php?id='+idLivro,
method: 'GET'
})
});
});
updateBadge.php:
require_once 'classes/Crud.php';
$banco = new Usuarios();
$idLivro = $_GET['idLivro'];
$banco->updateBadge($idLivro);
What I want to do, is when someone click that link(img) where have a badge next to it, it increment by 1 the respective column in DB.
But, the part where I have the update method is inside a class:
public function updateBadge($id){
$sql = "UPDATE $this->table SET badge = (badge+1) WHERE id = :id";
$stmt = DB::prepare($sql);
$stmt->bindParam(':id', $id);
return $stmt->execute();
}
How can I use AJAX to call this function to update the badge counter?
EDITED: I've change the code using the comments below. Still not working
You need a script (e.g. Users.php
as you call it in the AJAX request. In this Users.php
you have to instantiate your class and call the updateBadge
-method with the repective parameters, that have also to be sent in your AJAX request.
And if you just like to increment the badge column write following query (then only one bind param is fine):
$sql = "UPDATE $this->table SET badge = (badge+1) WHERE id = :id";
To get the ID to the AJAX request you need the ID somewhere in the HTML, get it via jQuery and pass it to your URL like
$.ajax({
url: 'classes/Users.php?id='+theJsVariableYouStoredTheIdIn,
method: 'GET'
})
Then you can access it in you Users.php
via $_GET['id']
page updateBadge.php
<?php
require_once 'classes/Crud.php';
//function isAjax() To test whether the query is in Ajax
public function isAjax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']== 'XMLHttpRequest';
}
if(isAjax()){
$banco = new Usuarios();
$idLivro = $_GET['idLivro'];
if($banco->updateBadge($idLivro)){
echo "updated";
}
}
And your script:
$(document).ready(function(){
$(".menu").click(function(){
var idLivro = document.getElementById("idLivro");
var badge= $('#vidLivro').val();
$.ajax({
url: 'updateBadge.php?id='+idLivro,
method: 'GET'
})
.done(function(data,text,jqxhr){
if(jqxhr.responssetext=='updated'){
$('#vidLivro').val(badge+1);
}
})
});
});