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.

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”;
}

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

}

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.