I'm quite new to jQuery. I am building a shopping cart and trying to delete products from a cart. If I have one item in the basket and then remove it, it will disappear, but if I add another item to the cart, the item I deleted will reappear. If I have a card with more than one object, when I attempt to delete it, it will only change the total.
$('.addToCart').click(function(){
var id = this.id;
var price = parseFloat($('#priceAdd-'+id).val()).toFixed(2);;
var name = $('#name-'+id).val();
var total =(parseFloat($('#total').text())+parseFloat(price)).toFixed(2);
cartSize++;
$('#product-'+id).fadeOut('fast');
$('#added-'+id).delay(500).fadeIn('fast');
$.ajax({
type: "POST",
url: 'resources/addToCart.php',
data: { itemId: id , name: name, price: price},
cache: false,
success: function(html){
$("ol").append(html).slideDown("slow");
$('#noItems').fadeOut('fast');
$('#total').html(total);
$('#mainCart').fadeIn('fast');
}
});
});
$('ol').on("click",'.del',function(e){
var id= e.target.id;
var productId = $('#productId-'+id).text();
var productPrice = $('#price-'+id).text();
var total = $('#total').text();
var newPrice = (parseFloat(total) - parseFloat(productPrice)).toFixed(2);
var dataString = 'id='+ id;
cartSize--;
alert(id);
$('#total').html(newPrice);
$("#cart-"+id).remove();
$.ajax({
type: "POST",
url: "resources/del.php",
data: { id: id },
cache: false,
success: function(html){
$('#added-'+productId).fadeOut('Fast');
$('#product-'+productId).delay(600).fadeIn('Fast');
if(cartSize == 0){
$('#noItems').fadeIn('Fast');
$('#mainCart').fadeOut('Fast');
}
}
});
return false;
});
Any input would be appreciated
Thank you
edit: is there anyone else who can help me?
I think when you are calling to "resources/del.php", this is not deleting the item in Server (only visually) and then when you add another with "resources/addToCart.php", this is returning ALL the items (even the one you think you remove)
Related
I have stored two JSON arrays in local storage i.e,
viewbody=>json data1 , viewcollar=>json data2. I am fetching these arrays in foreach loop from local storage with data name attribute dynamically. But am not able to pass two arrays data to php ajax. Kindly help me, someone.
Below is my code,
$(document).on('click','.startDesignbtn', function() {
var product_id = $(this).data("id");
$(".getoption").each(function(){
var option_name = $(".getoption").data("name");
// alert(option_name);
var views = localStorage.getItem("view"+option_name);
});
$.ajax({
url: 'index.php?route=product/design/designMultiImage',
type: 'post',
//dataType: 'text',
data:{
'product_id': product_id,
'views' : views,
},
success: function(data) {
alert(data);return false;
var intValArray = data.split(',');
var count = 0;
$.each(intValArray,function(i){
localStorage.setItem("view_"+count,intValArray[i]);
count++;
});
localStorage.setItem('design-image',data);
localStorage.setItem('parent-id',product_id);
// var custom_link = data;
window.location = "<?php echo $customize_link;?>";
}
});
});
Use array.push() to append values to an array. Also, you need to define the array outside of the each loop otherwise you reset it every time. Also, inside the loop, use $(this) as opposed to targeting the element by class. Fixed your click function below:
$(document).on('click','.startDesignbtn', function() {
var product_id = $(this).data("id");
var views = [];
$(".getoption").each(function(){
var option_name = $(this).data("name");
// alert(option_name);
views.push("view"+option_name);
});
$.ajax({
url: 'index.php?route=product/design/designMultiImage',
type: 'post',
//dataType: 'text',
data:{
'product_id': product_id,
'views' : views,
},
success: ...
i use this script
<script type="text/javascript">
$(function () {
$(".comment_button").click(function () {
var element = $(this);
var boxval = $("#content").val();
var dataString = 'content=' + boxval;
if (boxval == '') {
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "update_data.php",
data: dataString,
cache: false,
success: function (html) {
$("ol#update").prepend(html);
$("ol#update li:first").slideDown("slow");
document.getElementById('content').value = '';
$("#flash").hide();
}
});
}
return false;
});
$('.delete_update').live("click", function () {
var ID = $(this).attr("id");
var dataString = 'msg_id=' + ID;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete_data.php",
data: dataString,
cache: false,
success: function (html) {
$(".bar" + ID).slideUp('slow', function () {
$(this).remove();
});
}
});
}
return false;
});
});
</script>
this script combine live update and delete record using jquery and ajax
the problem is when I refresh the page, the record will disappear .. how to keep records that show up are not dissapear when the page is reloaded?
First Check the comment list. Did you put any limit in query, if so then use Order by Primary ID desc.So it would display latest records first.
When you delete any record, check whether it is actually deleted from database or not. Because you are not checking whether record actually deleted or not as per the code you given.
Assuming you are using update_data.php and delete_data.php to manipulate some database, you could use PHP to render the page initially using the data that is currently on the database.
If that is not the case, and you don't have access to that database (it could be a third party web service, right?), or you don't want to do that for any reason, you could use cookie like Saeed answered.
I'm trying to send $_POST data to another page to add sessions for a simple shopping cart.
I have a multiple forms within a PHP while loop each with multiple checkboxes, everything works apart from the checkboxes.
My question is how do I change this piece of code to change "item_extras" into an array?
if(this.checked) item_extras = $(this).val();
I have tried the following but, this just creates one line with all the values instead of another row within the array. If this is too confusing I could create a sample if it helps.
if(this.checked) item_extras += $(this).val();
$('form[id^="add_item_form"]').on('submit', function(){
//alert("On Click Works");
event.preventDefault();
addItem($(this));
});
function addItem(ele) {
//alert("I'm in the addItem Function");
var item_id = ele.parent().parent().find("input[name=item_id]").val(); // get item id
var item_name = ele.parent().parent().find("input[name=item_name]").val(); // get item name
var item_options = ele.parent().parent().find('#options').val(); // get selected option
var item_extras = "";
$item_extras = ele.parent().parent().find('input[name^="extra"]'); // find all extras
$item_extras.each(function() {
if(this.checked) item_extras = $(this).val(); // how do i make this into an array???
});
alert("BEFORE AJAX");
var dataString = 'item_id=' + item_id + '&item_name=' + item_name + '&item_options=' + item_options + '&item_extras[]=' + item_extras;
alert(dataString);
$.ajax({
type: "POST",
cache: false,
url: "includes/cart.php",
data: dataString,
success: function () {
$.ajax({
url: 'includes/cart.php',
success: function(data) {
$('#cart').html(data);
alert("AJAX SUCCESS");
}
});
}
});
return false;
}
you can use serialize method. Form.serialize()
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
var data = $(this).serialize();
});
My page consists of a list of records retrieved from a database and when you click on certain span elements it updates the database but at present this only works for the first record to be displayed.
(Basically changes a 0 to 1 and vice versa)
These are my two html elements on the page that are echoed out inside a loop:
Featured:<span class="featured-value">'.$featured.'</span>
Visible:<span class="visible-value">'.$visible.'</span>
Here is what I have:
$(document).ready(function() {
$('.featured-value').click(function() {
var id = $('.id-value').text();
var featured = $('.featured-value').text();
$('.featured-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$('.featured-value').html(data);
$('.featured-value').fadeIn('slow');
}
});
return false;
});
// same function for a different span
$('.visible-value').click(function() {
var id = $('.id-value').text();
var visible = $('.visible-value').text();
$('.visible-value').fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&visible="+visible,
success: function(data) {
$('.visible-value').html(data);
$('.visible-value').fadeIn('slow');
}
});
return false;
});
});
It was working fine with one using id attributes but now I'm using class the fadeIn part of the success query isn't working but I'm hoping the .each will fix this.
UPDATE
The full loop is as follows:
while ($event = $db->get_row($events, $type = 'MYSQL_ASSOC'))
{
// open event class
echo '<div class="event">';
echo '<div class="id"><span class="row">Event ID:</span><span class="id-value"> '.$id.'</span></div>';
echo '<div class="featured"><span class="row">Featured: </span><span class="featured-value">'.$featured.'</span></div>';
echo '<div class="visible"><span class="row">Visible: </span><span class="visible-value">'.$visible.'</span></div>';
echo '</div>';
}
Cymen is right about the id selector causing you trouble. Also, I decided to refactor that for you. Might need some tweaks, but doesn't everything?
function postAndFade($node, post_key) {
var id = $node.parents('.id').find('.id-value').text();
var post_val = $node.text();
$node.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&"+post_key+"="+post_val,
success: function(data) {
$node.html(data);
$node.fadeIn('slow');
}
});
return false;
}
$('.featured-value').click(function() { return postAndFade($(this), 'featured'); });
$('.visible-value').click(function() { return postAndFade($(this), 'visible'); });
The click function is getting the same id and value on each click because you've bound it to the class. Instead, you can take advantage of event.target assuming these values are on the item being clicked. If not, you need to use event.target and navigate to the items within the row.
$('.featured-value').click(function(event) {
var $target = $(event.target);
var id = $target.attr('id');
var featured = $target.text();
$target.fadeOut('slow');
$.ajax({
type: "POST",
url: "process.php",
data: "id="+id+"&featured="+featured,
success: function(data) {
$target.html(data).fadeIn('slow');
}
});
return false;
});
So something like that but it likely won't work as it needs to be customized to your HTML.
I now am working with my project. I have the problem with the data. I have knowledge on jquery
$(document).ready(function(){
$("input[type='radio']").click(function(){
var price = $(this).val();
add_payment_value(price);
});
});
function add_payment_value(price){
// here you can use $.ajax function to add your 'price value' to your cart
$.ajax({
type: "POST",
url: "add_payment.php",
// file where you can add price to your database
data: "",
success: function(){} // return something on success
});
}
I have 4 values which is stored in radio buttons ordered 4, 6.5, 8, 11. My question is how to write the values in data and var price = $(this).val();? Can anyone fill this? I gave some value but that is not working.
Change the add_payment_value function to accept a name and then uaw the code below:
$(document).ready(function(){
$("input[type='radio']").click(function(){
var price = $(this).attr("value");
var name = $(this).attr("name");
add_payment_value(price, name);
});
});
function add_payment_value(price, name){
// here you can use $.ajax function to add your 'price value' to your cart
$.ajax({
type: "POST",
url: "add_payment.php", // file where you can add price to your database
data: name + "=" + price,
success: function(){} // return something on success
});
}
Another alternative is to format the data string in the click handler and send it to add_payment_value function
$(document).ready(function(){
$("input[type='radio']").click(function(){
var price = $(this).attr("value");
var name = $(this).attr("name");
add_payment_value(name + "=" + price);
});
});
function add_payment_value(priceData){
// here you can use $.ajax function to add your 'price value' to your cart
$.ajax({
type: "POST",
url: "add_payment.php", // file where you can add price to your database
data: priceData,
success: function(){} // return something on success
});
}
use radio button id like ("#rb1").value instead of this.