Learning Ext JS 3

Ajax object, GET and POST requests Más videos

Descripción del tema

The communication with the server is the most important part in web applications. Sending and receiving information without having the page reload each time is very easy using Ajax, in this tutorial we are going to learn how to create GET and POST requests using the Ext JS Framework.

Resources

For this tutorial you need to download the resources, unzip them and copy the files to the Web server we have previously installed, inside of the folder course we will create a folder called "ajax", inside of this folder we have to copy the files we downloaded from the resources (ajax.html, ajax.js, ajax.php).

Namespace

The first thing we need to do is "package" the code we're going to write and assign a namespace, by doing this we're avoiding future issues.
//the namespace for this tutorial
Ext.ns('com.quizzpot.tutorial');

com.quizzpot.tutorial.Ajax = {
	init: function(){
		//the code goes here
	}
}

//when the DOM is ready to be used we call the function "init"
Ext.onReady(com.quizzpot.tutorial.Ajax.init,com.quizzpot.tutorial.Ajax);

Create the events

The next step in this tutorial is to create a "listener" for the event "click" in the buttons that are found in the HTML document, inside of this listener we will make the Ajax calls.
//when the user click on the button "json"…
Ext.fly('json').on('click',function(){
	//we will make a request through Ajax to the server
},this);

//do the same for the other two buttons…
Ext.fly('xml').on('click',function(){
			
},this);
	
//we have in the HTML document	
Ext.fly('html').on('click',function(){
		
},this);

Ajax

When the user clicks on the button "json" we're going to do the following:
Ext.Ajax.request({ //making the request
	url: 'ajax.php', //the URL to which to send the request
	method:'GET', //the method HTTP to use for the request
	params:{format:'json'},//an object containing properties which are used as parameters to the request
	success: this.log, //if the request succeeded, call the function “log”
	failure: this.fail, //if the request failed, call the function “fail”
	scope:this //the scope in which to execute the callbacks
});
As you can see the previous code, to make a request via Ajax we use the component "Ext.Ajax", we cannot create instances from this object because is a singleton, that's why we can use it without creating instances, we only need to call the method "request" and pass an object with the configurations we need. In the property "url" we specified where we're going to send the request, in this case "ajax.php" but you can something else depending on your necessities, just remember that you should never set parameters in the url (ex: ajax.php?param=hola&id=2&module=/index), I have seen many developers do this, but this is not the correct way to send parameters to the server, because we have a property that's in charge of doing that. The property "params" is the one responsible to send all the parameters we need, we can define them like an object ({name: 'value', param2:2}) using a String (name=value¶m2=2) or we can assign a function that returns the parameters we need, this is very helpful when we have dynamic parameters that are defined with conditions or rules. In the property "method" we specify the HTTP method the request is going to use (POST, GET), if we don't specify one by default the request is sent as GET if we haven't specified parameters (using the property "params") and POST if we have specified parameters. It's important to remember that the property "success" (inside of the configuration object) receives a reference to the function "log" which we haven't written yet, this function will be executed after the server responds successfully, this means it can be a while before we now the server's responds it depends on the load it has; the same thing applies for the property "failure" because it will execute the specified function when an error happened in the server or the communication ((404 not found, 403 forbidden, 500 server error, etc…). Let's define the requests for the other buttons we have left:
//the same thing for the other buttons...
Ext.fly('xml').on('click',function(){
	Ext.Ajax.request({
		url: 'ajax.php',
		params:{format:'xml'}, //in XML format
		success: this.log,
		failure: this.fail,
		scope:this
	});
},this);
	
//that we have in the HTML document
Ext.fly('html').on('click',function(){
	Ext.Ajax.request({
		url: 'ajax.php',
		success: this.log,
		failure: this.fail
	});
},this);
If you have noticed, the configuration in these requests are not the same, they've slightly changed to show the flexibility of the component.

The function success

We need to code the function that is going to be executed when the server's response is successful, in this case we will write the function "log", which will be a method of the object "com.quizzpot.tutorial.Ajax".
, //<---don't forget to write this comma to separate the methods
	
/***************************************
 *	If the request is successful …
 ***************************************/
log: function(response,options){//receives the response and the object configuration
	var el = Ext.get('response'); // gets the LOG
	var text = response.responseText; //removes the...
	text = text.replace(/</g,'&lt;'); // < and...
	text = text.replace(/>/g,'&gt;'); // >
	el.select('p.newest').removeClass('newest'); // removes the last update
	Ext.DomHelper.append(el,'<p class="newest">'+text+'</p>'); //updates the log
	el.scrollTo('top',el.dom.scrollHeight); //positions the scroller to the back
	el.select('p.newest').highlight('00ff66',{duration:0.5}); //highlights the last message
}
The most important part of the previous code is the function that receives two parameters, the first parameter is the server's response: the object XMLHttpRequest and the second parameters is the configuration object, the rest of the code is not important to explain because it must be replaced by the functionality you want to have, just don't forget that this is the place where you have to deal with the information returned by the server.

The function failure

If an error happens we must know how to handle it, the following code is triggered when an error has happened in the server or the communication:
, //<--- comma that separates the methods
	
/***************************************
 *	If the request fails, log the error
 ***************************************/
fail: function(response,options){
	var el = Ext.get('response');
	el.select('p.newest').removeClass('newest');
	Ext.DomHelper.append(el,'<p class="newest"><strong>Error Status '+response.status+' '+response.statusText+'</strong>: Opsss, there is something wrong! please try again</p>');
	el.scrollTo('top',el.dom.scrollHeight);
	el.select('p.newest').highlight('ff1111',{duration:0.5});
}
In the previous code we only notify the user that an error has happened, nothing complicated but you can change this part and adjust the code to your needs for your application.

The server

This course is about Ext JS, that's why I'm not going to explain with details the code I used in the server, it is just an example that is not very useful in the real world, but I'll tell you what it does.
<?php 
	
	if(rand(1,4) == 1){
		if(rand(1,2)==1)
			header("HTTP/1.0 404 Not Found"); 
		else
			header("HTTP/1.0 403 Forbidden"); 
		exit;
	}
	
	$type = $_SERVER['REQUEST_METHOD'];
	$msg = new Message("This is a ".$type." request!",true);
	
	$format = $type=='GET'? $_GET['format']:$_POST['format']; 
	
	switch($format){
		case 'xml':
			header("Content-Type: text/xml"); 
			echo $msg->toXML();
			break;
		case 'json':
			header("Content-Type: text/plain"); 
			echo $msg->toJSON();
			break;
		default:
			header("Content-Type: text/html"); 
			echo $msg->toHTML();
	}
	
	class Message{
		protected  $msg,$success;
		
		public function __construct($msg,$success) {
			$this->msg = $msg;
			$this->success = $success;
		}
	
		public function toXML(){
			return "<response><success>".$this->success."</success><msg>".$this->msg."</msg></response>";
		}
		
		public function toJSON(){
			return "{success:".$this->success.",msg:'".$this->msg."'}";
		}
		
		public function toHTML(){
			return '<p>'.$this->msg.'</p>';
		}
	}
?>
First it randomly sends errors, it can be either a 404 or 403, I have created a class "Message" which sets a message and a flag in the constructor, this class has three methods that return the message in different formats which are invoked and print in the browser through a switch block.

Conclusions

Using Ajax in our applications is very important, Ext JS has changed the way how we develop our applications or systems, this component is fundamental in the Framework and it is very important to know how to use it properly. I recommend you to check the API and make more examples with this component. As always if you have any questions or suggestions you can leave a comment or join the Quizzpot forum and ask your questions there for the benefit of others. Also, don't forget to follow our updates in Twitter.

Te gustaría recibir más tutoriales como este en tu correo?

Este tutorial pertenece al curso Learning Ext JS 3, te recomiendo revises el resto de los tutoriales ya que están en secuencia de menor a mayor complejidad.

Si deseas recibir más tutoriales como este en tu correo te recomiendo registrarte al curso, si ya eres miembro solo identifícate y registrate al curso, si no eres miembro te puedes registrar gratuitamente!

Si no gustas registrarte en este momento no es necesario! Aún así puedes recibir los nuevos tutoriales en tu correo! Jamás te enviaremos Spam y puedes cancelar tu suscripción en cualquier momento.

¿Olvidaste tu contraseña?

4Comentarios

Instructor del curso

Crysfel3

Autor: Crysfel Villa

Software engineer with more than 7 years of experience in web development.

Descarga Código Fuente Ver Demostración

Regístrate a este curso

Este tutorial pertenece al curso Learning Ext JS 3, revisa todos los tutoriales que tenemos en este mismo curso ya que están en secuencia y van de lo más sencillo a lo más complicado.

Tendrás acceso a descargar los videos, códigos y material adicional.

Podrás resolver los ejercicios incluidos en el curso así como los Quizzes.

Llevarás un registro de tu avance.