OpenCart – Using the json Object with Ajax

This is a simple tutorial that will show you how to set up a java script function that uses Ajax to contact a PHP CONTROL file, thus returning json data to echo the results on a TPL file (HTML). All throughout the Opencart framework this is happening and sometimes you will have need to write your own extension. In doing so, you will come across the need to use AJAX.

For this example we are going to do a simple HELLO WORLD echo. First, you need to write your javascript (with AJAX).  Since Opencart uses jQuery we will be using jquery style javascript. Jquery is not a scripting language. Rather, it’s a javascript library that makes great use of Javascript to produce rich applications.

First, let’s make a simple button that when clicked will execute a javascript function. We can do that a number of ways but for this example we will use the onClick.

<a onClick=”helloworld();” title=”Hello World Test”>Click Me</a>

Now we need the javascript function helloworld.


function helloworld(){



Now for the Ajax:


function helloworld(){

type: ‘POST’,
url: ‘index.php?route=common/header/helloworld’,
dataType: ‘json’,
beforeSend: function() {
$(‘#save’).after(‘<span>&nbsp;<img src=”view/image/loading.gif” alt=”” /></span>’);
complete: function() {
success: function(json) {

if (json[‘error’]) {
if (json[‘success’]) {
alert( json[‘success’]);




This line  url: ‘index.php?route=common/header/helloworld’, defines our control function as helloworld. That function will be created within the control file common/header.php

For this example we will be sending no real HTTP POST DATA to the function, only a basic connection with a successful return. Now we need to write the control function.

Open up the file: catalog/controller/common/header.php and paste this function:

public function helloworld{}{

$json = array();

$json[‘success’] = “HELLO WORLD”;



After uploading both of these files you will see that when you click on the button CLICK ME, you will see an alert that say’s HELLO WORLD. You have successfully created a json object with ajax and returned the results to the HTML. You will come to realize the power of this as you develop more procedures within the control.

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

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

Author Spotlight

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 *