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:
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:
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:
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:
// 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”:
header("Content-Type: text/xml");
echo '<?xml version="1.0"?>'.
'<root status="ok" code="16" error="none" id="658"/>';
?>
And on the client side:
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.
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).
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:
and
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.
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
well done.
Hi,
Can you give me an example how you would get CDATA back from an xml-file?
Hi, unfortunately, it’s not clear enough what do you mean. Could you please clarify your question?
Never mind, I found it here:
https://forum.dhtmlx.com/viewtopic.php?f=19&t=39294
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.
Hi Krunal, all the details can be found here: https://docs.dhtmlx.com/api__refs__dhtmlxajax.html
Never mind, I found it here:
https://forum.dhtmlx.com/viewtopic.php?f=19&t=39294
is it possible to add inot dhmlx ajax settings something like:
xhrFields: {
withCredentials: true
} to make it able to sende kerberos id?
Hi Seb,
You may try to use the query() method of the dhtmlxAjax:
https://docs.dhtmlx.com/api__dhtmlxajax_query.html
This method will allow you to define the headers for your requests.
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 ?
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); })
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.
I tried both async:true & async:false but in either case I am unable to save the response for later use
The ajax operation is async, so code outside of callback can be called before the value is really fetched
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
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.
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;})
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
What version of dhtmlx are you using for this code. I have dhtmlx461.js & am getting the TypeError
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?
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 )
Tags
Archives