How to save data to database through ajax?

Asked

Viewed 530 times

3

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

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

My teacher gave us this code, but I don’t 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>
  • 1

    In my opinion, this code does not make sense, because since it is using jQuery, it could very well use $.get or $.ajax to make the request instead of XMLHttpRequest. I recommend that you read the documentation of jQuery and redo this code, as it is much simpler than that.

1 answer

3


His teacher mixed code in pure JS (Javascript) with jQuery, a famous and widely used library to deal with differences between browsers, while the professional only thinks of logic.

Note that your code runs in the client’s browser (the person accessing the site) and only handles the "look" of your system. The whole part of dealing with databases is done in another language, which you have not illustrated us here. It’s like you have two 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 just jQuery to clean it up. And I’m going to use ES6 (modern version of Javascript), to dry everything up:

$(() => {
    $("#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 summary, what this script does is associate a click on a button, which in its HTML has the "ID" to record, to an Ajax call. What the Ajax layer does in essence, is to call up the URL that your teacher showed you.

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

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

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

Note that I also used jQuery, the same way your teacher used it. You could have used pure JS. Only you’d have to know which attribute you should use. Each field type (textarea, simple input) has a different attribute to pick up the content. Without seeing your HTML you can’t 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 it are on 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 (to that URL you passed above).

The first line is the trick your teacher wanted you to understand: she takes the data you specified, and turns it into text (which in English is string), that is, it "textifies" a Javascript dataset (in this case, the package that does this is from JS itself and is called JSON). That is to say, JSON.stringify takes the data you want to send, and turns it into text pq the 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 didn’t see it in the code I made.

Now, inside the stringify, that gets the cat jump:

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

See the resemblance to the code for date What had you done before? It’s using a JSON (JS Object Notation) notation to let JS know you’re working with data. There were several ways to describe data in JS in the past, too old a story to tell, hence the JSON that unified everything and became standard.

Note that she has set values as 100 for the field idCli. You should know how your HTML is, know the names of the fields, and in place of 100 vc you should put the JS code to get this value. You can use jQuery if you want.

Now, keep in mind two things:

  1. The field names, for example, here you used idCli, name and ID must be well known by their web service. Almost sure if you put a lowercase letter in the wrong place your service will give dick because it thinks ID is different from id that is different from Id.
  2. How your service will map that above URL to the service itself and how it will map each parameter to each variable within your service depends solely on the programming language and the technologies you are using in the service, even the protocol "Web Service" being "universal".

I forgot that to get the values of an input field, the function is . val() and not . text() - this one you use to handle more HTML than the content of things.

  • Show, very good explanation. + 1 :D

  • Man, your answer was extremely fantastic, it cleared up a lot of things I didn’t understand. Forgive me for not showing the html and the backend, I will do this through these two prints: html of the form: https://ibb.co/i9r5uq method in the java you receive: https://ibb.co/hfZGHA In the case of this my method of the webservice, there is no parameter to receive this json, and so it’s wrong, right? Your tips were extremely important, however it is a very confusing subject for me, forgive me if I missed something blank

  • in the case of this command: var data = JSON.stringify({"idCli":"100","name":"Laracroft","rg":"100100"}); idCli, name and rg are variables that I created in ajax and must be matched with the attributes of my web service (which, as I’m using persist, are the same column names in the database)?

  • I adapted my javascript with the code you taught me: https://ibb.co/cNvtfV On the date, I should do something like: { "idCli":"null", "name":"$("#name"). val();", "rg":"$("#RG"). val();" } ? PS: idCli = null as it is auto increment in the bank

  • update: I entered a " @Produces("application/json")" in my WS method, it’s enough to receive json?

  • Produces would be "I produce JSON". To receive would be @Consumes if not memory.

  • Just look at the function underneath the one you marked. Each function parameter has a @param annotation to map the received from JSON to the appropriate variable in Java.

  • Tip from a friend. Don’t mix the class that will be the Webservice REST with the Persistence Facade - the one that has or delegates the Persistenceunit, you earn more grade, and separate things.

Show 3 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.