I've coded up a sort of inventory managing system and I'm adding a shipping cart so to speak to it. I'm trying to make the interface easier to use and navigate through jquery. The 'cart' is stored via sessions in php. I have a page that outputs all the inventory and I am adding buttons that allow the user to add or remove each specific item from the 'cart', but only one button should be shown based on cart status (i.e. if the item is in cart, show the remove button).
Ive got a mess of jquery code as I'm trying all sorts of approaches
heres some php:
if(isset($_SESSION['cart'][$row['bbn']])) {
echo "REMOVE FROM CART\n";
echo "ADD TO CART\n";
} else {
echo "ADD TO CART\n";
echo "REMOVE FROM CART\n";
}
here's some jquery:
$(".addtocart").each(function (i) {
if($(this).hasClass('active')){
$(this).siblings('.removefromcart').hide();
}
});
$(".removefromcart").each(function (i) {
if($(this).hasClass('active')){
$(this).siblings('.addtocart').hide();
}
});
// View_inventory add button
$(".addtocart").click(function(){
var $bbn = $(this).parent().attr("id");
var $object = this;
$.ajax({
url: "queue.php?action=add",
data: { bbn: $bbn },
type: 'GET',
success: function(){
$($object).hide();
$($object).siblings('.removefromcart').show('highlight');
}
});
});
$(".removefromcart").click(function(){
var $bbn = $(this).parent().attr("id");
var $object = this;
$.ajax({
url: "queue.php?action=remove",
data: { bbn: $bbn },
type: 'GET',
success: function(){
$($object).hide();
$($object).siblings('.addtocart').show('highlight');
}
});
});
Any suggestions as to how I should make this simpler? Ive got it working now.
first in php:
$cart = '';
$noCart = '';
if ( ! isset($_SESSION['cart'][$row['bbn']]) ) $cart = 'inactive';
else $noCart = 'inactive';
echo 'REMOVE FROM CART\n';
echo 'ADD TO CART\n';
now I present two method, the first one will execute slightly faster as it only switch classes in css, but you don't get your fancy effect. you get it in the second method.
first method
add to your css:
.inactive {display: none;}
and in js:
$(".addtocart, .removefromcart").click(function(){
var $object = $(this);
var bbn = $object.parent().attr("id");
var action = $object.find('.addtocart').length ? 'add' : 'remove';
$.get("queue.php", {"action": action, "bbn": bbn}, function (data) {
$object.addClass('inactive').siblings().removeClass('inactive');
});
});
Second method, no need for a CSS entry.
$(function () { // equivalent to $(document).ready(function () {
$('.inactive').hide();
$(".addtocart, removefromcart").click(function(){
var $object = $(this);
var bbn = $object.parent().attr("id");
var action = $object.find('.addtocart').length ? 'add' : 'remove';
var params = {action: action, bbn: bbn};
// $('#someSpinnigLoadingImage').show();
$.get("queue.php", params, function (data) {
// $('#someSpinnigLoadingImage').hide();
$object.hide().siblings().show('highlight');
});
});
});
hope this help. note: I didn't test the code, some nasty typo might have slipped through.
Additionnal note, you might want some visual effect right before the ajax call (like in the comment in version 2, or hide $object, so that the user can't multiclick it.
$object.hide()
$.get("queue.php", params, function (data) {
$object.siblings().show('highlight');
});
Related
I create a load more button for load more posts from the database but when I add like button for that if one time clicks on load more button and then click on the like button, like.php file runs two times and adds two lines in likes table. if I click 2 times on load more then like.php file runs 3 times and...
I want to know how I should create a loadmore button and like the button to works fine.
this is simple of my codes:
posts.php :
<div id="comnts2"></div>
<button id="btn2" >load more</button><script>
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>
ld_comco.php:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" src="pc3/up.png">'.$lik.' Likes</img>';
?>
</span>
<?php }?>
<script type="text/javascript">
$(document).ready(function() {
var uid=<?php echo $uid;?>;
$(document).on("click", ".li_ik1", function() {
var psid = $(this).data('id');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
});
</script>
like.php:
<?php
$id=$_POST['psid'];
$uid=$_POST['uid'];
$Y=mysqli_query($conn,"INSERT INTO `t_plik` (pid,uid) VALUES ('$id','$uid')");
$Q=mysqli_query($conn,"UPDATE `tbl_users_posts` SET lik=lik+1 WHERE id='$id'");
?>
thanks
I think the problem is, that you bind your like button multiple times globally. Each time you load the content from ld_comco.php you also call $(document).on("click", ".li_ik1", ...) in the $(document).ready block, which means you bind all ".li_ik1" buttons on the entire document (but some of them has already been bind).
I would remove the $(document).ready(...) block from the ld_comco.php and move the logic into the posts.php right before you render your content. A further positive aspect is you have your business logic at one place.
KEEP IN MIND: You get a response of buttons in msg2, thats why you do not need to filter $msg2 anymore. But if you wrap your buttons with further html tags in ld_comco.php, your buttons will be on a deeper level, so you need to use a selector again, like you did with .on("click", ".li_ik1", ...).
posts.php
...
var $msg2 = $(msg2);
// Now you bind only the loaded buttons instead of
// the buttons in the entire document for multiple times
$msg2.on("click", function() {
var $element = $(this);
var psid = $element.data('id');
var uid = $element.data('uid');
$.ajax({
method: "POST",
url: "like.php",
data: {psid: psid, uid: uid}
}).done();
});
$("#comnts2").append($msg2);
...
In your ld_comco.php you need to add the data-uid="'.$uid.'" and remove the script block. Then your file should look like this:
<?php
$comnco2=$_POST['comnco2'];
$offset2=$_POST['offset2'];
$rzp=mysqli_query($conn,"SELECT * FROM `tbl_users_posts` WHERE uid = '$uid' ORDER BY id DESC limit $offset2, $comnco2");
while($rp=mysqli_fetch_assoc($rzp)){
$sid=$rz['id'];
$lik=$rz['lik'];
echo $sid."<br>";
/*like*/
echo'<img class="li_ik1" data-id="'.$sid.'" data-uid="'.$uid.'" src="pc3/up.png">'.$lik.' Likes</img>';
}
?>
$("#btn2").trigger("click");
this in posts.php means click the #btn2
so after clicking it, you click it again
$(document).ready(function() {
var comco2 = 2;
var offset2 = 0;
$("#btn2").click(function() {
$.ajax({
method: "POST",
url: "ld_comco.php",
data: { comnco2 : comco2, offset2 : offset2}
})
.done(function(msg2) {
$("#btn2").hide();
} else {
$("#comnts2").append(msg2);
});
offset2 = offset2 + comco2;
});
$("#btn2").trigger("click");
});
</script>
i am using smoke.js which allows to style the classic alert javascript windows.
All you have to do is place .smoke before the alert ie. smoke.confirm()
The issue I am having is with the ok/cancel callback, it isnt working for me.
This is the example the website shows.
`You can implement these the same way you'd use the js alert()...just put "smoke." in front of it.
The confirm() replacement, however, needs to be used just a little differently:
smoke.confirm('You are about to destroy everything. Are you sure?',function(e){
if (e){
smoke.alert('OK pressed');
}else{
smoke.alert('CANCEL pressed');
}
});
and the code I have is;
$(".upb_del_bookmark").click( function() {
if(smoke.confirm(delete_message)) {
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
It shows the style button and everything but when i click on OK it doesnt perform the function above, nothing happens.
So i rewrote it to
$(".upb_del_bookmark").click( function() {
if(smoke.confirm(delete_message, function(e))) {
if(e){
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
}}
But now when i click it doesnt even show anything
I am not a programmer, Help!!!!!
If you want to try it go to latinunit.org login with david:123321 and then go to a post and try to add it to your favourites
Update
I tried the following, it shows the window but it doesnt perform the function;
$(".upb_del_bookmark").click( function() {
smoke.confirm(delete_message, function(e) {
if(e){
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
}})
return false;
});
Here is the js file of the smoke script Link
When i click on cancel the following shows;
Uncaught TypeError: Property 'callback' of object # is not a
function Line:198
Uncaught TypeError: Property 'callback' of object # is not a
function Line:208
The following is what's on those linesof the smoke script;
finishbuildConfirm: function (e, f, box)
{
smoke.listen(
document.getElementById('confirm-cancel-' + f.newid),
"click",
function ()
{
smoke.destroy(f.type, f.newid);
f.callback(false);
}
);
smoke.listen(
document.getElementById('confirm-ok-' + f.newid),
"click",
function ()
{
smoke.destroy(f.type, f.newid);
f.callback(true);
}
);
The builtin javascript alert/confirm functions are synchronous, this is not. You need to handle the result of the confirm using the javascript callback pattern. You pass a function to the smoke.confirm() function which called when you need to respond to an action.
See the following code. The if around the smoke.confirm() has been removed and the handling code is wrapped in the function passed to the smoke.confirm() function.
$(".upb_del_bookmark").click( function() {
smoke.confirm(delete_message, function(e) {
if(e){
var post_id = $(this).attr('rel');
var data = {
action: 'del_bookmark',
del_post_id: post_id
};
$.post(upb_vars.ajaxurl, data, function(response) {
$('.bookmark-'+post_id).fadeOut();
$('.upb_bookmark_control_'+post_id).toggle();
});
}
});
}
I highly recommend reading a little about the callback pattern in javascript. It's very common and understanding it will help you use this plugin and many others.
So I'm learning JQuery and I'm stuck on this:
I have a page that displays a HTML table and inside that table I want to have a cell that can be updated via a dropdown menu, so you click on edit, the current value disappears and dropdown menu appears, and when the value is changed the database is updated and the new value is displayed. (with the menu disappearing)
The problem seem to be putting the .text and .show inside the data callback function - if I alert the data it is returning the correct data from the PHP file, and if I comment out the .post line and replace the (data) with ("test_text") it replaces the menu as I want it to.
Hopefully my question is well enough written to make sense, thanks.
Here's the code
$('.cat_color_hide_rep').hide();
$('.act_status_dropD').click(function () {
var record_id = $(this).parents('tr').find('.record_id').text()
$(this).parents('tr').find('.cat_color_hide_rep').show();
$(this).parents('tr').find('.cat_color_show_rep').hide();
});
$('.cat_color_hide_rep').change(function () {
var record_id = $(this).parents('tr').find('.record_id').text()
$(this).parents('tr').find('.cat_color_hide_rep').hide();
$.post('TEST_ajax_rep_list_status.php', {
ID: record_id
}, function (data) {
$(this).parents('tr').find('.cat_color_show_rep').text(data);
$(this).parents('tr').find('.cat_color_show_rep').show();
alert(data); // for testing
});
});
You can not access the $(this) inside the $.post function.
You can do this before the $.post:
var that = this;
And inside the post, do this:
$(that).parents('tr').find('.cat_color_show_rep').text(data);
$(that).parents('tr').find('.cat_color_show_rep').show();
This would be your resulting code:
$('.cat_color_hide_rep').hide();
$('.act_status_dropD').click(function () {
var record_id = $(this).parents('tr').find('.record_id').text()
$(this).parents('tr').find('.cat_color_hide_rep').show();
$(this).parents('tr').find('.cat_color_show_rep').hide();
});
$('.cat_color_hide_rep').change(function () {
var record_id = $(this).parents('tr').find('.record_id').text()
$(this).parents('tr').find('.cat_color_hide_rep').hide();
/** ADDED LINE **/
var that = this;
$.post('TEST_ajax_rep_list_status.php', {
ID: record_id
}, function (data) {
/** CHANGED LINES **/
$(that).parents('tr').find('.cat_color_show_rep').text(data);
$(that).parents('tr').find('.cat_color_show_rep').show();
alert(data); // for testing
});
});
In the callback function, this has been changed to refer to the XHR Object, you need to backup an reference of this from outside the function if you want to access it from the callback
var $this = $(this);
$.post('TEST_ajax_rep_list_status.php', {
ID: record_id
}, function (data) {
$this.parents('tr').find('.cat_color_show_rep').text(data);
$this.parents('tr').find('.cat_color_show_rep').show();
alert(data); // for testing
});
//Cache your selectors!
var catColorHide = $('.cat_color_hide_rep');
catColorHide.hide();
$('.act_status_dropD').on('click', function () { //Use the .on() method and save a function call. The .click() simply calls the .on() and passes in the callback.
var this = $(this), //If you use a selection more than once, you should cache it.
record_id = this.parents('tr').find('.record_id').text();
this.parents('tr').find('.cat_color_hide_rep').show();
this.parents('tr').find('.cat_color_show_rep').hide();
});
catColorHide.on('change', function () {
var this = $(this),
record_id = this.parents('tr').find('.record_id').text();
this.parents('tr').find('.cat_color_hide_rep').hide();
$.post('TEST_ajax_rep_list_status.php', {
ID: record_id
}, function (data) {
// I don't do the 'var this = $(this)' in here to fix your problem. The 'this' you see me using here refers to the element from the callback.
this.parents('tr').find('.cat_color_show_rep').text(data);
this.parents('tr').find('.cat_color_show_rep').show();
console.log(data); // Use this for testing instead.
});
});
I'm totally new to jquery and AJAX, After trying hard for 5-6 hours and searching the solution I'm asking for the help.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit").live('click',(function() {
var data = $("this").serialize();
var arr = $("input[name='productinfo[]']:checked").map(function() {
return this.value;
}).get();
if(arr=='')
{
$('.success').hide();
$('.error').show();
}
else
{
$.ajax({
data: $.post('install_product.php', {productvars: arr}),
type: "POST",
success: function(){
$(".productinfo").attr('checked', false);
$('.success').show();
$('.error').hide();
}
});
}
return false;
}));
});
</script>
and HTML+PHP code is,
$json = file_get_contents(feed address);
$products = json_decode($json);
foreach(products as product){
// define various $productvars as a string
<input type="checkbox" class="productvars" name="productinfo[]" value="<?php echo $productvars; ?>" />
}
<input type="submit" class="submit" value="Install Product" />
<span class="error" style="display:none"><font color="red">No product selected.</font></span>
<span class="success" style="display:none"><font color="green">product successfully added to database.</font></span>
As I'm pulling the product information from feed, I don't want to refresh the page, that's why I'm using AJAX post method. Using above code "install_product.php" page is handling the string properly and doing its job properly.
The problem I'm facing is, when first time I check the check box and install the product it works absolutely fine, but after first post "Sometimes it work and sometimes it won't work". As new list is pulled from feed every first post is perfect after that I need to click install button again and again to do so.
I tested the code on different browsers, but same problem. What may be the problem?
(I'm testing the code on live host not localhost)
$.live is deprecated, consider using $.on() instead.
Which function is not executing after it executes once? $.live?
Also, it should be:
var data = $(this).serialize();
not
var data = $("this").serialize();
In your example, you are looking for an explicit tag called 'this', not a scope.
UPDATE
$(function () {
$(".submit")
.live('click', function(event) {
var data = $(this).serialize();
var arr = $("input[name='productinfo[]']:checked")
.map(function () {
return this.value;
})
.get();
if (arr == '') {
$('.success')
.hide();
$('.error')
.show();
} else {
$.ajax({
data: $.post('install_product.php', {
productvars: arr
}),
type: "POST",
success: function () {
$(".productinfo")
.attr('checked', false);
$('.success')
.show();
$('.error')
.hide();
}
});
}
event.preventDefault();
});
});
Is it possible, it is missing the value at arr and showing up the error or is it like it is making call but not returning or it is not reaching the call at all?
Do a console.log to deal with debuging and check things out in firefox / chrome and see what and where is the issue.
I have this
"fsField" is the class of all elements in the form. So whenever the user blurs to another field it submits the form using the function autosave() - given below. It saves data when the user blurs but when the user clicks the button with class "save_secL" to go to next page it does not save.
$('.fsField').bind('blur', function()
{
autosave();
}
});
but when i use this code
$('.save_secL').click(function()
{
var buttonid = this.id;
{
var answer = confirm("You have left some questions unanswered. Click OK if you are sure to leave this section? \\n Click CANCEL if you want stay in this section. ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="unanswered" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
else
{
$('#hidden_agree').append('<input id="secLuseragreed" name="secL_user_agreed" value="answered all" type="hidden" />');
autosave();
window.location= buttonid+".php"
}
}
});
**autosave_secL.php is the php source thats saving the data in the database. I ran it independently and it does save data okay. **
function autosave()
{
var secL_partA_ques_1_select = $('[name="secL_partA_ques_1_select"]').val();
var secL_partA_ques_1 = $('[name="secL_partA_ques_1"]:checked').val();
var secL_partA_ques_2_select = $('[name="secL_partA_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partA_ques_1_select=" + secL_partA_ques_1_select + "&secL_partA_ques_1=" + secL_partA_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
}
});
}
**
valid() is a validation function that checks if any field is empty and returns a value if there is an empty field.**
function valid()
{
var items = '';
$('.fsField').each(function()
{
var thisname = $(this).attr('name')
if($(this).is('select'))
{
if($(this).val()=='')
{
var thisid = $(this).attr('id')
items += "#\"+thisid+\",";
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '#B5EAAA');
}
}
else
{
$('[name=\"'+thisname+'\"]').closest('td').css('background-color', '');
}
});
return items;
}
Can anyone please help? i am stuck for a day now. Can't understand why it saves when the user goes field to field but does not save when button is clicked with validation.
Tested with Firefox. this line appears in red with a Cross sign beside when the button(save_secL class) is clicked. I am using a ssl connection.
POST https://example.com/files/autosave_secL.php x
Here is the modified code trying to implement the solution
$('#submit_survey_secL').click(function()
{
if(valid() !='')
{
var answer = confirm("You have left some questions unanswered. Are you sure you want to Submit and go to Section B? ");
if(!answer)
{
var spl_items = valid().split(',');
$(spl_items[0]).focus();
return false;
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=4"
});
}
}
else
{
$('#hidden_agree').append('<input id=\"secLuseragreed\" name=\"secL_user_agreed\" value=\"unanswered\" type=\"hidden\" />');
autosave(function(){
window.location= "part1secM.php?token=1&id=6"
});
}
});
function autosave(callback)
{
var secL_partL_ques_1_select = $('[name="secL_partL_ques_1_select"]').val();
var secL_partL_ques_1 = $('[name="secL_partL_ques_1"]:checked').val();
var secL_partL_ques_2_select = $('[name="secL_partL_ques_2_select"]').val();
$.ajax(
{
type: "POST",
url: "autosave_secL.php",
data: "secL_partL_ques_1_select=" + secL_partL_ques_1_select + "&secL_partL_ques_1=" + secL_partL_ques_1 + "&user_id=<?php echo $row_token[user_id]?>" + "&updated_by=<?php echo $member."-".$key;?>",
cache: false,
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
{
callback();
}
}
});
}
I don't understand why this doesn't work as callback should totally work. Firebug does not show POST https://example.com/files/autosave_secL.php in red any more but it shows that it has posted but I think the callback is not triggering for some reason
$('.save_secL').click(function() {
//...
//start autosave. Note: Async, returns immediately
autosave();
//and now, before the POST request has been completed, we change location...
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
//....and the POST request gets aborted :(
Solution:
function autosave(callback)
{
//...
$.ajax(
{
//...
success: function()
{
$("#timestamp").empty().append('Data Saved Successfully!');
if($.isFunction(callback))
callback();
}
});
}
//and
autosave(function(){
window.location= buttonid+".php?token=$row_token[survey_token]&$member=$key&agr=1"
});
By the way, your autosave function is pretty hard for your server. Did you consider using localStorage + a final POST request containing all data?
I got the solution.
It might be one of the several. scr4ve's solution definitely helped. So here are the points for which I think its working now.
Moved "cache: false, " and removed "async:false" before url: in the ajax autosave function. Before I was putting it after "data: "
Added a random variable after autosave_secL.php/?"+Match.random()
Added scr4ve's solution so that POST is completed before redirect