Get content in Javascript

Asked

Viewed 74 times

0

I need to make some changes to a web page.

I am creating an HTML form with Javascript and need help in the following case:

My form has a field where the user type the ID of a SPOJ-WWW Test, after typing the ID the page must make a get of some data from the Test that is in SPOJ to complete other fields of my form.

For example, the user enters the ID of some problem and the page automatically identifies what the problem is and completes the fields, title, description, objectives, etc.

Is there a function in Javascript that does this somehow, like getting the content?

  • If open to use Jquery, ajax can help

2 answers

0

I don’t know if I understood it correctly, because I don’t know what SPOJ rsrs.... But I believe that what you want can be done as follows:

1 - Implement a function to manipulate the ID fill. This function will trigger when the "onfocusout" event happens in the input.

2 - When shooting, the function makes a "fetch" to the endpoint that serves the content you want.

3 - You take the GET Request Response performed (by fetch()) and then put the information received in the fields you decide.

handleIdSearch(event){
 let valor = event.target.value;
 fetch("http://urlDaApi.com.br?idProduto="+valor).then( function(resposta){
      // Veio um objeto do tipo Response, precisamos transformá-lo em JSON
      // Response.json() retorna outra Promise
      return resposta.json();
   }).then( function(json){
      // Pegue os valores do JSON
      document.getElementById("outroInput").value = json.valorOutroInput;
   }).catch( function(error){
      throw error;
   });
}

document.getElementById("campoIdProduto").addEventListener('focusout', 
// Callback do evento
function(event){
    handleIdSearch(event);
})

Voi there!

0


Making a GET request using pure javascript:

var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("demo").innerHTML =
      this.responseText;
    }
  };
  xhttp.open("GET", "ajax_info.txt", true);
  xhttp.send();

Example taken from W3schools

You can still use the function fetch as mentioned by Caio Saldanha’s reply.


Making a request with the jQuery library:

$.get( "ajax/test.html", function( data ) {
  $( ".result" ).html( data );
  alert( "Load was performed." );
});

Example taken from jQuery documentation

Browser other questions tagged

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