Sending AJAX requests

PHPR leverages the jQuery library to provide a JavaScript engine used for communicating with PHPR using Asynchronous JavaScript, also known as AJAX. There are many ways to use it, but the most basic implementation is to use the chaining method, so we will use this in our examples.

Basic usage

The object used for sending AJAX postbacks is called $.phpr.post(). The basic usage looks like this:

$.phpr.post().action('user:on_signin')
	.data('username', 'phproad')
	.data('password', 'food')
	.send();

This example will submit a request to the action() handler called user:on_signin along with the username and password data() values. The request is sent to the server by calling the send() function.

Use with form element

A more practical way would be to call the request from a HTML element, this will automatically pass the form data along with the request

<?= form_open() ?>
	<input name="username" value="phproad" />
	<input name="password" value="food" />
	<button onclick="$(this).phpr().post('user:on_signin').send()">Submit</button>
<?= form close() ?>

Notice the difference when calling against a HTML element, you must use $(element).phpr().post() instead. You can also call against any HTML element, for example a button, the closest form element will be targeted.

The post() function can take the action handler as the first parameter, this saves us from calling action().

Processing the response

To capture the response from the server, add the done() function to the chain before sending the request.

$('#form').phpr().post('user:on_signin')
	.done(function(response){
		alert('The server said ' + response.html);
	})
	.send()