Webix JavaScript library through the eyes of a beginner. Part 6. Server interaction



I am a beginner front-end developer. Now I am studying and training in a Minsk IT company. Learning the basics of web-ui takes place using the Webix JS library as an example. I want to share my modest experience and save it as a small tutorial on this interesting UI library.

SIXTH PROBLEM


Webix is ​​a JavaScript library in which operations primarily occur on the client side, and only then the result is sent to the server if the data needs to be saved. There are no strict requirements for the backend here. It doesn’t matter with what data is processed on the server, the main thing is that it receives requests of a certain format and gives the answer in the right form. All that is required of the developer is to connect the server and work with simple requests, given the fact that the project does not have complex user settings.

Consider the following tasks:

  • connecting the server side of the application;
  • server request methods;
  • how to track the download result;
  • How to track the result of saving.

The article uses the Table widget , which is described in detail in the documentation.

Sources for working with the article are located here .

The finished application can be found here .

Connecting the server side of the application


Here is an example based on the Table widget. The source structure has now changed the structure of the application. Previously, it was an ordinary index.html file with js files connected to it. Now two folders have been added - the backend, with a simple server script on nodeJS and the app folder, where all the written client code lies. Server operations for each widget are described in separate files. For the Table widget, this is the films.js file.
The code for the Table widget is located in the table.js file of the app folder and rendered in the “Dashboard” tab.
First, run the application on the local server.

Open the command line for the folder with the application and sequentially enter the following commands:
npm install
npm run server
After that, the following entry will appear in the terminal:
Server is running on port 3000 ...
Open localhost : 3000 / app in browser
The specified address / link is opened in the browser.

The server script that the Table widget will access will support all basic crud operations.

To load data into a table, specify the path to the script in its url property.

url: "/samples/server/films"

To send save requests - the path to the script is specified in the save property. The path will be the same as in url, only with the rest prefix. We will talk about rest below.

save:"rest->/samples/server/films"


Query methods determine what we want to do with the resource. By default, Webix uses the GET and POST methods, but we will use the RESTful API and all methods suitable for our data operations: GET, POST, PUT and DELETE.

With the rest prefix that is already set in the save setting, all requests will be sent through the corresponding ready-made proxy . The rest proxy coordinates the request method with the type of operation that we performed on the client. There are several ready-made proxies for certain tasks; if necessary, you can create custom proxies.

We will track requests using the example of the Table widget. To do this, in the browser, go to DevTools-> Network and find information about the desired request.

To load data into a table, useGET method .

We will refresh the page and click on the script request films.

By default, there will be no parameters in this request, since we are dealing with the first data loading into the component.

As a result, the server returns a JSON array with all the data.

Result of a GET request:



The POST method is used to create a new record in the table .

Using the form, add new data to the table.

The request data will be the following data:



When adding a record to the server, the id assigned there must definitely come:

{ "id":"ImurRuK1k59qzy2f" }

This is necessary so as not to lose the connection between the data on the server / client. The same id will now be used on the client.

To change the data in the rows, the PUT method is used .

We select the first row in the table - the data from it will appear in the form. Then we will change them and save. The entire record (data object) will go to the server along with our changes.



The server response should not contain a specific status (an empty object can also be the answer, as will be shown below), but in our case the server will return the following JSON:

{ status: “updated” }

To delete data, use the DELETE method .

Delete the first line by clicking on the cross.

In this case, the entire string will be the transmitted parameters to the server. The main thing in the parameters is the id of the record to be deleted on the server.



The server will return an empty object, since special confirmation of such an operation is not necessary.

Track download result


Consider a situation where we need to calculate how many records have been loaded into a table and display this as a message. To do this, use the ready handler .

The ready handler is called immediately after the first data has arrived in the component and only once. Inside the handler, we place the function webix.message()calling the count method . After calling it, a message will appear in the upper right corner of the screen “Loaded 250 records!”.

const table = {
// code the widget Table
    ready(){
        webix.message({
            text:`Loaded ${this.count()} records!`, 
            type:"success"
        });
    }
}

Data loading moment:



In case when any error occurred during data loading, the onLoadError event will fire :

$$("datatable").attachEvent("onLoadError", function(xhr){
    webix.message("Error!");
});

Tracking Save Results


You can get the server response when saving by operations such as adding, editing and deleting. Consider the example of the Table widget.

For this, the DataProcessor module is used to interact with the server. The API of this module can be used to fine tune data storage. We only need to track the moment of saving - therefore we use one of its events - onAfterSync .

The DataProcessor module is accessed by the setting. webix.dp(id)

The onAfterSync event is raised when the response from the server is received and processed. For this event, display a message through webix.message(). After saving, the message - will appear in the upper right corner “Saved!”.

We delete the first row in the table and look at the result.



Event code in script.js file after webix initialization:

let dp = webix.dp($$("film_list"));
dp.attachEvent('onAfterSync', () => {
    webix.message({
        text:"Saved!",
        type:"success"
    })
});

Errors in this case can be caught with the onAfterSaveError event :

dp.attachEvent("onAfterSaveError", function(id, status, response, details){
    webix.message("Error!");
});

Generalization


Using CRUD operations, we figured out how to interact with the server side of the application. We examined a standard set of query methods and how to catch loading and saving data. The examples discussed in the article are available not only for the Table widget, but also for List. You can try it yourself in the source codes indicated at the very beginning.

The code of the finished application can be found here .

All Articles