OpenCart – Create Ajax Function

Opencart makes really good use of Ajax all throughout the framework installation. There may come a time where you will need to make your own Ajax call because you want to set something up that does “not” come with the basic installation. This tutorial will teach you how to do this so you can say money and do it yourself :).  First, let’s discuss what AJAX is first.

What is Ajax?

Ajax(asynchronous JavaScript and XML), is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data can be retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not required (JSON is often used instead), and the requests do not need to be asynchronous.

Layman Definition: Ajax basically gives you the ability to send HTTP REQUESTS to a server, receive a return and execute a callback without having to change pages or refresh the current web page. It is “seamless”.

ajax-diagram

Jquery and Ajax

Since Opencart already uses Jquery Library then you will make calls to ajax using the Jquery format. Let’s look at one example of how Opencart uses Ajax.  The most common example is the ADD TO CART on the product details page. For version 1.5.6:

$.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>’ + json['error']['option'][i] + ‘</span>’);
}
}

if (json['error']['profile']) {
$(‘select[name="profile_id"]‘).after(‘<span>’ + json['error']['profile'] + ‘</span>’);
}
}

if (json['success']) {
$(‘#notification’).html(‘<div style=”display: none;”>’ + json['success'] + ‘<img src=”catalog/view/theme/default/image/close.png” alt=”” /></div>’);

$(‘.success’).fadeIn(‘slow’);

$(‘#cart-total’).html(json['total']);

$(‘html, body’).animate({ scrollTop: 0 }, ‘slow’);
}
}
 });

Line by line:

  1. $.ajax({ (Open Ajax)
  2. url: ‘index.php?route=checkout/cart/add’, (Url to php function that will receive the Ajax)
  3. 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’), (locations of data to be sent by POST. These are located of course in the HTML by a class name.)
  4. dataType: ‘json’,(Type of data being sent)
  5. Then you will see a SUCCESS procedure that if successful, then do this…..

Writing your own Ajax

First, you must have a reason to want to write your own Ajax but for this example our reasons will be purely generic. Our functions will execute a basic HELLO WORLD. First figure out where you want this to work on your Opencart site and paste this function in a .TPL:

function testAjax(){
$.ajax({
url: ‘URL TO PHP CONTROL (function is called testAjax)’,
type: ‘post’,
data: ‘name=Hello World’,
dataType: ‘json’,
success: function(json) {

if (json['success']) {
alert(json['success']);
}
}
});
}

Now all you need is your PHP Function that will receive the post data and return it back via JSON OBJECT

public function testAjax(){
$json = array();
if(isset($this->request->post['name'])){

$json[success'] = $this->request->post['name'];

}
$this->response->setOutput(json_encode($json));
}

That’s it!  The only thing you need to do now is create a button in your html that executes the javascript function. Let’s do that here:

<a onClick=”testAjax();”>TEST MY AJAX</a>

Looking for quality OpenCart Hosting? Look no further than Arvixe Web Hosting!

Tags: , , , , , , | Posted under OpenCart | RSS 2.0

Author Spotlight

Joe Stenhouse

Joe Stenhouse

I am a web application developer that specializes in PHP, JAVASCRIPT, MYSQL, HTML, and CSS. We manifest exciting potentials within the world wide web through means of innovation.

Leave a Reply

Your email address will not be published. Required fields are marked *


4 − 3 =

You may use these HTML tags and attributes: <a href="" title="" rel=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>