Skip to content

Instantly share code, notes, and snippets.

@hawkapparel
Created January 19, 2019 20:41
Show Gist options
  • Save hawkapparel/f2fd1e13137ffb83674fccd48aa1b774 to your computer and use it in GitHub Desktop.
Save hawkapparel/f2fd1e13137ffb83674fccd48aa1b774 to your computer and use it in GitHub Desktop.
Example AJAX with native VANILLA JS
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Ejemplo API</title>
</head>
<body>
<h1>EJEMPLO API</h1>
</body>
<script type="text/javascript">
//PETICION GET
var url = "http://190.108.81.149:8080/ws/api/Clientes";
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
console.log("ESTOY EN EL REQUEST ONLOAD");
console.log(request);
if (request.status >= 200 && request.status < 400) {
// Success!
console.log("ESTOY EN Success");
console.log(request.responseText);
var data = JSON.parse(request.responseText);
console.log("ESTOY EN EL DATA");
console.log(data);
} else {
// We reached our target server, but it returned an error
console.log("error DEL servidor");
}
};
request.onerror = function() {
// There was a connection error of some sort
console.log("error DE TU CONEXION");
};
request.send();
/////////////////////////////////////////////////////
//PETICION POST
var url = "http://190.108.81.149:8080/ws/api/Clientes";
var inputNombre = document.getElementById("nombre").value;
var auth = false;
if ( inputNombre !== "") {
auth = true;
}
if( auth ){
let dataJson = {
nombreCompleto: inputNombre,
direccion: "Casa asdasdsadsa",
tipoDocumento: "1",
numeroDocumento: "20103129061",
telefono: "979582967",
celular: "979582967",
email: "[email protected]",
email1: "",
email2: "",
nombreContacto: "Christian Tamayo",
estado: 1
}
var data = JSON.stringify(dataJson);
var request = new XMLHttpRequest();
request.open('POST', url, true);
request.setRequestHeader('Content-type', 'application/json; charset=utf-8', 'X-Requested-With');
//request.setRequestHeader('X-CSRF-Token', token.value);
request.onreadystatechange = function() {
console.log("ESTOY EN EL REQUEST ONLOAD POST");
console.log(request);
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
// Success!
console.log("ESTOY EN Success POST");
console.log(request.responseText);
var data = JSON.parse(this.responseText);
console.log("ESTOY EN EL DATA POST");
console.log(data);
}else{
console.log("error DEL servidor POST");
}
}
};
request.send(data);
request = null;
}
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment