📜 ⬆️ ⬇️

Mohawk / Working with Ajax

In this article I will describe the work with Ajax in Mohawk.
Working with Ajax is implemented through the Ajax class, which is located in the kernel / Ajax.js file.

The Ajax class takes over the basic routine operations:
- create XmlHttpRequest request
- conversion of special characters in the request data
- drawing up and sending a request to the server
- acceptance of the response from the server


For more convenient work, the following classes are also used:
- XML ​​- for lightweight work with XML
- FormsInterface - for working with HTML forms.
')

Form and FormsInterface


Let's create a simple HTML form with which we will work. Let, for example, this will be a feedback form:
< form id ="feedback" method ="post" onsubmit ="return send(this)" >
< fieldset >
< ul >
< li >
< label for ="name" > Name: </ label >
< input id ="name" name ="name" />
</ li >
< li >
< label for ="email" > Email: </ label >
< input id ="email" name ="email" />
</ li >
< li >
< label for ="message" > Message: </ label >
< textarea id ="message" name ="message" cols ="40" rows ="8" ></ textarea >
</ li >
</ ul >
< button type ="submit" > Submit </ button >
</ fieldset >
</ form >


* This source code was highlighted with Source Code Highlighter .


At the onsubmit event, the form will call the send function and pass a reference to itself as an argument. In the function send, we will work. First we need to get the data from the form. The DOM extension FormsInterface provides a convenient method for retrieving data from a form: form. getData (), where form is the form itself. The getData () method will return data from the form as an associative array:
function send(form) {
var data = form.getData();
// data = {'name': 'Alice', 'email': 'alice@example.com', message: 'Hello world!'}

return false ;
}


* This source code was highlighted with Source Code Highlighter .


Ajax and XML


To work with the Ajax class, you need to connect it:
include( 'mohawk.kernel.Ajax' );

* This source code was highlighted with Source Code Highlighter .


In order to submit the form data, we need to create an Ajax request:
var request = new Ajax( 'test.xml' , Ajax.METHOD_POST);

* This source code was highlighted with Source Code Highlighter .


The constructor of the Ajax class takes arguments: the address to which the request will be sent and the HTTP method. If the method is not specified, the request will be sent by the GET method. Through the class, you can send not only the usual GET and POST requests, but also PUT, DELETE, HEAD, OPTIONS. In the latter case, it is possible to emulate requests through POST with sending the corresponding X-Request-Method header. Ie, for example, a PUT request will be sent via POST, but the header will be: X-Request-Method: PUT. This is necessary if for some reason you cannot send requests other than GET and POST (for example, Kerio firewall blocks the HTTP DELETE method).

So, in order to send a request, you need to call the request.send (data) method, which takes the sent data as an associative array as an argument. For example:
request.send({ 'a' : 1, 'b' : 2}); // a=1&b=2


* This source code was highlighted with Source Code Highlighter .


Add an AYAX request to the send function:
function send(form) {
var request = new Ajax( 'test.xml' , Ajax.METHOD_POST);
var data = form.getData();
request.send(data);
return false ;
}


* This source code was highlighted with Source Code Highlighter .


When you call the send () function, these forms will be sent to the server. However, we still need to find out that the server has successfully received this data, and in more complex applications it also receives the response from the server. To do this, we define a handler function that will be called when a response is received from the server. The handler is set via the request.responseHandler property:
function send(form) {
var request = new Ajax( 'test.xml' , Ajax.METHOD_POST);
request.responseHandler = function (request) {
alert( 'Tada!' );
}
var data = form.getData();
request.send(data);
return false ;
}


* This source code was highlighted with Source Code Highlighter .


Create a test.xml file to emulate our server. Suppose the server tells us that everything is ok and displays the message “Done”:
<? xml version ="1.0" encoding ="UTF-8" ? >
< data >
< status > ok </ status >
< message > Done </ message >
</ data >


* This source code was highlighted with Source Code Highlighter .


If we test the form, then after sending, we are given an alert box "Tada!".
Let's complicate our handler. We want to get a response from the server, namely: status and message. The argument to the request.responseHandler function, we pass, refers to the AYAX request: request . After receiving the server's response, the request.data property will appear on the request object, which will contain data from the server. The XML object automatically parses the XML response, and as a result, the request.data will contain the associative array with the server response: {'status': 'ok', 'message': 'Done!'}
function send(form) {
var request = new Ajax( 'test.xml' , Ajax.METHOD_POST);
request.responseHandler = function (request) {
var response = request.data;
alert( 'Status: ' + response.status + ', message: ' + response.message);
}
var data = form.getData();
request.send(data);
return false ;
}


* This source code was highlighted with Source Code Highlighter .


Json


Many developers prefer JSON instead of XML. For example, the server response may be in this format ( test.js ):
{
status: 'ok' ,
message: 'Done!'
}


* This source code was highlighted with Source Code Highlighter .


To accept JSON data, you need to change only two lines:
function send(form) {
// test.xml test.js
var request = new Ajax( 'test.js' , Ajax.METHOD_POST);

// - 'json'
request.type = Ajax.TYPE_JSON;

request.responseHandler = function (request) {
alert( 'Tada!' );
}
var data = form.getData();
request.send(data);
return false ;
}


* This source code was highlighted with Source Code Highlighter .


As you can see from the example, the Ajax class allows you to completely abstract from the format of the transmitted and received data. We can work with XML, and with JSON, without changing the logic of the application.

Debugging Ajax Requests


When developing applications that use Ajax, debugging requests are often required. You need to see what went where and what came from there. Firefox has a wonderful firebug for this purpose, and Opera has a built-in console for web developers. In the beta version of Chrome 2, it seems that it is possible to view Ajax requests. But in IE, as usual, problems arise with debugging.

You can see the requests and responses sent by Ajax from the server using the Mohawk debugging console. The console connects quite simply:
include( 'mohawk.UI.Console' );

var Console = new Mohawk.UI.Console();
Console.regKey();
document .addLoader( function () {
Console.append();
});


* This source code was highlighted with Source Code Highlighter .


An example of console logs:
Ajax query sent to: test.xml
Data:
name:Alice
email:alice@emaxmple.cmo
message:Hello world!
Query: name=Alice&email=alice@emaxmple.cmo&message=Hello world!

Ajax query received from: test.xml
Data:
<?xml version="1.0" encoding="UTF-8"?>
<data>
<status>ok</status>
<message>Done</message>
</data>


View console operation and sample form.
Download Mohawk with examples
You can also read the introduction to Mohawk and about JS-templating

Source: https://habr.com/ru/post/54341/


All Articles