what happens when add to cart button clicks in opencart - opencart

Can somebody please tell me, which function will execute when we click on 'Add to Cart' button in store front? which code or method will execute when Add to Cart button clicked? I observed that there some calculations takes place.
In view/theme/*/template/product/product.tpl
<input type="hidden" name="product_id" size="2" value="<?php echo $product_id; ?>" />
<input type="button" value="<?php echo $button_cart; ?>" id="button-cart" class="button" />
in javascript
<script type="text/javascript"><!--
$('#button-cart').bind('click', function() {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('.product-info input[type=\'text\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea'),
dataType: 'json',
success: function(json) {
$('.success, .warning, .attention, information, .error').remove();
if (json['error']) {
if (json['error']['option']) {
for (i in json['error']['option']) {
$('#option-' + i).after('<span class="error">' + json['error']['option'][i] + '</span>');
}
}
}
alert(json['success']);
if (json['success']) {
$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/palioxis/image/close.png" alt="" class="close" /></div>');
$('.success').fadeIn('slow');
$('#cart-total').html(json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
}
}
});
});
//--></script>
Can somebody brief what happens here?

The jQuery code looks for a button with the id, 'button-cart'.
Once it is clicked, it runs the Ajax code below. The data will be transmitted to route=checkout/cart/add url.
The file calls your /controller/checkout/cart.php file and looks for the add() function. The data pass to the add() function will be from 'data'.
Then if the data are passed correctly, the jQuery code would prompt an alert message from json['success'] and load a DIV layer.
Otherwise, if the data were not passed correctly, it would give an error message on the page.
Let me know if this helps you understand it. I use Opencart.

Related

How do I get my email sign up form to work while hosting static webpage on AWS?

Like the title states - I'm trying to get my email collection form on my static webpage to work while hosting on AWS.
The HTML is:
<form id="email-submit" method="post">
<div class="container-fluid">
<div class="row justify-content-end">
<div class="col-lg-6">
<div class="call-action-content text-center">
<h2 class="call-title">Want early access?</h2>
<p class="text">Enter your email below to gain priority access and to receive updates on the official release.</p>
<div class="call-newsletter">
<i class="lni-envelope"></i>
<input type="email" id="email-input" placeholder="Email address">
<button type="submit" onClick="submitToAPI2(event)">Stay informed</button>
And the jquery/ajax I found on Amazon's documentation I'm using is:
function submitToAPI2(e) {
e.preventDefault();
var URL = "the api gateway";
var reeamil = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
if (!reeamil.test($("#email-input").val())) {
alert ("Please enter a valid email address");
return;
}
var email = $("#email-input").val();
var data = {
email : email
};
$.ajax({
type: "POST",
url : "api gateway",
dataType: "json",
crossDomain: "true",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
success: function () {
// clear form and show a success message
alert("Successfull");
document.getElementsById("email-submit").reset();
location.reload();
},
error: function () {
// show an error message
alert("Error. Please try again");
}});
}
Any ideas on why it's not working?

Accessing a widgets value in django template

I need to do an ajax call in django depending on the values set on two date fields and a select dropdown. In order to do that I have to pass those values into javascript function which will be called when a button is click. I have set the form dates fields as Date type and select as Choice field. How can I pass the current values of these to the javascript function?
form.html (template):
<div class="form-group">
<label class="control-label">* Start Date:</label><br>
{{ form.date1 }}
</div>
<div class="form-group">
<label class="control-label">* End Date:</label><br>
{{ form.date2 }}
</div><br><br>
<div class="form-group">
Category: {{ form.category }}
</div>
<button type="button" class="btn btn-xs btn-warning"
onclick="javascript:check_availability({{ XXX }}, '{% url "find_available" %}');">
Check Now
</button>
Javascript:
function check_availability(date1, date2, category, url) {
$.ajax({
type: 'GET',
url: url,
data: {date1: date1, date2: date2, category: category},
dataType: 'json',
success: available_now,
error: function() {
alert('Unable to find available items')
}
});
}
fucntion available_now () {...}
In form.py (view)
category = forms.ChoiceField(choices=(...))
date1 = forms.DateField(widget=forms.DateInput())
date2 = forms.DateField(widget=forms.DateInput())
How could I pass those three values set in the widgets in place of XXX for the above function call? I need to specifically get the selected value of the dropdown.
This isn't in any way a question about Django, but about Javascript. Since you are using jQuery for your Ajax function, you should use it to get the value of the fields. Also note, you should avoid setting onclick handlers directly in the HTML; you should do that in your jQuery script as well.
<button type="button" id='find-available' class="btn btn-xs btn-warning" data-url='{% url "find_available" %}');">
Check Now
</button>
...
$('form').on('click', '#find-available', function() {
$this = $(this);
$.ajax({
type: 'GET',
url: $this.data('url'),
data: $this.parent().serialize(),
dataType: 'json',
success: available_now,
error: function() {
alert('Unable to find available items')
}
});
});

Does Making an AJAX call make a DJANGO form Invalid?

I make an ajax call to my server using the change event on a select widget. Does this cause the Django Form to be invalid? Here is an example of the code.
JAVASCRIPT
<form class="form-horizontal" action="{% url 'accountSelections' %}" method="post">
{% csrf_token %}
<div class="form-group">
<div class="row">
<div class="col-md-4">
{{ account_selection_form|crispy }}
<input class="btn btn-primary" id="button" type="Submit" value="Next >>">
</div>
<div class="col-md-4">
</div>
<div class="col-md-4">
<div id="grid"></div>
</div>
</div>
</div>
</form>`
$( document ).ready(function() {
$("#id_excludeClassification").SumoSelect();
var token = $('input[name="csrfmiddlewaretoken"]').prop('value');
$( "#id_acctFilterName" ).change(function() {
var data = "";
$.ajax({
type:"GET",
url : "../filter",
data : "id="+$(this).val(),
csrfmiddlewaretoken: token,
success : function(response) {
$("#grid").kendoGrid({
data: response,
height: 550,
groupable: true,
sortable: true,
columns: [
{
field: "acctCd",
title: "Code"
}, {
field: "shortName",
title: "Account Name"
}]
});
var grid = $("#grid").data("kendoGrid");
dataSource = new kendo.data.DataSource({
data: response
});
grid.dataSource = dataSource;
dataSource.read();
grid.refresh();
data = response;
return response;
},
error: function() {
alert('Error occured');
}
});
});
});
Does a form submit after cause this to make the form invalid?
My understanding is that you can submit multiple times with the same CSRF token, so it shouldn't be a problem.
you put your csrfmiddlewaretoken variable out data object that you send to your server then it can't work.
Here is what you have to do :
data : {
id : $(this).val(),
csrfmiddlewaretoken: token,
}

updating template with response in Ember after create/update action

I am working on a simple CRUD app using ember js. I have a template with a input form which sends data to the server and server responds with success response.
input form data: "user": {"id": 1, "name": "John"};
server response: {"message":"Created successfully", "nextId": 2}.
I want to display the success message on the same template(one with the input form). Because template refers to the user model and user model does not have a message attribute. How can it be done? Please help.
Here is my code:
var Manager = Ember.Application.create();
Manager.Router.map(function() {
this.resource('users');
this.resource('user', {path: '/users/:user_id'});
this.resource('home', {path: '/'});
});
Manager.UserRoute = Ember.Route.extend({
model: function(params) {
return jQuery.getJSON("http://localhost:8085/users/"+ params.user_id);
},
actions :{
insert : function(){
var user = this.modelFor("User");
$.ajax({
url: "http://localhost:8085/Users",
data: JSON.stringify(user),
type: "POST",
contentType: "application/json",
})
.done(function(data){
//set data.message to display on UI
})
}
}
});
and my template looks like this:
<script type="text/x-handlebars" data-template-name="user">
<form class="form-horizontal" role="form" {{action "insert" on="submit"}}>
<div class="form-group">
<label for="userId" class="control-label col-xs-2">User Id</label>
<div class="col-xs-4 input-group">
{{input type="number" value=_id class="form-control" id="userId" placeholder="Identity"}}
</div>
</div>
<div class="form-group">
<label for="name" class="control-label col-xs-2">Name</label>
<div class="col-xs-4 input-group">
{{input type="text" value=name class="form-control" id="name" placeholder="Name"}}
</div>
</div>
{{#if message}}
<div class="alert alert-success input-group" role="alert">{{message}}</div>
{{/if}}
<div class="form-group button-center">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
</script>
Set the message property on your controller to the response that comes back.
actions :{
insert : function(){
var user = this.modelFor("User");
var self = this;
$.ajax({
url: "http://localhost:8085/Users",
data: JSON.stringify(user),
type: "POST",
contentType: "application/json",
})
.done(function(data){
//set data.message to display on UI
self.controllerFor('user').set('message', data.message);
})
}
}

How To Add Add To Shopcart Button In Opencart Product Description

I am trying to insert a shop cart button at the bottom of the product description in Opencart verson 1.5.4 and am using the default theme.
I looked at the source code for a particular product and copied this information from the source code into the bottom of the product description.
<div class="cart">
<div>Qty: <input type="text" name="quantity" size="2" value="1" />
<input type="hidden" name="product_id" size="2" value="85" />
<input type="button" value="Add to Cart" id="button-cart" class="button" />
</div>
<div><span> - OR - </span></div>
<div><a onclick="addToWishList('85');">Add to Wish List</a><br />
<a onclick="addToCompare('85');">Add to Compare</a></div>
</div>
When I click on the add to shop cart button, nothing happens.
But when I click on the add to wish list and compare , the product is added to the respective lists.
What am I missing?
Should I be using a different code?
Can anyone help me solve this?
Chang you add to shopping cart button , with this
<a onclick="addToCart('<?php echo $product['product_id']; ?>');" class="button"><?php echo $button_cart; ?></a>.
Hope it will works for you.
As far as I know, the Add to Cart code button uses an ID that is linked within a DIV. So jQuery is not lookning for #button-cart - it is looking for, example cart. addform #button-cart and also your missing some variables that need to be nested too.. Update your post with the full version of the product.tpl please too
This is the code you need to be using for moving the Add To Cart Button:
<div class="cart">
<div><?php echo $text_qty; ?>
<input type="text" name="quantity" size="2" value="<?php echo $minimum; ?>" />
<input type="hidden" name="product_id" size="2" value="<?php echo $product_id; ?>" />
<input type="button" value="<?php echo $button_cart; ?>" id="button-cart" class="button" />
<span> <?php echo $text_or; ?> </span>
<span class="links"><a onclick="addToWishList('<?php echo $product_id; ?>');"><?php echo $button_wishlist; ?></a><br />
<a onclick="addToCompare('<?php echo $product_id; ?>');"><?php echo $button_compare; ?></a></span>
</div>
<?php if ($minimum > 1) { ?>
<div class="minimum"><?php echo $text_minimum; ?></div>
<?php } ?>
</div>
But make sure the .product-info and #cart ID and Class child elements are supported within your new DIV move. Why? Look at this jQuery, it depends on them to find the values - having said this - you could change it too.
$('#button-cart').bind('click', function() {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('.product-info input[type=\'text\'], .product-info input[type=\'hidden\'], .product-info input[type=\'radio\']:checked, .product-info input[type=\'checkbox\']:checked, .product-info select, .product-info textarea'),
dataType: 'json',
success: function(json) {
$('.success, .warning, .attention, information, .error').remove();
if (json['error']) {
if (json['error']['option']) {
for (i in json['error']['option']) {
$('#option-' + i).after('<span class="error">' + json['error']['option'][i] + '</span>');
}
}
}
if (json['success']) {
$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('.success').fadeIn('slow');
$('#cart-total').html(json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
}
}
});
});
And updated version according to your needs would be:
/*
Notice I have changed the DIV to assign div#cart
So it looks for <div id="cart">
But make sure options are available for the error response
and validation
*/
$('#button-cart').bind('click', function() {
$.ajax({
url: 'index.php?route=checkout/cart/add',
type: 'post',
data: $('div#cart input[type=\'text\'], div#cart input[type=\'hidden\'], div#cart input[type=\'radio\']:checked, div#cart input[type=\'checkbox\']:checked, div#cart select, div#cart textarea'),
dataType: 'json',
success: function(json) {
$('.success, .warning, .attention, information, .error').remove();
if (json['error']) {
if (json['error']['option']) {
for (i in json['error']['option']) {
$('#option-' + i).after('<span class="error">' + json['error']['option'][i] + '</span>');
}
}
}
if (json['success']) {
$('#notification').html('<div class="success" style="display: none;">' + json['success'] + '<img src="catalog/view/theme/default/image/close.png" alt="" class="close" /></div>');
$('.success').fadeIn('slow');
$('#cart-total').html(json['total']);
$('html, body').animate({ scrollTop: 0 }, 'slow');
}
}
});
});
UPDATE
Do you mean "move" the add to cart button? or simply copy the exesting one so there's two #button-cart in your page?
If the first, the solution from #TheBlackBenzKid should work as you expected.
But if you want to copy the existing button, you should modify the selector so it use class (.button-cart). I hope this help.
Sorry for the late reply. Based on your answer:
I would like to copy the existing one so that there are two buttons in the page
What I mean in modify the selector so it use class (.button-cart) is you should change your ajax trigger to match 2 selector (because now you have 2 'trigger', the top "Add to cart" and at the bottom that you copy to).
First modify your add-to-cart to <input type="button" value="Add to Cart" id="" class="button-cart button" />
see, we don't use id="button-cart" anymore, instead, we use button-cart as our class attribut (class="button-cart button"). By using class, we can declare another element with same class (i.e your 'add-to-cart' button at the bottom of your product description).
Then modify your Ajax script. The original ajax script is:
$('#button-cart').bind('click', function() {
$.ajax({
// another code
});
Change to:
$('.button-cart').bind('click', function() {
$.ajax({
// another code
});
id use # and class use.. I hope this help you.