I need to update a table with new values in MySQL when an image is clicked.
$("#image1").click(function(){
Here's an example of the query:
mysqli_query($conn,"UPDATE photos SET rating='$ratingnew1' WHERE link='$img1link'");
How do I execute that query only when the image is clicked?
$("#image1").click(function(){
$.ajax({url: "update.php",
data: {img1link : 'image link', ratingnew1: 'rating'});
});
and then the update.php file
<?php
mysqli_query($conn,"UPDATE photos SET rating='$ratingnew1' WHERE link='$img1link'")
?>
As a matter of fact your code must contain 2 parts: client side (JQuery) and server side (PHP). The JQuery code can be can be
$(document).ready({
$("#image1").click(function(){
$.ajax({
url: "update.php",
type: "POST",
data: {
img1link : 'image link',
ratingnew1: 'new rating'
},
succsess: function(data){
//some action
}
});
});
});
here in data
block you have to declare the variable which will be sent by POST
action (as the type
of the request is POST
). For more possible settings and potions please see the JQuery.ajax() documentation.
For server side (in this particular example update.php) you can use the following code:
<?php
$data['img1link'] = '';
$data['ratingnew1'] = '';
foreach($data as $key=>$value){
if(array_key_exists($key, $_POST))
$data[$key] = $_POST[$key];
}
if($data['img1link'] != '')
mysqli_query($conn,"UPDATE photos SET rating='".mysqli_real_escape_string($data['ratingnew1'])."' WHERE link='".mysqli_real_escape_string($data['ratingnew1'])."'");
$("#image1").click(function(){
$.post("update.php",{img1link : this.src});//here You send POST request to the server with post data img1link = src tag value of image
});
update.php
//and here You receive data $_POST['img1link']
if(!empty($_POST)) {
mysqli_query($conn,"UPDATE photos SET rating=rating+1 WHERE link='".$_POST['img1link']."'")
}