For this particular article we will base it on the information provided on the following articles, so make sure you have finished reading and following the examples on this articles before proceeding:



In this article we will change the Javascript Tabs for widgetA and widgetB to include an AJAX call to a third widget. This 3rd widget will be our backend widget or engine that will manage the data in the back. This backend widget would be known as the controller if we were talking about an MVC model of programming. So lets change both widgets to the following:


- widgetA -

 

<script defer>
	var countA = 0;
	$('#buttonA').on('click', function() {
		++countA;
		$.ajax({
			method: "POST",
		  	url: "/api/data/html/get/data_widgets/widget_name?name=wonderWidget",
			data: { wonderAction: "eat", wonderCount: countA }
		}).done(function(data) {
		  	$('#widgetB').html(JSON.parse(data));
		});
	});
</script>

 


- widgetB -

 

<script defer>
	var countB = 0;
	$('#buttonB').on('click', function() {
		++countB;
		$.ajax({
			method: "POST",
		  	url: "/api/data/html/get/data_widgets/widget_name?name=wonderWidget",
			data: { wonderAction: "drink", wonderCount: countB }
		}).done(function(data) {
		  	$('#widgetA').html(JSON.parse(data));
		});
	});
</script>

 


With this changes, we will create the controller widget called wonderWidget with the following code in the HTML Tab:


- wonderWidget -

 

<?php
$action = $_POST['wonderAction'];
$actionCounter = $_POST['wonderCount'];

if ($action == 'eat') {
	if ($actionCounter < 3) {
		$answer = 'Go for 3 Cakes!';
	}
	else if ($actionCounter < 5) {
		$answer = 'Almost 5 Cakes and still going!';
	}
	else if ($actionCounter < 9) {
		$answer = 'You are definitely hungry';
	} else {
		$answer = 'Yum Yum Cake!';
	}
} 
else if ($action == 'drink') {
	if ($actionCounter < 2) {
		$answer = 'Go for 2 Sodas';
	}
	else if ($actionCounter < 4) {
		$answer = 'It appears you need 4 Sodas to be happy';
	}
	else if ($actionCounter < 7) {
		$answer = 'You are definitely thirsty';
	} else {
		$answer = 'Thirst quencher Maximus!';
	}
}

echo json_encode($answer);
?>

 


Save it and since the wonderWidget is a backend only widget, it does not need to be added to the homepage since widgetA and widgetB will simply call it for information. So lets try this out in out homepage.


The result should be similar to this: