AJAX with Multiple Submit - php

I currently have a 'Add to Cart' button which submits product data from an array and posts the data using AJAX.
Currently on submit only one of the three products are been send to the cart.
I was told to use .then function after each AJAX post but I'm unsure how to tie this in with the for() function and the array.
Any and all help would be very much appreciated! Thank you.
function addtocart() {
var products = [{
'id': 32,
'qty': 2
}, {
'id': 33,
'qty': 1
}, {
'id': 34,
'qty': 5
}];
$('.submit').on('click', function(e) {
e.preventDefault();
for (var j = 0; j < products.length; j++) {
jQuery.ajax({
type: 'POST',
url: 'XXX/?post_type=product&add-to-cart=' + products[j].id + '&quantity=' + products[j].qty
});
}
});
}
<div class="addtocart">
<button class="submit">Add to Cart</button>
</div>
Update:
function addtocart() {
var products = [{'product_id':32,'quantity':2},{'product_id':33,'quantity':1},{'product_id':34,'quantity':5}];
$('.submit').on('click', function(e){
e.preventDefault();
$.ajax(
{
type:'POST',
url:'XXX/?post_type=product&add-to-cart',
data:JSON.stringify(products)
}
);
console.log(JSON.stringify(products));
});
}
addtocart();
Network Snapshot
Console Log Snapshot
I was told to do something like this, but I can't add an ID without it been within a for()
url: 'XXX/?post_type=product&add-to-cart='+IDHERE

Related

Fullcalendar modal button click runs more times

I have a problem with button click in modal (using FullCalendar).
My plan is:
Click on event
Modal appears with 3 options
Confirm changes a value in mysql database / Refuse changes a value in mysql database
When I try one time is works very well. But when I close the modal and open an other i click on the refuse/confirm button then it runs more times (2, 4 ...).
What is the problem??
modal:
<div id="eventContent" title="Event Details" style="display:none;">
Name: <span id="name"></span><br>
Start: <span id="startTime"></span><br>
End: <span id="endTime"></span><br><br>
<p id="eventInfo"></p>
<button id="confirm_button" type="button">Confirm</button>
<button id="refuse_button" type="button">Refuse</button>
<button type="close_button">Close</button>
</div>
eventRender:
<script>
$(document).ready(function () {
$('#calendar').fullCalendar({
header: {
left: '',
center: 'prev title next',
right: ''
},
events: "http://localhost/calendar_directory/calendar_db_connect.php",
eventRender: function (event, element) {
element.click(function () {
var start = $.fullCalendar.formatDate(event.start, "YYYY-MM-DD");
var end = $.fullCalendar.formatDate(event.end, "YYYY-MM-DD");
$("#name").html(event.title);
$("#startTime").html(start);
$("#endTime").html(end);
$("#eventContent").dialog({modal: true, title: event.title, width: 350});
$("#refuse_button").click(function ()
{
var id = event._id;
var confirmed_number = 2;
var decision = confirm("Do you really want to refuse that?");
if (decision)
{
$.ajax({
url: "http://localhost/calendar_directory/confirm_events.php",
data: '&id=' + id + '&confirmed_number=' + confirmed_number,
type: "POST",
success: function (json)
{
console.log(id);
return;
}
});
}
});
$("#confirm_button").click(function ()
{
var id = event._id;
var confirmed_number = 1;
var decision = confirm("Do you really want to confirm that?");
if (decision)
{
$.ajax({
url: "http://localhost/calendar_directory/confirm_events.php",
data: '&id=' + id + '&confirmed_number=' + confirmed_number,
type: "POST",
success: function (json) {
console.log("confirmed");
return;
}
});
}
})
});
},
});
});
</script>
Database structure here:
confirmed column can be: 0,1 or 2
Assigned the same handler to the click event.
The solution is:
$("#refuse_button").unbind("click").click(function(){
/*Your code goes here*/
}
$("#confirm_button").unbind("click").click(function(){
/*Your code goes here*/
}

Ajax post data of Multiple selected Checkboxes - Laravel

I am using laravel and have list of data in a table which has checkboxes to each.
I am looking for multiple delete operation on controller side. I tried for single delete and it worked like charm. But when I used post method for these datas it throws me 500 internal server error.
<script type="text/javascript">
$(function() {
$("#btndel").click(function(){
var a = [];
var cboxes = $('input[name="suppcheck[]"]:checked');
var len = cboxes.length;
for (var i=0; i<len; i++) {
a[i] = cboxes[i].value;
}
console.log(a);
var element = $(this);
if(confirm("Are you sure you want to group delete this?"))
{
$.ajax({
type: "POST",
url: "groupDeleteSupp",
data: "ids":[{info:a}],
alert(data);
success: function(){}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
here is the ajax script. The ids are fecthed perfectly in array a[].
here is my logic at controller,
$data = Input::all();
//p($data);
if(Request::ajax())
{
$ids = $request->input('info');
if(isset($ids))
{
DB::table('supplier')->whereIn('RefAddress', $ids)->delete();
DB::table('address')->whereIn('ID', $ids)->delete();
Session::put('groupDelete');
return redirect('/Suppliers');
}
else
{
Session::put('groupFail');
return redirect('/Suppliers');
}
}
What should be done to pass those values. Its not form either hence I assumed I dont have to deal with csrf token.
Awaiting your reply.

show woocommerce messages in overlay div or tooltip without page refresh

I am trying to get rid of the redirect/reload when the user is adding a product or gets a info message in my woocommerce shop. I just want to show the "added to cart" message in a tooltip or overlay div and let them continue shopping without renavigate to the shop.
AJAX add to cart is enabled
so my question is:
what can I do to display this messages without refreshing the whole page?
EDIT: maybe useful for anyone, heres my FINAL CODE:
$('.add_to_cart_button, .single_add_to_cart_button').click(function(e) {
var produkt_id;
if ($(this).attr('data-product_id') == undefined) {
produkt_id = $('input[type=hidden]').val();
} else {
produkt_id = $(this).attr('data-product_id');
}
var amount;
if ($(this).hasClass('single_add_to_cart_button') == true) {
if ($('.qty').val() !== '1') {
amount = $('.qty').val();
}
console.log(amount + ' single_add_to_cart_button');
}
else {
amount = '1';
console.log(amount + ' add_to_cart_button');
}
function addToCart(produkt_id) {
$.ajax({
type: 'POST',
url: '?add-to-cart=' + produkt_id,
data: {'product_id': produkt_id,
'quantity': amount},
success: function(response, textStatus, jqXHR) {
// callback
}/*,
dataType: 'JSON'*/
});
}
e.preventDefault();
addToCart(produkt_id);
});
Do you mean something like this:
if you do the function "addedToChart" it will do a ajax and creat a message at top of the page
$(document).on('click','.add_to_cart_button',function(e) {
e.preventDefault();
addedToCart($(this).data('product_id'));
});
function addedToCart(id){
$.ajax({
type: "POST",
url: "some.php",
data: { product_id: id},
success: function(){
$('body').prepend('<div style="position:fixed; height:20px; width:100%; background-color:red; text-align:center;">Added to chart</div>');
}
});
}

AJAX POST not loading class on button click.

If rating = +0 the following will show (standby).
If I click on the button, then the following will show( adding rating ).
If I click again, then the following will show ( removing rating )
I'd like for it to show as follows:
if rating = +0, when I click it the following will show.
Issue: When I click the button the font-weight:bold & color: # goes away when It should automatically update with the class. What am I doing wrong? Sorry for this lame question, just been at it for a while and I'm stuck with such a simple problem I'm sure.
This is my code:
PHP :
<div class="up vote" name="voteUp" id="<?php echo $post_iD;?>">
<div class="wrapper">+<?php echo $VoteRate;?></div>
</div>
AJAX:
$(function()
{
$(".vote").click(function()
{
var id = $(this).attr("id");
var name = $(this).attr("name");
var dataString = 'id='+ id ;
var parent = $(this);
if (name=='voteUp')
{
$.ajax(
{
type: "POST",
url: "voting/up_vote.php",
data: dataString,
cache: false,
success: function(html)
{
parent.html(html);
}
});
}
return false;
});
});
In your success function, replace the HTML of the .wrapper div, not the parent:
parent.find(".wrapper").html(html);

Calling ajax once

I have created a button on my website when it is clicked, I sent data on some php file using ajax and return the results. The code I am using is below,
My Goal :
When that button is clicked for the first time. I want to send the data on some php file using ajax and return the results, and
When it is clicked for the second time, I just want to hide the content, and
When it is clicked for the third time, I just want to show the container without calling the ajax again.
jQuery:
$(function() {
$('#click_me').click(function(){
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php",
}).done(function(data) {
$('#container').html(data);
}).success(function(){
$('#container').show('fast');
});
}else if(container == 'block'){
$('#container').hide('fast');
}
});
});
Html :
<input type="button" id="click_me" value="Click Me"/>
<div id="container"></div>
The jQuery way would be like this:
$(function() {
$('#click_me').one('click', function() {
$.ajax({
// ... other params ...,
success: function(result) {
$('#container').html(result).show('fast');
$('#click_me').click(function() {
$('#container').toggle('fast');
});
});
});
});
});
http://api.jquery.com/one/
http://api.jquery.com/toggle/
You can use the counter
http://forum.jquery.com/topic/making-a-number-counter
(function () {
var count = 0;
$('table').click(function () {
count += 1;
if (count == 2) {
// come code
}
});
})();
JQuery Mouse Click counter
Working Example of your code :-
http://jsfiddle.net/2aQ2g/68/
Something like this should do the trick...
$("#click_me").click(function(){
var $btn = $(this);
var count = ($btn.data("click_count") || 0) + 1;
$btn.data("click_count", count);
if ( count == 1 ) {
$.ajax({
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php"
})
}
else if ( count == 2 ) {
$('#container').hide('fast');
}
else {
$('#container').show('fast');
$btn.unbind("click");
}
return false;
});
One way to do it would be to add a class call count using jQuery every time the user clicks on the button (http://api.jquery.com/addClass/) and you can get the count value in the handler and based on that you can handle the click appropriately.
You can do this by defining a simple variable counting the clicks.
$(function() {
var clickCount = 1; //Start with first click
$('#click_me').click(function(){
switch(clickCount) {
case 1: //Code for the first click
// I am just pasting your code, if may have to change this
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php",
}).done(function(data) {
$('#container').html(data);
}).success(function(){
$('#container').show('fast');
});
}else if(container == 'block'){
$('#container').hide('fast');
}
break;
case 2:
//code for second click
break;
case 3:
//Code for the third click
break;
});
clickCount++; //Add to the click.
});

Categories