I got this opensource php mini cart from youtube. Now the problem is how to apply it with ajax or javascript? So that everytime I add, remove and delete the items it wont refresh the whole page and will still work whether the javascript is on or off. If javascript is on the cart.php will use javascript and if it is off the cart.php will use php.
here's the code for add, remove and delete items in the cart. To look or download the full source code just click this link: cart php source code
if(isset($_GET['add'])){
// use session to add the product
$quantity = mysql_query('SELECT id, quantity FROM products WHERE id='.mysql_real_escape_string((int)$_GET['add']));
while($quantity_row=mysql_fetch_assoc($quantity)){
//if quantity is not equal in the database quantity
if ($quantity_row['quantity']!=$_SESSION['cart_'.(int)$_GET['add']]){
$_SESSION['cart_'.(int)$_GET['add']]+='1';
}
}
header('Location: '.$page);
}
if(isset($_GET['remove'])){
$_SESSION['cart_'.(int)$_GET['remove']]--;
header('Location: '.$page);
}
if(isset($_GET['delete'])){
$_SESSION['cart_'.(int)$_GET['delete']]='0';
header('Location: '.$page);
}
It is very simple to implement ajax in opencart. you just need to use it's own prebuilt Cart API and use it in your project.
First need to learn URL for Cart Functionalities
1. http:/ /< project location >/index.php?route=checkout/cart/add (with product_id and quantity as parameters)
2. http:/ /< project location >/index.php?route=checkout/cart/remove (with key as parameter which is cart id)
3. http:/ /< project location >/index.php?route=checkout/cart/edit (quantity[key] and value = 'quantity' as parameters
now you can use these code in Ajax requrest, assuming that your using jquery
var cart = {
'add':function(product_id){
$.get('http:/ /< project location >/index.php?route=checkout/cart/add',
{product_id: product_id},
function(data){}
},
};
Like this you can make add, remove, edit and getcart function and you can add these functions to buttons or page load etc.
for example
<button onclick="cart.add('prod_01');> Add to Cart </button>
Please Note
these routes are basic opencart structure so no need to change it, you just have to use these routes in your javascript code to make ajax call and display the result, it's output is in JSON format, so it is very simple and easy to display a cart.
Good Luck
Related
I am trying to make the code for a shopping cart, which is working. However, when I refresh the page it's adding a product to my cart automatically.
For example, I have 3 products on my website, which are Apple, Banana, Orange.
I click on Apple and it's added to my cart with QTY 1 and the URL is showing
`mydomain.com/my-cart?action=addcart&p_id=FylvGt6Yyb6n%2BzTXcJHwjBawOY%2Fw3QSZxF7rdUJLqhA%3D#`
Now if I refresh the page then it's adding another Apple to my cart (QTY 2). Then if I refresh the page again it adds another Apple (QTY 3) and so on. I don't know why this is happing. It's adding to SESSION.
Would you help me in this?
Below Is my cart code.
$action = isset($_GET['action'])?$_GET['action']:"";
$p_id=$conn->real_escape_string($_GET['p_id']);
$decrypted_p_id = decryptIt($p_id);
//Add to cart
if($action=='addcart') {
//Finding the product by code
$query = "SELECT p_unique_id, p_images,p_name, p_currentprice FROM products WHERE p_id=?";
if ($stmt = $conn->prepare($query)) {
$stmt->bind_param("i", $decrypted_p_id);
$stmt->execute();
$stmt->bind_result($p_unique_id,$p_images, $p_name, $p_currentprice);
$stmt->fetch();
}
$currentQty = $_SESSION['products'][$decrypted_p_id]['qty']+1; //Incrementing the product qty in cart
$_SESSION['products'][$decrypted_p_id] =array(
'qty'=>$currentQty,
'p_unique_id'=>$p_unique_id,
'p_images'=>$p_images,
'p_name'=>$p_name,
'p_currentprice'=>$p_currentprice
);
$product='';
// header("Location:cart.php");
}
Displaying product
<?php if(!empty($_SESSION['products'])):
foreach($_SESSION['products'] as $key=>$product):?>
/*some code here*/
endforeach;?>
<?php endif;?>
Edited code here Suggested by ADyson
if (isset($_POST['submit'])) {
$action=$conn->real_escape_string($_POST['action']);
$decrypted_p_id=$conn->real_escape_string($_POST['p_id']);
// whole code here
i found this code:
$currentQty = $_SESSION['products'][$decrypted_p_id]['qty']+1;
this code always run when u reload the page,
give some condition if you want to add manually
If you simply click refresh on the exact same page then action=addcart etc. is still in the URL. Therefore inevitably it runs that action again when the page loads, and adds the items to the cart again.
An "add" action like that would be better done as a POST request, partly for semantic reasons (it's "sending" data rather than "get"ting it) and partly to avoid annoyances like this. Ideally a GET request should not cause any change of state in the application.
Instead of
Add to cart
you can do something like:
<form action="my-cart" method="POST">
<button type="submit">Add to cart</button>
<input type="hidden" name="action" value="addcart"/>
<input type="hidden" name="p_id" value="<?php echo $p_user_id;?>"/>
</form>
You can use some CSS to make the button appear more like your old hyperlink, if you wish.
Then, in your PHP cart code, simply replace all references to $_GET with $_POST instead, to read the values from the POST request.
This will have the advantage that the variables are not saved into the URL and therefore if someone tries to refresh the URL it will not automatically repeat the same action based on those variables.
You could also look into sending the data to add cart items via AJAX, so that it doesn't require a postback at all and usually results in a smoother user experience - if you look at most shopping websites now, that is generally what they do.
I'm developing an eCommerce site with WordPress+WooCommerce.
I added buttons to certain products in the Short Description field in order to quickly select certain number of products to be added in the cart (this is because I have different offers, for example: "Buy 4 for the price of 3").
I have a script like this in the general jquery file:
<script>
function pack4() { document.getElementById("quantity").value = "4"; }
function pack8() { document.getElementById("quantity").value = "8"; }
</script>
And this is an example of the code I have in some products Short Description:
<span><strong>4x3 Pack:</strong>TOTAL<strong>$1800</strong></span>
<button class="select" onclick="pack4()">Select</button>
Everything works and whenever you click on every button the order quantity adds the corresponding number.
The thing is: Whenever my client (who usually edits products) click on the Text/Visual flap of Short Description, the onclick="pack4()" code disappears. I guess WordPress/WooCommerce have got some jQuery filter that erases this kind of codes. I need it to stop doing that, because the client regularly edits things (and of course they don't know anything about coding). Otherwise, I have to add the code again every time.
I also suspect WP/WC also filters it without needing to click on this Text/Visual flap (but I might be wrong about that).
Anyone knows what to do?
Thanks!
The easiest and accurate way is to create a custom shortcode this way:
if( !function_exists('display_product_button_pack') ) {
function display_product_button_pack( $atts ) {
// Shortcode Attributes
$atts = shortcode_atts(
array(
'pack' => '4', // default pack is 4
),
$atts,
'button_pack'
);
$output = '<button class="select" onclick="pack'.$atts['pack'].'()">Select</button>';
return $output;
}
add_shortcode( 'button_pack', 'display_product_button_pack' );
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
The code is tested and works.
USAGE:
There is an optional pack argument in your shortcode, which default value is 4…
For your Pack 8 for example, you will insert this in the short description product editor:
[button_pack pack="8"]
This will output this html:
<button class="select" onclick="pack8()">Select</button>
For the Pack 4, as default argument value is already 4 you just use this:
[button_pack]
I'm doing an e-commerce site (learning purposes) with KeystoneJS. In the view where I display all the products I want to add a filter for sort the items by price and another one to show the products of only one brand. Two forms are needed but I don't get to submit only one
My products.pug looks like this
.container
form(method='post')
input(type='hidden', name='action', value='products')
button(type='submit').btn.btn-primary Send
And my products.js in routes/views/ looks like this
[...]
// Print a word when submit the form
view.on('post', { action: 'products' }, function(next) {
console.log('POST')
next()
})
// Get all products from db
view.on('init'...)
// Render
view.render('products')
So basically what I want to do is to print POST when I hit the button in the view. Instead of that, I receive a 404 error page. I would really appreciate if you guys can help me
Got it! In /routes/index.js I replaced
app.get('/products', route.views.products);
for
app.all('/products', route.views.products);
I feel dummy but happy.
I am integrating SimpleCart.js (http://simplecartjs.org/) into a small project. I wanted to see if it is possible to actually add the shipping information to the SimpleCart Object.
I get the shipping information from an existing user account, and it contains:
shipId, ship_first, ship_last, ship_street, ship_city, ship_state, ship_zip, ship_phone
I have seen in the documentation that I can extend the SimpleCart.js object (http://simplecartjs.org/documentation/simplecart-extend). So currently I am doing it like this:
In my HTML markup :
<a href="#" onclick="setShipping(<?php echo $address['id'] . ", '" . $address['ship_first'] [...] ?>Set Address</a>
My javascript looks like this:
<script>
function setShipping(shipId, ship_first [...]) {
var shippingInfo = {
shipId: shipId,
ship_first: ship_first,
[...]
};
simpleCart.extend(simpleCart, shippingInfo);
// do some more stuff like updating the checkout button and tax rate
}
</script>
This code works on this page, however when I browse to another page the shipping properties appear to have gotten lost. I basically check on every page if the shipping has been set or not, and if it hasn't, I display the link to set the shipping address.
How would I extend the object "permanently" ?
Simply add your simpleCart extender to actual simpleCart.js file.
I have created a Tasks List in SharePoint. When I try to add a new Task, it opens a form with few visible fields like TaskName, StartDate, DueDate, Description, AssignedTo. When I click on 'ShowMore', then it is showing all the remaining fields like %complete, TaskStatus, Priority, Comments, ExpectedDueDate.
Issue: I want all the fields to be visible from the start without clicking on 'ShowMore', because some people might get confused with this option and may skip filling these fields. Can someone please kindly suggest how to achieve this. Any help is greatly appreciated. Thank you!
Unfortunately there is no such setting that allows to configure fields visibility in tasks form AFIK.
But task form could be customized in order to display all the fields as demonstrated below.
Since it is a SharePoint 2013 environment, the following approach is suggested:
Create rendering template to display all the fields in New & Edit forms
Update Task web part in New & Edit forms pages
Template file
The following example demonstrates how to display all the fields of Task form:
(function () {
function preTaskFormRenderer(renderCtx) {
rlfiShowMore();
}
function registerRenderer()
{
var ctxForm = {};
ctxForm.Templates = {};
ctxForm.OnPreRender = preTaskFormRenderer;
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctxForm);
}
ExecuteOrDelayUntilScriptLoaded(registerRenderer, 'clienttemplates.js');
})();
How to apply changes
Upload the specified script (lets name it TaskForm.js) into SharePoint Site Assets library
Open New Form page in edit mode and go to Tasks web part properties
Specify JS Link property located under Miscellaneous group: ~sitecollection/SiteAssets/TaskForm.js (see pic. 1)
Save changes and repeat steps 2-4 for Edit form
I prefer other methods to the JavaScript workaround to really solve the problem:
1. You can change the list form assigned to the local Task content type, for example via PowerShell:
$web = Get-SPWeb http://YourSharePointSite
$list = $web.Lists["Tasks"]
$ct = $list.ContentTypes[0]
$ct.DisplayFormTemplateName = "ListForm"
$ct.NewFormTemplateName = "ListForm"
$ct.EditFormTemplateName = "ListForm"
$ct.Update()
You can set the list form assigned to the ListFormWebPart via SharePoint Designer
Create your own control template and add the ShowExpanded="true" attribute to the TaskListFieldIterator control
Pass the Expanded=1 in the request query string like NewForm.aspx?Expanded=1
Change the default column order of the local Task content type
All of these have the effect of displaying all the fields without the "Show More" button. You can read more about these methods here:
http://pholpar.wordpress.com/2014/11/01/no-more-show-more-in-tasks-lists/