php - How do I make an onclick ajax request for favorites button work properly -
i have list on site has favorites button associated each item on list. using image button click. php is:
echo "<img src=\"./images/emptystar.png\" alt=\"favorite\" class=\"favoritebutton\" billid=\"" . $count['id'] ."\" userid=\"". $_session['userid'] ."\" />\n";
i have javascript/jquery make onclick of image submit ajax request php file.
$(document).ready(function() { $(".favoritebutton").click(function () { var billid = $(this).attr("billid"); var userid = $(this).attr("userid"); var ajaxrequest; var params = "billid=" + billid + "&userid=" + userid; ajaxrequest.open("post","./ajaxphp/favorites.php",true); ajaxrequest.setrequestheader("content-type", "application/x-www-form-urlencoded"); ajaxrequest.setrequestheader("content-length", params.length); ajaxrequest.setrequestheader("connection", "close"); ajaxrequest.send(params); ajaxrequest.onreadystatechange=function() { if (ajaxrequest.readystate===4 && ajaxrequest.status===200) { if(ajaxrequest.responsetext === "true") { if($(this).attr("src") === "./images/emptystar.png") { $(this).attr("src","./images/fullstar.png"); } else { $(this).attr("src","./images/emptystar.png"); } } } }; }); });
the php file @ ./ajaxphp/favorites.php following:
<?php include("./includes/dbcxnfunction.inc"); $billid = $_post['billid']; $userid = $_post['userid']; $query = "if not exists (select * favoritebills userid = '$userid' , billid = '$billid' ) insert favoritebills (userid,billid) values($userid,$billid) else delete favoritebills userid = '$userid' , billid = '$billid' "; $result = mysqli_query(dbcxn('bill'),$query) or exit("couldn't execute query favorites"); if($result) { $request = "true"; } else { $request = "false"; } echo $request; ?>
in particular concerned sql query , javascript because not of correctness, used validator javascript jquery , valid.
when click image on page, nothing happens though have tested both conditions image change. either javascript written incorrectly, or there never response sent favorites.php file.
the network tab in console.
use jquery's .ajax , pass clicked element storing in var before make ajax call
$(".favoritebutton").click(function () { //store $(this) in var can passed inside success function var this$ = $(this); var billid = this$.attr("billid"); var userid = this$.attr("userid"); $.ajax( { url : "./ajaxphp/favorites.php", type: 'post', data : { billid : billid , userid : userid }, success : function( responsetext ){ if( responsetext == "true"){ if( this$.attr("src") == "./images/emptystar.png"){ this$.attr("src","./images/fullstar.png"); }else{ this$.attr("src","./images/emptystar.png"); } } }, error : function( e ){ alert( ' error : ' + e ); } }); });
Comments
Post a Comment