An Ajax request allows to “retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page.” [Ajax (programming) - From Wikipedia]
Every Ajax framework has its own way of simplifying the direct use of the XMLHttpRequest object, and Ext Js has Ext.Ajax.request for coding Ajax requests. There are also other ways to send Ajax requests with Ext Js, but this one is the hand coded one which leaves you the maximum flexibility.
It’s quite straightforward and I’ll explain it with a simple working example. First we need to prepare our params object with the variables to send to the server. If we don’t need any variable we can omit it and omit the corresponding line in the request. One interesting consequence is that a request without parameter will be sent in GET method, while a request with parameter will be sent with the POST method.
With the url parameter we’re telling Ext Js where to fetch the data and according to the same origin policy it should be a url on the same website.
With success: and failure: hooks we can define callbacks, i.e. functions that will get called when the data will be ready. It’s important to stress again that the request is asynchronous, any code after the request will be processed and only later, one of the callback will be executed.
Ext.Ajax.request({
params: {greeting: 'Hello', who: 'Everybody'},
url: '/extjs/ajax1.php',
success: function (resp) {
var data;
data = Ext.decode(resp.responseText);
if (data.success === true) {
Ext.MessageBox.alert('Message', data.msg);
} else {
Ext.MessageBox.alert('Error', 'Some problem occurred');
}
},
failure: function () {
Ext.MessageBox.alert('Error', 'Some problem occurred');
}
});
The corresponding PHP code on the server is the following:
function main() {
if (!isset($_POST['greeting']) || !isset($_POST['who'])) {
$res = array('success' => false, 'msg' => 'Missing parameters');
echo json_encode($res);
return;
}
$res = array('success' => true,
'msg' => $_POST['greeting'] . ' ' . $_POST['who']);
echo json_encode($res);
}
To run this example code, click on the run button, it should show the message ‘Hello Everybody’ composed by the two strings passed as parameter. Of course for such a trivial task there is no need to send an Ajax request, but I wanted to show a simple example of an Ajax request with Ext Js.