Mohawk / Work with Ajax

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

    The Ajax class takes on the basic routine operations:
    - creating an XmlHttpRequest request
    - converting special characters in the request data
    - composing and sending a request to the server
    - receiving a response from the server


    For more convenient work, the following classes are also used:
    - XML ​​- for easier 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 be a feedback form:

      

        

            

    •         
              
            

    •       

    •         
              
            

    •       

    •         
              
            

    •     

        
      



    * This source code was highlighted with Source Code Highlighter.


    On the onsubmit event , the form will call the send function and pass the reference to itself as an argument. We will work in the send function . 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 us 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 must connect it:
    include('mohawk.kernel.Ajax');

    * This source code was highlighted with Source Code Highlighter.


    In order to send 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 where 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. That is, 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 it is not possible to send requests other than GET and POST (for example, the Kerio firewall blocks the HTTP DELETE method).

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


    * This source code was highlighted with Source Code Highlighter.


    Add the ajax 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 the send () function is called, the form data will be sent to the server. However, we still need to find out that the server successfully received this data, and in more complex applications we also need to accept 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 through 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 went ok and displays the message Done:


      ok
      Done


    * This source code was highlighted with Source Code Highlighter.


    If we test the form, then after sending, we are issued an alert box “Tada!”.
    Let's complicate our handler. We want to get a server response, namely: status and message. In the request.responseHandler function that we set, the argument is passed a link to the ajax request: request . After receiving the server response, the request object will have the request.data property, which will contain data from the server. The XML object automatically parse the XML response, and as a result, in request.data there will be an 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 over XML. For example, the server response may be in the following 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 JSON without changing the logic of the application.

    Debugging Ajax requests


    When developing applications using Ajax, you often need to debug queries. You need to see what went where and what came from there. Firefox has a wonderful firewall for these purposes, and Opera has a built-in console for web developers. The beta version of Chrome 2 seems to be able 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 debug console. The console is connected 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.


    EXAMPLE console log: View operation example of the shape and the console Download Mohawk examples can also read the introduction of Mohawk and about JS-standardization
    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:


    ok
    Done






    Also popular now: