PETICIONES (XMLHttpRequest) JAVASCRIPT GET POST DELETE JSON PHP MYSQL
ChatGPT
<!DOCTYPE html>
<html>
<head>
<title>JSON POST Example</title>
</head>
<body>
<button
id="sendButton">Send JSON</button>
<script>
document.getElementById('sendButton').addEventListener('click',
sendData);
function
sendData() {
var data = {
name: "John",
age: 30,
city: "New York"
};
var
xhr = new XMLHttpRequest();
xhr.open("POST", "process.php", true);
xhr.setRequestHeader("Content-Type",
"application/json;charset=UTF-8");
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log("Response:", xhr.responseText);
} else {
console.log("Request failed:", xhr.status, xhr.statusText);
}
}
};
xhr.send(JSON.stringify(data));
}
</script>
</body>
</html>
<?php
// Read incoming JSON data
$inputJSON =
file_get_contents('php://input');
$data =
json_decode($inputJSON, true);
// Process the JSON data (for example, echoing it
back)
echo
json_encode($data);
?>
<?php
// Read incoming JSON data
$inputJSON =
file_get_contents('php://input');
$data =
json_decode($inputJSON, true);
// Get and output the value of "city"
$city =
$data['city'];
echo
"City: " . $city;
?>
////////////////////////////////////////////
var dataARR = {
byteValue:
1,
data: []
};
Note data is an array.
dataARR.data.push({Username: "wazo", Info:
"wazoinfo"});
dataARR.data.push({Username: "bifo", Info:
"bifoinfo"});
Then getting it ready and sending:
var dataJSON = JSON.stringify(dataARR);
$.ajax({
type:
"POST", // This for array
url:
"login.php",
cache:
false,
data: {
myJson: dataJSON },
success:
function (data) {
// Do
stuff here
}
});
In the
javascript:
var dataJSON = JSON.stringify(dataARR);
xhr.send(dataJSON);
In the php:
$dataTotal = json_decode(file_get_contents(
"php://input" ), true);
$Username0 = $dataTotal['data'][0]['Username'];
$Info0 = $dataTotal['data'][0]['Info']);
$Username1 =
$dataTotal['data'][1]['Username'];
$Info1 =
$dataTotal['data'][1]['Info']);
/////////////////////////////////////
var obj={
nombre:'juan',
edad:25,
sueldos:[1200,1700,1990]
};
var
cadena=JSON.stringify(obj);
onexion1=new XMLHttpRequest();
conexion1.onreadystatechange = procesarEventos;
conexion1.open('GET','pagina1.php?cadena='+cadena,
true);
conexion1.send(null);
<?php
$cad=json_decode(stripslashes($_REQUEST['cadena']));
echo 'Nombre:'.$cad->nombre;
echo '<br>';
echo 'Edad:'.$cad->edad;
echo '<br>';
echo 'Primer sueldo:'.$cad->sueldos[0];
echo '<br>';
echo 'Segundo sueldo:'.$cad->sueldos[1];
echo '<br>';
echo 'Tercer sueldo:'.$cad->sueldos[2];
?>
////////////////////////////
var xhr = new
XMLHttpRequest();
var url = "http://localhost:5043";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type",
"application/json");
var data =
JSON.stringify({"test" : "hello"});
xhr.send(data);
////////////////////////////
function sendUrl() {
var data = {
title: button.innerHTML
};
console.log(JSON.stringify(data));
var xhr =
new XMLHttpRequest();
xhr.open('POST',
url);
// no matter if the type is json or
x-www-form-urlencoded. Works with both
// xhr.setRequestHeader('Content-type',
'application/json');
// xhr.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
xhr.onload =
function() {
var
main = document.getElementById('main');
if (xhr.status === 200) {
main.innerHTML
= xhr.responseText;
}
else {
main.innerHTML
= 'Request failed. Returned status of '
+ xhr.status;
}
};
xhr.send(JSON.stringify(data));
}
<?php
$postData =
file_get_contents('php://input');
if
(empty($postData)) {
echo 'Direct
requests are not allowed!';
exit;
}
$post = json_decode($postData,
true);
//
var_dump($post);
foreach ($post
as $key) {
echo
'Product: '. $key['title'] .'|';
}
?>
///////////////////////////////////////
<!DOCTYPE html>
<html>
<body>
<h2>JSON data from PHP file.</h2>
<p>The JSON received from the PHP
file:</p>
<p id="example"></p>
<script>
var obj, dbParameters, xmlhttp;
obj = {
"table":"fruits", "limit":5 };
dbParam =
JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if
(this.readyState == 4 && this.status == 200) {
document.getElementById("example").innerHTML =
this.responseText;
}
};
xmlhttp.open("GET",
"your_file.php?x=" + dbParam, true);
xmlhttp.send();
</script>
</body>
</html>
<?php
header("Content-Type: application/json;
charset=UTF-8");
$obj =
json_decode($_GET["x"], false);
$connect = new mysqli("RequiredServer",
"RequiredUsername", "RequiredPassword",
"Northwind");
$result = $connect->query("SELECT name FROM
".$obj->table."
LIMIT ".$obj->limit);
$output = array();
$output = $result->fetch_all(MYSQLI_ASSOC);
echo
json_encode($output);
?>
xmlhttp.onreadystatechange = function() {
if
(this.readyState == 4 && this.status == 200) {
newObj =
JSON.parse(this.responseText);
for (x
in newObj) {
txt += newObj[x].name +
"<br>";
}
document.getElementById("JSON").innerHTML =
txt;
}
};
//////////////
obj = {
"table":"customers", "limit":10 };
dbParam =
JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if
(this.readyState == 4 && this.status == 200) {
newObj =
JSON.parse(this.responseText);
for (x
in newObj) {
txt += newObj[x].name +
"<br>";
}
document.getElementById("JSON").innerHTML = txt;
}
};
xmlhttp.open("POST",
"JSON.php", true);
xmlhttp.setRequestHeader("Content-type",
"application/learn-encoded");
xmlhttp.send("x=" + dbParam);
<?php
header("Content-Type: application/json;
charset=UTF-8");
$obj =
json_decode($_POST["x"], false);
$conn = new mysqli("myServer",
"myUser", "myPassword", "Northwind");
$result = $conn->query("SELECT name FROM ".$obj->table."
LIMIT ".$obj->limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo
json_encode($outp);
?>
////////////////////////////
<!DOCTYPE html>
<html>
<body>
<h2>JSON data from PHP file.</h2>
<p>The JSON received from the PHP
file:</p>
<p id="example"></p>
<script>
var obj,
dbParameters, xmlhttp;
obj = {
"table":"fruits", "limit":5 };
dbParam =
JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if
(this.readyState == 4 && this.status == 200) {
document.getElementById("example").innerHTML =
this.responseText;
}
};
xmlhttp.open("GET",
"your_file.php?x=" + dbParam, true);
xmlhttp.send();
</script>
</body>
</html>
<?php
header("Content-Type: application/json;
charset=UTF-8");
$obj =
json_decode($_GET["x"], false);
$connect = new mysqli("RequiredServer",
"RequiredUsername", "RequiredPassword",
"Northwind");
$result = $connect->query("SELECT name FROM ".$obj->table."
LIMIT ".$obj->limit);
$output = array();
$output = $result->fetch_all(MYSQLI_ASSOC);
echo
json_encode($output);
?>
////////////////////////////////////////////
https://stackoverflow.com/questions/8599595/send-json-data-from-javascript-to-php
const params =
'data=' + JSON.stringify(data)
console.log(params)
var xhr = window.XMLHttpRequest ? new XMLHttpRequest()
: new ActiveXObject("Microsoft.XMLHTTP");
xhr.open('POST', request, true);
xhr.onreadystatechange = function() {
if(xhr.status==200){
if(xhr.readyState>3) success(xhr.responseText);
}
};
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type',
'application/x-www-form-urlencoded');
xhr.send(params);
$data =
$_POST['data'];
var_dump($data);
$data = html_entity_decode($data);
var_dump($data);
$data =
json_decode($data);
var_dump($data);
//////////////////////////////
GET, POST, PUT
& DELETE using AJAX in JavaScript
OpenJavaScript
const req = new XMLHttpRequest();
METODO GET
req.open('GET', 'https://reqres.in/api/users');
req.addEventListener('load', function() {
const res =
JSON.parse(req.responseText);
console.log(res);
});
req.send();
const req = new XMLHttpRequest();
req.open('GET', 'https://reqres.in/api/users');
req.addEventListener('load', function() {
if
(req.readyState === 4 && req.status === 200) {
const
res = JSON.parse(req.responseText);
console.log(res);
} else {
console.log("Request error");
}
});
req.send();
///////////////////
METODO POST O PUT
const user = {
name:
"Nicholas Cage",
address:
"Oakwood Street",
}
const req = new XMLHttpRequest();
req.open('POST', 'https://reqres.in/api/users'); //
'POST' or 'PUT'
req.setRequestHeader("Content-Type",
"application/json");
req.addEventListener('load', function() {
const res =
JSON.parse(req.responseText);
console.log(res);
});
req.send(JSON.stringify(user));
const user = {
name:
"Nicholas Cage",
address:
"Oakwood Street",
}
const req = new XMLHttpRequest();
req.open('POST', 'https://reqres.in/api/users');
req.setRequestHeader("Content-Type",
"application/json");
req.addEventListener('load', function() {
if (req.readyState === 4
&& req.status === 201) {
const
res = JSON.parse(req.responseText);
console.log(res);
} else {
console.log("Request error");
}
});
req.send(JSON.stringify(user));
//////////////////////////////////
METODO DELETE
const req = new XMLHttpRequest();
req.open('DELETE', 'https://reqres.in/api/users/2');
req.addEventListener('load', function() {
if (req.readyState === 4
&& req.status === 204) {
console.log("Successfully deleted!")
} else {
console.log("Request
error");
}
});
req.send();
////////////////////////////////
XMLHttpRequest()
const xhr = new XMLHttpRequest();
xhr.open("POST",
"https://jsonplaceholder.typicode.com/todos");
xhr.setRequestHeader("Content-Type",
"application/json; charset=UTF-8")
const body =
JSON.stringify({
userId: 1,
title: "Fix my bugs",
completed: false
});
xhr.onload = () => {
if
(xhr.readyState == 4 && xhr.status == 201) {
console.log(JSON.parse(xhr.responseText));
} else {
console.log(`Error: ${xhr.status}`);
}
};
xhr.send(body);
const xhr = new XMLHttpRequest();
xhr.open("POST",
"https://jsonplaceholder.typicode.com/todos");
xhr.setRequestHeader("Content-Type",
"application/json; charset=UTF-8");
const body =
JSON.stringify({
userId: 1,
title: "Fix my bugs",
completed: false
});
xhr.onload = () => {
if
(xhr.readyState == 4 && xhr.status == 201) {
console.log(JSON.parse(xhr.responseText));
} else {
console.log(`Error: ${xhr.status}`);
}
};
xhr.send(body);
FetchAPI
fetch("https://jsonplaceholder.typicode.com/todos",
{
method:
"POST",
body: JSON.stringify({
userId: 1,
title: "Fix my bugs",
completed: false
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
fetch("https://jsonplaceholder.typicode.com/todos",
{
method:
"POST",
body: JSON.stringify({
userId: 1,
title: "Fix my bugs",
completed: false
}),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
})
.then((response) => response.json())
.then((json)
=> console.log(json));
AXIOS
axios.post("https://jsonplaceholder.typicode.com/todos",
{
userId: 1,
title: "Fix my bugs",
completed: false
})
.then((response) => console.log(response.data))
.then((error) => console.log(error));
const body = {
userId: 1,
title: "Fix my bugs",
completed: false
};
$.post("https://jsonplaceholder.typicode.com/todos",
body, (data,
status) => {
console.log(data);
});
///////////////////////////////
// Get all users
var url =
"http://localhost:8080/api/v1/users";
var xhr = new
XMLHttpRequest()
xhr.open('GET', url, true)
xhr.onload = function () {
var users =
JSON.parse(xhr.responseText);
if
(xhr.readyState == 4 && xhr.status == "200") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(null);
// Get a user
var url =
"http://localhost:8080/api/v1/users";
var xhr = new
XMLHttpRequest()
xhr.open('GET', url+'/1', true)
xhr.onload = function () {
var users =
JSON.parse(xhr.responseText);
if
(xhr.readyState == 4 && xhr.status == "200") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(null);
// Post a user
var url =
"http://localhost:8080/api/v1/users";
var data = {};
data.firstname = "John";
data.lastname =
"Snow";
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Content-type','application/json;
charset=utf-8');
xhr.onload = function () {
var users =
JSON.parse(xhr.responseText);
if
(xhr.readyState == 4 && xhr.status == "201") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(json);
// Update a user
var url =
"http://localhost:8080/api/v1/users";
var data = {};
data.firstname = "John2";
data.lastname =
"Snow2";
var json = JSON.stringify(data);
var xhr = new XMLHttpRequest();
xhr.open("PUT", url+'/12', true);
xhr.setRequestHeader('Content-type','application/json;
charset=utf-8');
xhr.onload = function () {
var users =
JSON.parse(xhr.responseText);
if
(xhr.readyState == 4 && xhr.status == "200") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(json);
// Delete a user
var url =
"http://localhost:8080/api/v1/users";
var xhr = new XMLHttpRequest();
xhr.open("DELETE", url+'/12', true);
xhr.onload = function () {
var users =
JSON.parse(xhr.responseText);
if (xhr.readyState
== 4 && xhr.status == "200") {
console.table(users);
} else {
console.error(users);
}
}
xhr.send(null);
//////////////////////////////
MLHttpRequest
XMLHttpRequest es un
objeto de navegador incorporado que permite realizar solicitudes HTTP en
JavaScript.
A pesar de tener la
palabra “XML” en su nombre, puede operar sobre cualquier dato, no solo en
formato XML. Podemos cargar/descargar archivos, seguir el progreso y mucho más.
En este momento, hay
otro método de búsqueda más moderno que de alguna manera desaprueba
XMLHttpRequest.
En el desarrollo web
moderno, XMLHttpRequest se usa por tres razones:
Razones históricas:
necesitamos admitir scripts existentes con XMLHttpRequest.
Necesitamos admitir
navegadores antiguos y no queremos rellenos polifónicos (por ejemplo, para
mantener los scripts pequeños).
Necesitamos algo que
fetch no pueda hacer todavía, p. para seguir el progreso de la carga.
¿Te suena familiar?
Si es así, entonces está bien, continúe con XMLHttpRequest. De lo contrario,
diríjase a Fetch.
Los basicos
XMLHttpRequest tiene
dos modos de operación: síncrono y asíncrono.
Veamos primero el
asíncrono, ya que se usa en la mayoría de los casos.
Para hacer la
solicitud, necesitamos 3 pasos:
Crear XMLHttpRequest:
let xhr = new XMLHttpRequest();
El constructor no
tiene argumentos.
Inicialízalo,
generalmente justo después de new XMLHttpRequest:
xhr.open(método,
URL, [async, usuario, contraseña])
Este método
especifica los principales parámetros de la solicitud:
método: método HTTP.
Por lo general, "GET" o "POST".
URL: la URL para
solicitar, una cadena, puede ser un objeto de URL.
asíncrono: si se
establece explícitamente en falso, entonces la solicitud es síncrona, lo
cubriremos un poco más adelante.
usuario, contraseña:
inicio de sesión y contraseña para la autenticación HTTP básica (si es
necesario).
Tenga en cuenta que
la llamada abierta, al contrario de su nombre, no abre la conexión. Solo
configura la solicitud, pero la actividad de la red solo comienza con la
llamada de envío.
Envíalo.
xhr.send([cuerpo])
Este método abre la
conexión y envía la solicitud al servidor. El parámetro de cuerpo opcional
contiene el cuerpo de la solicitud.
Comentarios
Publicar un comentario