DHTMLX Little-Known Features: How to Work with Ajax

Based on frequent questions about working with DHTMLX and Ajax, we decided to explain how it works in detail.

The main function of Ajax is interaction with a server, sending requests and processing of user data in particular. dhtmlxAjax was simplified in the version 4.0.

The general scripts of working with Ajax are the following:

  • data request from the server
  • processing of the server response
  • error handling

We’ll use PHP as a server script, but in general any server script can generate the content.

For data request either GET or POST requests are used. With GET we have the following:

dhx4.ajax.get("server.php?p1=v1&p2=v2", function(){...});

The first param is the address of the server script server.php, there also can be any number of additional parameters p1=v1, p2=v2 (but don’t forget about the limit of GET request). As GET is an asynchronous request, we need the second param – a function that is called after the response is loaded (we’ll talk about it later).

POST request is similar to GET, but here we pass the parameters as a separate argument:

dhx4.ajax.post("server.php", "p1=v1&p2=v2", function(){...});

The examples of work with synchronous requests getSync and postSync you can find in our docs.

So, the data are requested by client. Now let’s see how to process them on the server and create a response for the client side. The most secure way is to pass data by means of using some structure, e.g. json or xml. Why them? These formats are described and they are the same in any environment. We won’t show the business logic operations in our example, just the received result.

We’ll start with json. Let’s suppose that the server returns the following:

<?php
echo '{status: "ok", code: 16, error: "none", id: 658}';
?>

Now let’s get back to the client and process the response got from the server:

dhx4.ajax.get("server.php", function(r){
    // use built-in function to convert string to json
    var t = dhx4.s2j(r.xmlDoc.responseText);
    if (t != null) {
         // response successfuly parsed
    } else {
         // response is not in json format
    }
});

When dealing with xml, don’t forget to make sure that the client got the correct content-type header, it should be “text/xml”:

<?php
header("Content-Type: text/xml");
echo '<?xml version="1.0"?>'.
'<root status="ok" code="16" error="none" id="658"/>';
?>

And on the client side:

dhx4.ajax.get("server.php", function(r){
    var xml = r.xmlDoc.responseXML;
    if (xml != null) {
       // response successfuly parsed
       var root = xml.getElementsByTagName("root")[0];
       var status = root.getAttribute("status");
    } else {
        // response is not in json format
    }
});

Error handling

Sometimes something goes wrong and we have an error during the request processing on the server. It can be connection error, expired session or just a bug in the server code. DHTMLX Ajax provides two events for specifying custom handlers of server errors.

dhx4.attachEvent(“onAjaxError”, function(){ })

The Event takes place each time when the server returns the response with incorrect status (404 – Page not found, 500 – server error, and so on).

dhx4.attachEvent(“onLoadXMLError”, function(){ })

The event occurs only when working with xml and occurs when the returned data are not valid (response can’t be parsed as xml correctly).

REST requests



Although we’ve reviewed only POST and GET requests, dhtmlxAjax supports all REST operations – GET, POST, PUT, DELETE. For two last requests we can use:

dhx4.ajax.put(“some.php, function(){ });

and

dhx4.ajax.delete(“some.php, function(){ })

Syntax and behaviour are the same as in in case of dhx4.ajax.post.

Complex requests



Sometimes all the described above isn’t enough. In this case we can use dhx4.ajax.query method which allows implementing all of the mentioned operations and even more.

dhx4.ajax.query({
    method:”POST”,
    url:”some.php,
    data:”k1=v1&k2=v2”,
    async:true,
    callback:function(){...},
    headers:{
          “MyHeader-Name1”:”value”,
          “MyHeader-Name2”:”value”
    }
})

As we see from the example, this method allows using all types of requests to the server, using sync and async API, pass additional data or specify a function for handling the server response.

Also this method has “headers” param that allows specifying additional Request Headers. This API can be used in quite specific cases, for loading data from third party API and data services.

We tried to cover all the questions about using of DHTMLX Ajax, but if you still have something to ask, feel free to leave your comments below.

Advance your web development with DHTMLX

Gantt chart
Event calendar
Diagram library
30+ other JS components