DHTMLX Little-Known Features: How to Work with Ajax

| Comments (21)

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.

Comments

  1. Ken Wilson January 18, 2015 at 7:37 pm

    well done.

  2. Real Name February 17, 2015 at 4:35 pm

    Hi,

    Can you give me an example how you would get CDATA back from an xml-file?

  3. Krunal Fijiwala February 20, 2015 at 5:29 pm

    It is not cleared how to use dhtmlx ajax.
    please provide some samples also so get cleared how to use it.
    please provide samples for del, get, getSync, post, postSync, put, query.

  4. Real Name February 24, 2015 at 4:24 pm
  5. Seb Dk August 14, 2017 at 4:50 pm

    is it possible to add inot dhmlx ajax settings something like:
    xhrFields: {
    withCredentials: true
    } to make it able to sende kerberos id?

  6. PH May 16, 2018 at 11:28 pm

    When using dhx4.ajax.query how do you get access to the response? Tried this –
    callback:function(r){response = r.xmlDoc.responseXML;}
    But it didn’t work ?

    • Stanislav (DHTMLX team) May 17, 2018 at 2:13 pm

      There are two way to obtain the response

      – callback
      dhx4.ajax.query({
      url:”some.php”,
      callback:function(xhr){ console.log(xhr.xmlDoc.responseText); }
      });

      – promise
      dhx4.ajax.query({
      url:”some.php”
      }).then(function(text){ console.log(text); })

      • PH May 17, 2018 at 5:07 pm

        Thanks for the response. I am trying to use the callback. I have a variable in javascript called response that is outside of the dhx4.ajax.query block. Within the callback function I set – response = xhr.xmlDoc.responseText
        But the response is null? Inside the callback function console.log prints the server response correctly; so I am getting back the response but need to know how to save it so it can be used later in Javascript. Thanks for your help.

        • PH May 17, 2018 at 5:12 pm

          I tried both async:true & async:false but in either case I am unable to save the response for later use

        • Stanislav (DHTMLX team) May 17, 2018 at 8:03 pm

          The ajax operation is async, so code outside of callback can be called before the value is really fetched

          • PH May 17, 2018 at 9:40 pm

            So how do I go about implementing something like this? Is post Or postSync an option? I need to be able to pass JSON object to the server

          • Stanislav (DHTMLX team) May 18, 2018 at 2:35 pm

            It is better to avoid the sync operations ( browser will deprecate the sync ajax calls in the near future )

            Use async mode, but trigger any result dependent code from the callback. So it will be executed only after ajax call processing.

      • PH May 17, 2018 at 5:21 pm

        When I tried to use promise as shown above I get the following error in Javascript –
        Uncaught TypeError: Cannot read property ‘then’ of undefined. This is what I have –

        dhx4.ajax.query({
        method:”POST”,
        url:”/myUrl”,
        data:JSON.stringify(jsonData),
        headers:{
        “Accept” : “*/*”,
        “Content-Type” : “application/json”
        }
        }).then(function(text){ console.log(“text = ” + text); response = text;})

        • Stanislav (DHTMLX team) May 17, 2018 at 8:07 pm

          Here is the snippet which runs the same code
          it show an error alert, as used url is invalid, still there is no problem with “then” method.

          http://snippet.dhtmlx.com/a472a28a7

          • PH May 17, 2018 at 8:18 pm

            What version of dhtmlx are you using for this code. I have dhtmlx461.js & am getting the TypeError

          • PH May 17, 2018 at 8:21 pm

            I guess “then” is not supported in the version of dhtmlx that I have & won’t be able to easily upgrade. Is there a way to make the callback function work correctly? i.e. get the response & process it outside the ajax.query block?

          • Stanislav (DHTMLX team) May 18, 2018 at 2:34 pm

            Promise works for DHTMLX 5+, in case of DHTMLX 4.x use callbacks ( ajax.query may be not supported at all by some older 4.x builds )

Leave a Reply