I am trying to create a button that when clicked will add a record to that database, and when clicked again, will delete this record from that database (it's a 'favourite' button).
I would like it to work as follows;
User clicks 'fav' button > button state changes to success > record added
User clicks 'fav' button again > state changes to default > record removed from db
So far my code is as follows (updated code thanks to #Peter);
books_model.php
class BooksModel
{
public function checkFav($bookid,$userid)
{
$book_id=$_REQUEST['book_id'];
$user_id=$_SESSION['user_id'];
$sql = "SELECT * FROM favourite WHERE user_id=? AND book_id=?";
$query = $this->db->prepare($sql);
$query->bind_param('ii', $userid,$bookid);
$query->execute();
$query->store_result();
$rows_found = $query->num_rows();
if(empty($rows_found)) {
$sql = "INSERT INTO favourite (user_id, book_id)
VALUES (?, ?)";
$query = $this->db->prepare($sql);
$query->bind_param('ii',$userid,$bookid);
$query->execute();
} else {
$sql = "DELETE FROM favourite WHERE user_id=? AND book_id =?";
$query = $this->db->prepare($sql);
$query->bind_param('ii',$userid,$bookid);
$query->execute();
}
}
}
books_controller.php
class Books extends Controller
{
function checkFav()
{
$checkFav_model = $this->loadModel('Books');
}
}
itemView.php
$(document).ready(function(){
$( "#fav" ).click(function(){
$( this ).toggleClass( "btn-success" );
book_id = $(fav).val(); // set the value of the button (book_id)
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>books/checkFav', //location of query
data: {book_id:book_id}, //taken from value of button
success: function () {
$( "div.addtofavs" ).slideToggle( "slow" ); //show div below button
}//end success
});//end ajax
});
});
button html
<button id="fav" value="'.$book->id.'" type="button" class="btn btn-default"></button>
Currently when I click the button and look in the console I can see the post, however nothing is being sent to my db.
Any advice or direction is appreciated as I am quite new to MVC and JS.
public function checkFav($bookid,$userid)
{
$sql = "SELECT * FROM favourite WHERE user_id=:userid AND book_id=:bookid";
$query = $this->db->prepare($sql);
$query->bindParam(':userid', $userid);
$query->bindParam(':bookid', $bookid);
$query->execute();
$rows_found = $query->countRows();
if(empty($rows_found)) {
$sql = "INSERT INTO favourite (user_id, book_id) VALUES (:userid, :bookid)";
$query = $this->db->prepare($sql);
$query->bindParam(':userid', $userid);
$query->bindParam(':bookid', $bookid);
$query->execute();
} else {
$sql = "DELETE FROM favourite WHERE user_id=:userid AND book_id =:bookid";
$query = $this->db->prepare($sql);
$query->bindParam(':userid', $userid);
$query->bindParam(':bookid', $bookid);
$query->execute();
}
}
$book_id=$_REQUEST['book_id'];
$user_id=$_SESSION['user_id'];
checkFav($book_id,$user_id);
You can simply do a check:
SELECT * FROM favourite WHERE user_id = :user_id AND book_id = :book_id
if it returns something, execute the
DELETE FROM favourite WHERE user_id = :user_id AND book_id = :book_id
else do the insert.
If you want to show the book is already added as favourite to the user, then you have to execute another call on page load which gives the button an attribute, which tells you AND the user it's already a favourite or not.
In the last case you don't have to do the check anymore. Just execute the DELETE query if it contains the attribute, else do the INSERT
// try to get the attribute of the button
var attr = $(".favoriteButton").attr('data-favorite');
// check the button has the attribute
if (typeof attr !== typeof undefined && attr !== false) {
//delete query
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>books/deleteFav', //location of query
data: {book_id:book_id}, //taken from value of button
success: function () {
$( "div.addtofavs" ).slideToggle( "slow" ); //show div below button
}//end success
});//end ajax
});
}
Something like that
Use generic vars: var IsDeleted; var IsAdded; then IsDeleted = 0; IsAdded =1; (your book is added). Change the values again when you delete book IsDeleted = 1; IsAdded =0; when you execute $( "#fav" ).click(function() check those values and do what action you want (add, delete).
<button class="fvrt" data-item-id="11" data-current-state="0"> Like <button> // 0 = normal, 1 = liked
$(document).on('click', '.fvrt', function(){
if($(this).attr('data-current-state') == 0){
like_item($(this).attr('data-item-id')); // send ajax request
$(this).attr('data-current-state', '1');
$(this).val('Liked');
}else{
dislike_item($(this).attr('data-item-id')); // send ajax request
$(this).attr('data-current-state', '0');
$(this).val('Like');
} // checking state
}); // on clicked
Related
What's wrong with my code? I can't even place an order or save it on database. I'm using ajax/jquery, it reaches the success but the problem is, it doesn't save in database.
PS: I also included place_order(); under script type.
Button:
<button id="place_order" class="btn btn-black">PLACE ORDER</button>
Jquery:
//Placing Order / Complete the Transaction
function place_order() {
$('#place_order').click(function(e){
var place_order = $('#place_order').val();
$.ajax({
type: 'POST',
url: '../pages/class.php',
data: {place_order:place_order},
success:function(data) {
location.href="../pages/index.php";
}
});
});
}
Class.php
if(isset($_POST['place_order'])) {
if(isset($_SESSION['item_cart'])) {
foreach($_SESSION['item_cart'] as $id=>$val) {
$user_id = $_SESSION['id']; //id of users
$product_stocks = $val['product_stocks']; //product stocks
$product_id = $val['product_id']; //id of product/item
$product_name = $val['product_name']; //name of product
$product_quantity = $val['product_qty']; //quantity of product
$product_price = $val['product_price']; //price of product
$product_size = $val['product_size']; //size of product
//Total Price
$total = $product_quantity * $product_price;
//Check if the stocks is less than quantity
if ($product_stocks < $product_quantity) {
echo "Insufficient Stock";
} else {
//Insert it on database
$insert_query = "INSERT INTO tbltransactions(product_name, product_price, product_qty, total_price, product_id, account_id) VALUES('$product_name', $product_price, $product_quantity, $total, $product_id, $user_id)";
$query = mysqli_query($db_conn, $insert_query);
//If the query is success, update the stocks in database
if($query) {
$update_query = "UPDATE tblproduct_extension SET product_stocks = $product_stocks - $product_quantity WHERE product_id = '$product_id' AND product_size='$product_size'";
$query = mysqli_query($db_conn, $update_query);
//unset the SESSION
unset($_SESSION['item_cart']);
}
}
}
}
}
There is no value assigned to the variable place_order
data: {place_order:place_order},
Assign value to variable using
var place_order = $("#place_order").val(); //change field name
I want to create a shopping cart and i'm almost finish. I use ajax for dynamic search and ajax for add to cart and use jquery for refresh a specific div when click but i face a problem.My problem is Quantity problem. I use session for store value
//this is my session update code
$con = mysqli_connect("localhost", "root" , "","atest");
session_start();
require("functions.php");
cart_session();
$id=$_POST['id'];
//echo $arr['cart'];
if(isset($_SESSION[$arr["cart"]][$id])){
$_SESSION[$arr["cart"]][$id][$arr["quantity"]]++;
//redirect("http://localhost/my/work/sellingcart/index.php",true);
}else{
$sql_s="SELECT * FROM product_1
WHERE p_id={$id}";
//echo $sql_s;
$query_s=mysqli_query($con,$sql_s);
if(mysqli_num_rows($query_s)!=0){
$row_s=mysqli_fetch_array($query_s);
$_SESSION[$arr['cart']][$row_s["p_id"]]=array(
"{$arr["quantity"]}" => 1
);
//redirect("http://localhost/my/work/sellingcart/index.php",true);
}else{
$message="This product id it's invalid!";
}
}
//use ajax for update cart
<script>
$("#link").click(function(e) {
e.preventDefault();
var id = $("#id").val();
var dataString = 'id='+id;
$('#loading-image').show();
$(".form :input").attr("disabled", true);
$('#remove_cart').hide();
$('#link').hide();
$(".container").css({"opacity":".3"});
$(".form :input").attr("disabled", true);
$('#remove_cart').hide();
$('#link').hide();
$.ajax({
type:'POST',
data:dataString,
url:'add_cart.php',
success:function(data) {
$('#availability').html(data);
},
complete: function(){
$('#loading-image').hide();
$(".form :input").attr("disabled", false);
$('#remove_cart').show();
$('#link').show();
$(".container").css({"opacity":"1"});
}
});
//$("#chat").load(location.href + " #chat");
//$("#chat").load(location.href+" #chat>*","");
});
</script>
Here is image and Red mark is my problem.
i want to update my cart when i give value and move it then it update my session by ajax and php.
Is there any help? I don't want to user can update there quantity every cart item singly. i want it dynamic just give quantity number and move then it save by ajax.
Assign an onchange event to your quantity input boxes:
$('input[name=quantityBox]').change(function() { ... });
In your function() above, add an AJAX POST request containing something like
var quantity = $('input[name=quantityBox]').val();
// var id = something;
$.ajax({
type:'POST',
data:"productId=" + id + "&updateQuantity=" + quantity,
url:'add_cart.php',
success:function(data) {
$('#availability').html(data);
},
complete: function(){
// anything you want to do on successful update of request
}
});
In your PHP function above, you check whether the product already exists in user's cart. At that point, change the quantity.
if(isset($_SESSION[$arr["cart"]][$id])){
$quantity = $_POST['updateQuantity'];
$id = $_POST['productId'];
$_SESSION[$arr["cart"]][$id][$arr["quantity"]] = $quantity;
}
Special Thanks To Nvj
Assign an onchange event to your quantity input boxes:
<input id="qty<?php echo $row['p_id'] ?>" value="" onchange="save_quantity(<?php echo $row['p_id'] ?>)">
function with ajax :
function save_quantity(x){
var quantity=$("#qty"+x).val();
$.ajax({
type:'POST',
data:"updateQuantity=" + quantity+ "&id="+x,
url:'update_qty.php',
success:function(data) {
$('#availability').html(data);
},
complete: function(){
// anything you want to do on successful update of request
}
});
}
php file update_qty.php
session_start();
$qty = $_POST["updateQuantity"];
$p_id = $_POST["id"];
foreach($_SESSION['cart'] as $id => $value) {
if($id==$p_id)
echo $id;
$_SESSION['cart'][$id]['quantity']=$qty;
}
I am trying to insert values from an input field into a database with ajax as part of a conversation system.I am using an input form as follows.
<input data-statusid="' .$statuscommentid. '" id="reply_'.$statusreplyid.'" class="inputReply" placeholder="Write a comment..."/>
with the following jquery I carry out a function when the enter key is pressed by the user.
$(document).ready(function(){
$('.inputReply').keyup(function (e) {
if (e.keyCode === 13) {
replyToStatus($(this).attr('data-statusid'), '1',$(this).attr("id"));
}
});
});
within this function is where I am having the problem ,I have no problems calling the function with jquery but I have done something wrong with the ajax and I don't know what?
$.ajax({ type: "POST", url: $(location).attr('href');, data: dataString, cache: false, success: function(){ $('#'+ta).val(""); } });
Additionally this is the php I am using to insert into the database
<?php //status reply input/insert
//action=status_reply&osid="+osid+"&user="+user+"&data="+data
if (isset($_POST['action']) && $_POST['action'] == "status_reply"){
// Make sure data is not empty
if(strlen(trim($_POST['data'])) < 1){
mysqli_close($db_conx);
echo "data_empty";
exit();
}
// Clean the posted variables
$osid = preg_replace('#[^0-9]#', '', $_POST['sid']);
$account_name = preg_replace('#[^a-z0-9]#i', '', $_POST['user']);
$data = htmlentities($_POST['data']);
$data = mysqli_real_escape_string($db_conx, $data);
// Make sure account name exists (the profile being posted on)
$sql = "SELECT COUNT(userid) FROM user WHERE userid='$userid' LIMIT 1";
$query = mysqli_query($db_conx, $sql);
$row = mysqli_fetch_row($query);
if($row[0] < 1){
mysqli_close($db_conx);
echo "$account_no_exist";
exit();
}
// Insert the status reply post into the database now
$sql = "INSERT INTO conversation(osid, userid, postuserid, type, pagetext, postdate)
VALUES('$osid','$userid','$postuserid','b','$pagetext',now())";
$query = mysqli_query($db_conx, $sql);
$id = mysqli_insert_id($db_conx);
// Insert notifications for everybody in the conversation except this author
$sql = "SELECT authorid FROM conversation WHERE osid='$osid' AND postuserid!='$log_username' GROUP BY postuserid";///change log_username
$query = mysqli_query($db_conx, $sql);
while ($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$participant = $row["postuserid"];
$app = "Status Reply";
$note = $log_username.' commented here:<br />Click here to view the conversation';
mysqli_query($db_conx, "INSERT INTO notifications(username, initiator, app, note, date_time)
VALUES('$participant','$log_username','$app','$note',now())");
}
mysqli_close($db_conx);
echo "reply_ok|$id";
exit();
}
?>
Thanks in advance for any help it will be much appreciated
Why didn't you set the proper URL for Ajax calls instead of using location.href?
var ajax = ajaxObj("POST", location.href);
In additional, I guess ajaxObj is not defined or well coded. You are using, jQuery, why don't you try jQuery ajax?
http://api.jquery.com/jquery.ajax/
var ajax = ajaxObj("POST", location.href);
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
var datArray = ajax.responseText.split("|");
if(datArray[0] == "reply_ok"){
var rid = datArray[1];
data = data.replace(/</g,"<").replace(/>/g,">").replace(/\n/g,"<br />").replace(/\r/g,"<br />");
_("status_"+sid).innerHTML += '<div id="reply_'+rid+'" class="reply_boxes"><div><b>Reply by you just now:</b><span id="srdb_'+rid+'">remove</span><br />'+data+'</div></div>';
_("replyBtn_"+sid).disabled = false;
_(ta).value = "";
alert("reply ok!");
} else {
alert(ajax.responseText);
}
ajax.send("action=status_reply_ok&sid="+sid+"&user="+user+"&data="+data);
}
}
Using google maps, I have events saving to a database using mysqli. These events are then displayed as markers on the map and when clicked the relevant data is displayed in an info box (Name, date, etc). I want the option to delete an event event by deleting a row from the DB when the Remove (remove-event) button is clicked. The button is contained in the data displayed with the javascript:
var eventContent = $('<div class="event-info">' + '<h4 class="event-name">' + point.name + '</h4><hr>' +
'<span><h5>Date: </h5>' +
'<p class="event-date">' + point.edate + '</p></span>' +
'<p class="event-description">'+point.description+'</p>' +
'</span><button id="remove-event" name="remove-event" class="remove-event btn btn-danger btn-sm" onclick="tidy_maps.delete()" title="Remove Event">Remove Event</button>'+
'</div>');
// Display Event details on marker click
google.maps.event.addListener(event_markers[i], "click", function () {
infowindow.setContent(eventContent[0]);
infowindow.open(map, event_markers[i]);
The script that sends it to the php (removedata.php):
tidy_maps.delete = function() {
$.ajax({
type:'POST',
url:'removedata.php',
success:function(data) {
if(data) {
alert("Are you sure?");
}
else {
alert("ERROR!!!!");
}
}
});
}
The removedata.php is:
$con = mysqli_connect("localhost", "root", "password", "gmaps1");
if (!$con) {
die("Can not connect: " .mysql_error());
}
$sql = "DELETE FROM events WHERE id = 'id' ";
$query = mysqli_query($con, $sql);
if(mysqli_affected_rows($con)) {
echo "Record deleted successfully";
}
mysqli_close($con);
As it is, it does not delete the row in the DB, but when i change the line:
$sql = "DELETE FROM events WHERE id = 'id' ";
to a specific ID No. Example:
$sql = "DELETE FROM events WHERE id = '5' ";
And i run the removedata.php in the browser, it deletes the row with ID=5 from the DB. There seems to be no errors when the console when clicking the remove button so it must be sending to PHP script ok.
I would like when the Remove button is clicked that it asks are you sure and then it deletes that specific Row form the DB.
As far as I can tell you don't pass the ID of the row to be deleted.
You can send data two ways, either as a url parameter, or post it using the
data tag:
$.ajax({
type:'POST',
url:'removedata.php',
data: {id : 5}
});
Access the ID in removedata.php:
$id = intval($_POST["id"]);
$sql = "DELETE FROM events WHERE id = " . $id;
WHERE id = 'id' you need to remove the '' and add the $ symbol if you want id to be a variable.
Ok I've played around a little and amended the JS slightly:
tidy_maps.delete = function() {
var confirm_remove = confirm("Do You Want to Remove This Event?")
if(confirm_remove) {
$.ajax({
type:'POST',
url:'removedata.php',
});
window.location = "http://www.google.com/";
}
else {
alert("ERROR!!!!");
}
}
So when Confirm is YES, i threw in a redirect to Google just to see what happens. When YES is clicked in the confirm box, it redirects the page to Google but does not delete the row from the DB
Try this
var id = 5;
var request = $.ajax({
url:'removedata.php',
type: "POST",
data: "id="+id,
success: function(data){
console.log(data);
}
});
get post value in removedata.php
//get post value
$id = intval($_POST["id"]);
$sql = "DELETE FROM events WHERE id = " . $id;
This has been an ongoing issue for me. You all have already helped so much. However, I am stuck again. I cannot get my .ajax() to run. For some reason the .click() won't even work without if(field != text) above my .ajax() call, but I digress.
My question is: Why is my ajax() not functioning properly and if this gets fixed will the table is have displayed update after the query is sent to the database without a page refresh?
Here is my script:
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_td").click(function()
{
$(this).children(".text").hide();
$(this).children(".editbox").show();
}).children('.editbox').change(function()
{
var id=$(this).closest('tr').attr('id');
var field=$(this).data('field');
var text=$(this).val();
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
alert("made variables");
if(field != text)
{
alert("in if");
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#first_"+ID).html(first);
$("#last_"+ID).html(last);
}
});
}
else
{
alert('Enter something.');
}
});
// Edit input box click action
$(".editbox").mouseup(function()
{
return false
});
// Outside click action
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
</script>
Here is my table_edit_ajax.php
<?php
//connect to DB
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASS, DB_NAME);
echo 'in table_edit';
$id = mysqli_escape_String($_POST['id']);
$table = "owners";
$field = mysqli_escape_String($_POST['field']);
$text = mysqli_escape_String($_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($query);
//close connection
mysqli_close($con);
?>
The first argument to all mysqli functions is the connection, statement, or result object.
$id = mysqli_escape_String($con, $_POST['id']);
$table = "owners";
$field = $_POST['field'];
$text = mysqli_escape_String($con, $_POST['text']);
$query = "UPDATE ".$table." SET ".$field."='".$text."' WHERE ".$table."_id = '".$id."'";
mysqli_query($con, $query);
$field shouldn't be escaped, since it's not a string value. Therefore, you need to validate it carefully, to prevent SQL injection. Perhaps instead of allowing the client to submit the field name to update, have them submit an integer, which you look up in an array to convert to a field name.
In your AJAX call, you may have a problem due to not encoding your parameters properly. Change the dataString assignment to:
var dataString = { id: id, field: field, text: text };
Then jQuery will encode it for you.
you are sending a data string
var dataString = 'id= '+ id +'&field= '+ field +'&text= '+ text;
and retrieving it through $_POST.
first check what is in $_POST
and use $_GET instead of $_POST
and change post in ajax to get
and what is first and last in success callback??