How to save data in the database through ajax?

2

I'm trying to send a javascript form to my webservice through ajax.

The idea is that: the javascript send the complete form, and in the webservice, will be saved in the database through the persist method.

My teacher gave us this code, but I do not understand how it works:

 <script>
        $(document).ready(function($){
            $("#gravar").click(function(event){
                //para a submissao em modo normal
                //event.preventDefault(); se fir submit
                var url="http://localhost:8080/sorte/webresources/entidades.cliente";
                //enviando dados usando POST
                xhr = new XMLHttpRequest();
                xhr.open("GET", url, true); //true = assincrono

                //para metodos diferentes de get
                //xhr.setRequestHeader("Content-type","application/json");

                xhr.onreadystatechange = function(){
                    if(xhr.readyState == 4 && xhr.status == 200){
                        //var json = JSON.parse(xhr.responseText);
                        //para obter a resposta que o web service enviou
                        var saida = xhr.responseText;//não se aplica a metodo 

                        alert(saida);
                    }
                }
                //var data = JSON.stringify({"idCli":"100","nome":"LaraCroft","rg":"100100"});
                  // xhr.send(data);//so recebe parametro se consumir entreada
                  xhr.send();
                });
            });

    </script>
    
asked by anonymous 19.11.2018 / 20:15

1 answer

3

Your teacher mixed JS (JavaScript) pure code with jQuery, a well-known and widely used library for dealing with browser differences, while the professional just thinks about logic.

See that your code runs on the client's browser (the person accessing the site) and only deals with the "look" of your system. The whole part of tinkering with Database is done in another language, which you did not illustrate here. It's like you have 2 layers (like onion) and you just showed us the top layer.

XHR (XMLHttpRequest) is the Javascript object that handles Ajax in the browser. Maybe she's trying to teach you how to use it, but I'll take the liberty of rewriting the code using only jQuery to make everything cleaner. And I'm going to use ES6 (modern version of Javascript), to make everything leaner:

$(() => {
    $("#gravar").click(() => {
        $.ajax(
            method: "GET",
            url: "http://localhost:8080/sorte/webresources/entidades.cliente",
            data: {
            }
        ).done(() => {
            $("#resultado").text("Deu tudo certo!");
        }).fail((err) => {
            $("#resultado").html("<span>Deu alguma coisa errada: " + err + "</span>");
        });
    });
});

In short, what this script does is associate a click on a button, which in your HTML has the "ID" to write to an Ajax call. What the Ajax layer does in essence is to call the URL your teacher showed you.

There must be a server, Tomcat, Apache HTTP, Axis, or depending on the language you use on the server, it will take that URL and be able to know which service it should send the data to. How to do this? It depends exclusively on which language and technologies you are using on the server, since each has n-patterns to do that.

See that in the code, I put date , an empty field. Here, on this date, you must explain to JS where fields are which values you should pass to the webservice. I'll give you a simple example:

data: {
    nomePessoa : $("#nomePessoa").val(),
    idadePessoa : $("#idadePessoa").val()
} 

See that I also used jQuery in the same way that your teacher used it. You could have used pure JS. Only you would have to know which attribute you should use. Each field type (textArea, single input) has a different attribute to pick up the content. Without seeing your HTML you can not know much. Using jQuery makes things a little easier.

If you want me to explain literally what your code does, the only relevant parts of the move are in these two lines:

var data = JSON.stringify({"idCli":"100","nome":"LaraCroft","rg":"100100"});
xhr.send(data);

The second line is very simple. It takes your data (date) and sends it all to the server (for that URL you passed above).

The first line is the trick your teacher wanted you to understand: she takes the data you specified, and transforms it into a text (in English it is a string), that is, it "texts" a Javascript dataset in this case, the package that does this is from JS itself and is called JSON). That is, JSON.stringify takes the data you want to send, and transforms it into text because web communication is done in text - so any service you mount on the server can read the content.

jQuery is smart enough to do this automatically, so you did not see it in the code I made.

Now, within the stringify, which is the cat's leap:

{
 "idCli":"100",
 "nome":"LaraCroft",
 "rg":"100100"
}

Do you see the similarity to the code for date you had done before? It is using a notation JSON (JS Object Notation) notation for JS to know that you are working with data. There were several ways of describing data in JS in the past, a very old story to tell, from which came the JSON that unified everything and became standard.

Notice that it set fixed values to 100 for the idCli field. You should know how your HTML is, know the names of the fields, and in place of 100 you should put the JS code to get this value. You can use jQuery if you like.

Now, keep in mind 2 things:

  • The names of the fields, for example here you used idCli, name and rg should be well known by your web service. Almost sure that if you put a lowercase letter in the wrong place your service goes give Dick because he thinks ID is different from id that is different from Id.
  • Since your service will map that URL to the service itself and how it will map each parameter to each variable within your service, it depends exclusively on the programming language and the technologies you are using in the service, even the protocol "Web Service" being "universal."
  • I've forgotten that to get the values from an input field, the function is .val () and not .text () - that you use to handle HTML more than content.

        
    19.11.2018 / 21:16