Adding icon to product added in cart PHP/Jquery - php

I am trying to add a checkmark to the products that have been added to cart.
I am using ajax to return.
But i know i am doing wrong.
I got a bit lost.
I made with php first,and it works,but only displays when i refresh the page.
My php code...
if(isset($_SESSION['product'][$id])){
$added='<a href="" class="badge-corner" product_id="'.$id.'" >
<span class="fa fa-check"></span></a>';
}else{
$added='';
}
I want to use ajax to display the checkmark.
This is where i get my product id and store them to session.
My add to cart function and item counter code..(cart_function2.php)
<?php header('Content-Type: application/json');
session_start();
if (isset($_GET['action'])) {
$action = $_GET['action'];
$prod = $_GET['prod_id'];
$result="";
switch ($action) {
case 'add':
$result = add_prod($prod);
break;
default:
$result = ['result'=>'error'];
break;
}
}
// Calculate subtotal here
$result['totals'] = new stdClass;
$total_in_cart=count($_SESSION['product']);
$_SESSION['products']=$total_in_cart;
if(isset($_SESSION['product'][$prod])){
$added='</span>';
}else{
$added='';
}
$result['added'] = $added;
$result['items'] = $total_in_cart;
echo json_encode($result);
function add_prod($prod){
//add function
$_SESSION['product'][$prod] = 1;
$_SESSION['products']++;
return ['result'=>'success'];
}
?>
And this is the script in my gallery...
$('.actions').click(function(e){
e.preventDefault(e);
var action = $(this).attr('data-action'); //gets button id
var id = $(this).attr('product_id');
console.log("triggered action " + action + " for product " + id);
$.ajax({
url: 'cart_functions2.php',
type : 'GET',
data: {action:action,prod_id:id},
dataType: 'json'
}).done(function(data) {
console.log("ajax call returned the following: " + JSON.stringify(data));
if (data.result == "success") {
$("#items").html(data.items);
$(".show").html(data.added) + id;
//some debugging script
i am trying to display in here
<div class="show">'.$added.'</div>
When i click add product, all my products gets checked at once.
Why?
Please help me,i'm still a noob at jquery.

Related

pass PHP value back to AJAX function on success

I'm building an AJAX timeline of wall posts and I have the following function to check for new posts and then post the new ones to the wall, similar to how Twitter works:
wall_posts.php
$news = tz::shared()->news->getNew(25);
<div id="wall_posts">
<?php foreach ($news as $news_post) { ?>
<div class="wall_post"><?php echo $news_post['message']; ?></div>
<?php } ?>
</div>
jQuery:
function checkForNewPosts() {
// This represents the last record in the table AKA the "most recent" news
var lastCustomerNewsID = <?php echo $news[0]['id']; ?>;
$.ajax({
url: "example.com/ajax.php",
method: "post",
data:{
lastCustomerNewsID: lastCustomerNewsID,
},
dataType:"text",
success:function(data)
{
$('#wall_posts').prepend(data);
}
});
}
setInterval(checkForNewPosts, 10000);
The news PHP array above with index 0 indicates it is the last/most recent ID in the array/table
PHP (ajax.php):
if ($_POST) {
$lastCustomerNewsID = $_POST['lastCustomerNewsID'];
$new_posts = tz::shared()->news->getNewForWall($lastCustomerNewsID);
$output = '';
if ($new_posts) {
foreach ($new_posts as $new_post) {
$output .= "<div class='wall_post'>";
$output .= $new_post['message'];
$output .= "</div>";
}
} else {
}
echo $output;
}
Note - The function getNewForWall pulls records with an id greater than the argument passed in
This works fine when getting a new post, however the problem is that I need to update the "last id" to the "newest id" from the new records returned in ajax.php each time the function runs, because currently once its grabs the newest posts the first time, its keeps recognizing those as new on an ongoing basis.
How can I pass the newest "last id" from the array in ajax.php back to the AJAX function each time it runs? Can I pass a separate variable back to the AJAX function?
Thanks!
First of all, I think PHP here should return JSON instead of HTML information
JQuery should process JSON to generate HTML information
The PHP code looks like this (this is an example)
<?php
$page = $_POST['page'];
$method = $_GET['method'];
if ($method == "list") {
$limit = 20;
$offset = ($page - 1) * $limit;
$post = new Post();
// Calculate offsets according to page limits and page numbers and query articles
//Let's assume that the field of content is "content"
$offset = ($page - 1) * $limit;
$post_list = $post->offset($offset)->limit($limit)->select();
$total = $post->offset($offset)->limit($limit)->count(); //Statistics of all entries
//Get the largest ID by ID sort
$last_id = $post->order('id desc')->find();
$last_id = $last_id['id'];
echo json_encode([
'last_id' => $last_id,
'post_list' => $post_list,
"maxpage"=>ceil($total / $limit), //Calculate the maximum number of pages
]);
} elseif ($method == 'last_check') {
$post = new Post();
//Get the largest ID by ID sort
$last_id = $post->order('id desc')->find();
$last_id = $last_id['id'];
echo json_encode([
'last_id' => $last_id,
]);
}
Now we can check whether there are new articles through timers and page flips.
And you can use maxpage to determine if there is the next page.
function checkForNewPosts() {
$.ajax({
url: "example.com/ajax.php?method=last_check",
method: "get",
dataType:"json",
success:function(data)
{
if(data.last_id>lastCustomerNewsID){
//Write a new post operation here.
lastCustomerNewsID = data.last_id;
}
}
});
}
function getNextPage(){
var html;
page = page + 1;
$.ajax({
url: "example.com/ajax.php?method=list",
method: "post",
data:{
"page": page
},
dataType:"json",
success:function(data)
{
//Collate JSON into the required HTML format
html = "";
$.each(data.post_list, function(i, item){
html = html + "<div class='wall_post'>" + item.contect + "</div>";
});
if(data.last_id>lastCustomerNewsID){
//Write a new post operation here.
lastCustomerNewsID = data.last_id;
}
if(data.maxpage<=page){
//If there is no next page
}
$('#wall_posts').prepend(data);
}
});
}
setInterval(checkForNewPosts, 10000);

Trigger combo box events using jquery

I have this code:
$show_location = mysql_query("SELECT * FROM location ORDER BY location_code");
while($row_location = mysql_fetch_array($show_location))
{
$location_code = $row_location['location_code'];
$show_store = mysql_query("SELECT * FROM store_list WHERE location LIKE '%$location_code%'");
$count_store = mysql_num_rows($show_store);
while($row_store = mysql_fetch_array($show_store))
{
$store_name = $row_store['store_name'];
}
if($count_store==0)
{
$status = "Inactive";
echo '<option value="'.$location_code.'">'.$location_code.'</option>';
$sql1 = "SELECT description FROM location WHERE location_code=$location_code";
$result1 = mysql_query("$sql1");
$row1 = mysql_fetch_assoc($result1);
$description=$row1['description'];
}
else
{
$status = "Active";
}
//echo '<option value="'.$location_code.'">'.$location_code.'</option>';
}
What I want to do is to display the $description somewhere in the form. I have the kind of combobox where you can select as many as you can. I want to display each $description once a location is selected. But I dont know where to put the trigger. Can sombody help me? Thanks!
correct me if i am wrong, but will every location_code have one description right?
well there are two ways:
1) Easy but not so efficient way
Make an ajax call for every selected value.
$("#myDropDown").change(function (event) {
//alert("You have Selected :: "+$(this).val());
$.ajax({
type: "POST",
url: "ajax.php",
data: { type: "1", location: $(this).val() }
}).done(function( msg ) {
("#mydata").html(msg)
});
});
You can check for type == 1 on php side, get the description and print it
The above method will cause a ajax request for every selection
2) A bit complex, but efficient
First of all json_encode your location_code and description. It will become something like {code:"AU", description:"blah blah"}
Then use something like this
$("#sel").change(function(e){
//alert($(this).val());
var array = $(this).val();
for(key in array){
var json = JSON.parse(array[key]);
$("#desiptions").html(json.description);
}
});

Add Product to Session of Wishlist and not delete the session like now

I got a problem with my shopping cart wishlist sessions. I add with a button an article to wishlist in form of an session array when i click another icon to whishlist he removes me the clicked item before an delete the session of the item selected before.
here is my js code to grab values for session:
$(document).ready(function(){
$(".addButton").on("click", function(event){
event.preventDefault();
var button = $(this);
var parent = button.parent();
var wlproducturl = parent.find("input[name$='.id']").val();
var wlproduct = parent.find("input[name$='.name']").val();
$.ajax({
type : "POST",
url : "../assets/wlscript.php",
data : { wlproduct : wlproduct, wlproducturl : wlproducturl },
success : function(data) {
$('div#resultwish').html('<div class="alert alert-success in fade" ><button type="button" class="close" data-dismiss="alert">×</button>You added '+wlproducturl+' '+wlproduct+'\'s to your wishlist.</div>');
}
});
// alert("Add article with id = " + idArticle + " and name = " + nameArticle);
});
});
This is my wlscript php file:
<?php
session_start();
$p = trim($_POST['wlproduct']);
$q = trim($_POST['wlproducturl']);
$orders[$p] = $q;
$_SESSION['orders'] = $orders;
?>
And so I output the selected items:
<?php
session_start();
print_r($_SESSION['orders']);
?>
So how can I add new item to session without deleting the old one add a product more to wishlist?
Maybe simply because you are overwriting $orders each time, with your actual code:
<?php
session_start();
$p = trim($_POST['wlproduct']);
$q = trim($_POST['wlproducturl']);
$orders[$p] = $q; // UNAWARE IF $_SESSION['orders'], OR $orders ALREADY CONTAIN SOMETHING...
$_SESSION['orders'] = $orders; // ... AND THEREFORE ALL IS OVERWRITTEN.
?>
Maybe this ?
<?php
session_start();
// if (session_is_registered("orders")) // CAREFUL, OBSOLETE SINCE PHP 5.4.0
if (is_array($_SESSION['orders']))
{
$orders = $_SESSION['orders']; // RETRIEVING WHAT HAS PREVIOUSLY BEEN STORED
}
$p = trim($_POST['wlproduct']);
$q = trim($_POST['wlproducturl']);
$orders[$p] = $q; // THIS NOW ADDS TO EXISITNG
$_SESSION['orders'] = $orders;
?>

PHP / AJAX Shopping cart not working correctly

I'm having some problems with, building a shopping cart.
I cannot set a different quantity for each items in my shop. The quantity should be picked up from an input field, at that is working fine. But if you're setting the quantity to 3 for item 1, and the quantity to 5 for item 2, every items will have the quantity of 5 (the last added).
Also when you're trying to delete one of the items, the quantity now will be set to zero, of every items. It is like, that the quantity of each item is not stored, and I have no idea why this is happening.
The cart I'm using, is PHP/SQL and AJAX.
This is my code so far:
PHP:
<?php
// This doument contains the AJAX generated for the building-cart
/////////////////////////////////////////////////////////////////
// Clear Cache and include config.php
include("includes/config.php");
// Start Session
session_start();
?>
<?php
$product_id = $_GET['id']; //the product id from the URL
$action = $_GET['action']; //the action from the URL
$quantitys = $_GET['qun']; //the action from the URL
// if there is an product_id and that product_id doesn't exist display an error message
if($product_id && !productExists($product_id)) {
die("Error. Product Doesn't Exist");
}
// decide what to do
switch($action) {
case "add":
//add one to the quantity of the product with id $product_id
if($_SESSION['cart'][$product_id] < 1) { $_SESSION['cart'][$product_id]++; }
break;
case "remove":
$_SESSION['cart'][$product_id]--; //remove one from the quantity of the product with id $product_id
if($_SESSION['cart'][$product_id] == 0) unset($_SESSION['cart'][$product_id]); //if the quantity is zero, remove it completely (using the 'unset' function) - otherwise is will show zero, then -1, -2 etc when the user keeps removing items.
break;
case "empty":
unset($_SESSION['cart']); //unset the whole cart, i.e. empty the cart.
break;
}
?>
<?php
//if the cart isn't empty show the cart
if($_SESSION['cart']) {
echo '<ul id="cart-items">'."\n";
//iterate through the cart, the $product_id is the key and $quantity is the value
foreach($_SESSION['cart'] as $product_id => $quantityt) {
//get the name, description and price from the database - this will depend on your database implementation.
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$result = mysql_query("SELECT * FROM single_partners WHERE single_id = $product_id");
//Only display the row if there is a product (though there should always be as we have already checked)
if(mysql_num_rows($result) > 0) {
if($test = mysql_fetch_array($result)) {
$partner_id = $test['partner_id'];
$partner_price = $test['price'];
}
// Get partner name
$get_partner_name = mysql_query("SELECT * FROM partners WHERE partner_id='$partner_id'");
if($partner_name = mysql_fetch_array($get_partner_name)) {
$name = $partner_name['name'];
$logo = $partner_name['logo'];
$type = $partner_name['type'];
$logo_dir = "media/partners/build/color/";
$line_cost = $partner_price * $quantitys; //work out the line cost
$total = $total + $line_cost; //add to the total cost
}
echo '<li>'."\n";
echo '<div class="logo" style="background-image: url('.$logo_dir.$logo.')">'."\n";
echo '</div>'."\n";
echo '<div class="details">'."\n";
echo '<span class="name">'.$name.'</span>'."\n";
echo '<span class="details">details</span>'."\n";
echo '</div>'."\n";
echo '<div class="price"><input name="qun" type="hidden" value="'.$quantitys.'" /><input name="partner" type="hidden" value="'.$product_id.'" /><span class="remove-button"></span>'."\n";
echo '<span class="price">'.number_format((float)$line_cost, 2, ',', '').'</span>'."\n";
echo '</div>'."\n";
echo '</li>'."\n";
}
}
echo '<div class="footer">'."\n";
echo '<span class="empty-button">Empty</span>'."\n";
echo '<span class="total-price">'.number_format((float)$total, 2, ',', '').'</span>'."\n";
echo '</div>'."\n";
echo '</ul>'."\n";
}else{
//otherwise tell the user they have no items in their cart
//echo "You have no items in your shopping cart.";
}
//function to check if a product exists
function productExists($product_id) {
//use sprintf to make sure that $product_id is inserted into the query as a number - to prevent SQL injection
$sql = mysql_query("SELECT * FROM single_partners WHERE single_id = $product_id");
return mysql_num_rows($sql) > 0;
}
?>
AJAX Call:
// Load building cart, when adding items
$(document).on('click', 'input[type=button].add-button', function() {
// AJAX - Define data to send
var actiontype = "add";
productid = $('input[name="address"]').val();
quantity = $('input[name="qun"]').val();
var data = "action="+ actiontype + "&id="+ productid + "&quantity="+ quantity;
$.ajax({
url: 'buildingcart.php',
data: data,
success:function(result) {
// Show result
$('#building-cart .content').html(result);
}
});
});
// Load building cart, when adding items
$(document).on('click', '.remove-button', function() {
// AJAX - Define data to send
var actiontype = "remove";
productid = $(this).parent().find('input[name="partner"]').val();
var data = "action="+ actiontype + "&id="+ productid;
$.ajax({
url: 'buildingcart.php',
data: data,
success:function(result) {
// Show result
$('#building-cart .content').html(result);
}
});
});
// Load building cart, when adding items
$(document).on('click', '.empty-button', function() {
// AJAX - Define data to send
var actiontype = "empty";
var data = "action="+ actiontype;
$.ajax({
url: 'buildingcart.php',
data: data,
success:function(result) {
// Show result
$('#building-cart .content').html(result);
}
});
});
I tried changing
foreach($_SESSION['cart'] as $product_id => $quantity)
to
foreach($_SESSION['cart'] as $product_id)
with no luck.
I also want to have the ability to set a different size for each item, but the same thing happens here. It always takes the quantity/size of the last added item, and update it to the rest of the items, which is not intended.
Sorry for the long codes.. Hope someone can help me :-)

Ajax call doesn't return data after echoed

The ajax call successfully update the record but doesn't return the string of echo. This script was working before but might be because of some upgrade it stops working. It is working fine on my local system but when I move it to bluehost server then it does not work.
Here is my Ajax call:
// call to ajax script to update site
function autopost_update_site() {
// get base directory url
var baseDir = jQuery('#baseDir').val();
var id = jQuery('#site_id').val();
var site_name = jQuery('#site_name').val();
var site_url = jQuery('#site_url').val();
var is_active;
if ( jQuery('#active_radio').is(':checked') ){
is_active = '1';
} else {
is_active = '0';
}
var username = jQuery('#login_username').val();
var login_pass = jQuery('#login_pass').val();
// call to ajax script to update script
jQuery.ajax( {
type: "POST",
url: baseDir + "/autopost_ajax_actions.php",
data: "id=" + id + "&site_name=" + site_name + "&site_url=" + site_url + "&is_active="+ is_active + "&username=" + username + "&login_pass="+login_pass +"&action=update_site",
beforeSend: function() {
jQuery('#update_site_button').attr("disabled", true);
// shortcode edit button
jQuery('#update_site_button').html('Updating...');
// admin page edit button
jQuery('#update_site_button').val('Updating...');
},
complete: function() {
jQuery('#update_site_button').attr("disabled", false);
// shortcode edit button
jQuery('#update_site_button').html('Update');
// admin page edit button
jQuery('#update_site_button').val('Update');
},
success: function(data) {
alert("Result: " + data); // NOTHING IS HAPPENING HERE, NO ALERT DATA
if (jQuery.trim(data) === "success") {
alert("Site updated.");
// refresh page
window.setTimeout('location.reload()', 200);
} else {
alert("Some error occured, Please try again.");
}
}
});
}
Here is my custom php script for ajax actions:
// update site
if ( $_POST['action'] == 'update_site' && isset ($_POST['id']) ) {
// collect site data
$site_name = $wpdb->escape($_POST['site_name']);
$site_id = intval($wpdb->escape($_POST['id']));
$site_url = $wpdb->escape($_POST['site_url']);
$username = $wpdb->escape($_POST['username']);
$login_pass = $wpdb->escape($_POST['login_pass']);
$is_active = $wpdb->escape($_POST['is_active']);
$query = $wpdb->prepare("UPDATE " . $autopost_sites_table_name . " SET site_name = %s, site_url = %s, username = %s, login_pass = %s, is_active = %s WHERE id = %s", $site_name, $site_url, $username, $login_pass, $is_active, $site_id);
#$log->LogDebug($query);
// execute query
$result = $wpdb->query($query);
#$log->LogDebug($result);
if ( $result !== FALSE || $result !== 0) {
// return success
$response = "success";
#$log->LogDebug($response);
echo $response; // THIS RESPONSE IS NOT SHOWING ON AJAX SUCCESS
} else {
$log->LogError("Failed to update site with ID: " . $_POST['id']);
echo "Failed to update site.";
}
}
Can anyone tell me what is missing?
Change data as follows
data:{
id:id,
site_name:site_name,
site_url:site_url ,
is_active:is_active ,
username:username,
login_pass:login_pass,
action:"update_site"
}
As It is mentioned that the script is working great on local but not working on server. So it was some server issue and I was getting error for "Access-Control-Allow-Origin" in chrome network.
I just added
header('Access-Control-Allow-Origin: *');
to my ajax action script and it worked! Thanks
after
echo $response;
put
die();
See http://codex.wordpress.org/AJAX_in_Plugins
In the example it says:
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}

Categories