Skip to content

Instantly share code, notes, and snippets.

@sistematico
Last active November 6, 2019 19:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sistematico/c1bdf247c69edd60206b48fa9bc4cf11 to your computer and use it in GitHub Desktop.
Save sistematico/c1bdf247c69edd60206b48fa9bc4cf11 to your computer and use it in GitHub Desktop.
XMLHttpRequest Examples
<?php
$array = array(
array('texto'=>'Olá ' . $_POST['nome'] . '!'),
array('texto'=>'Bem-vindo(a) ' . $_POST['nome']),
array('texto'=>'Tudo bem ' . $_POST['nome'])
);
echo json_encode($array);
<?php
echo "Lorem, ipsum dolor sit amet consectetur adipisicing elit. Nostrum repellendus doloremque consectetur sed esse autem quos dignissimos recusandae velit eum qui voluptatibus vitae obcaecati id repellat aspernatur, eaque ipsa aliquid?";
<!DOCTYPE html>
<html lang="pt-br">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>XMLHttpRequest</title>
</head>
<body>
Código em: <a href="https://gist.github.com/sistematico/c1bdf247c69edd60206b48fa9bc4cf11">https://gist.github.com/sistematico/c1bdf247c69edd60206b48fa9bc4cf11</a>
<br /><br />
<button id="getBtn">XHR Get</button> <div id="resultadoGet"></div><br /><br />
<button id="postBtn">XHR Post</button> <div id="resultadoPost"></div><br /><br />
<button id="jsonBtn">XHR Json</button> <div id="resultadoJson"></div><br /><br />
<button id="callbackBtn">XHR Callback</button> <div id="resultadoCallback"></div><br /><br />
<script src="xhr.js"></script>
<script src="xhrpost.js"></script>
<script src="xhrjson.js"></script>
<script src="xhrcallback.js"></script>
</body>
</html>
<?php
$array = array(
array('texto'=>'Algum texto'),
array('texto'=>'Algum outro texto'),
array('texto'=>'E mais algum texto')
);
echo json_encode($array);
<?php
echo $_POST['lorem'];
const getBtn = document.getElementById("getBtn");
const resultadoGet = document.getElementById("resultadoGet");
let xhr = (url,div) => {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
div.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
};
getBtn.onclick = function(){
xhr('get.php', resultadoGet);
};
const callbackBtn = document.getElementById("callbackBtn");
const resultadoCallback = document.getElementById("resultadoCallback");
let xhrCallback = (url, method, cb, params = null) => {
xmlhttp = new XMLHttpRequest();
xmlhttp.open(method, url, true);
if (method === 'post') {
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
cb(xmlhttp.responseText);
}
}
xmlhttp.send(params);
};
let callback = (resposta) => {
let saida = '';
data = JSON.parse(resposta);
data.forEach((el, i) => {
saida += data[i].texto + '<br />';
});
resultadoCallback.innerHTML = saida;
};
callbackBtn.onclick = function(){
xhrCallback('callback.php', 'post', callback, 'nome=Joao&sobrenome=Silva');
};
const jsonBtn = document.getElementById("jsonBtn");
const resultadoJson = document.getElementById("resultadoJson");
let xhrJson = (url, div) => {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
let objetos = JSON.parse(xmlhttp.responseText);
let saida = '';
let i;
for(i = 0; i < objetos.length; i++) {
//saida += '<a href="' + objetos[i].id + '">' + objetos[i].artista + '</a><br>';
saida += objetos[i].texto + '</a><br>';
}
div.innerHTML = saida;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
};
jsonBtn.onclick = function(){
xhrJson('json.php', resultadoJson);
};
const postBtn = document.getElementById("postBtn");
const resultadoPost = document.getElementById("resultadoPost");
let xhrPost = (url,params,div) => {
xmlhttp = new XMLHttpRequest();
xmlhttp.open('POST', url, true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
div.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(params);
};
postBtn.onclick = function(){
xhrPost('post.php', 'lorem=ipsum&ipsum=lorem', resultadoPost);
};
@wilcorrea
Copy link

function ajax (method, url, callback, error = () => undefined) {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState !== 4) {
            return
        }
        const response = xmlhttp.responseText
        if (xmlhttp.status < 200 && xmlhttp.status > 299) {
            error(response, xmlhttp)
           return
        }
        callback(response, xmlhttp)
    }
    xmlhttp.open(method, url, true);
    xmlhttp.send();

@sistematico
Copy link
Author

function ajax (method, url, callback, error = () => undefined) {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState !== 4) {
            return
        }
        const response = xmlhttp.responseText
        if (xmlhttp.status < 200 && xmlhttp.status > 299) {
            error(response, xmlhttp)
           return
        }
        callback(response, xmlhttp)
    }
    xmlhttp.open(method, url, true);
    xmlhttp.send();

Aí é outro nível né!? :D

@wilcorrea
Copy link

wilcorrea commented Nov 5, 2019

function post (url, params, callback = undefined, error = undefined) {
  ajax('POST', url, params, callback)
}

function ajax (method, url, params = undefined, callback, error = () => undefined) {
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readyState !== 4) {
            return
        }
        const response = xmlhttp.responseText
        if (xmlhttp.status < 200 && xmlhttp.status > 299) {
            error(response, xmlhttp)
           return
        }
        callback(response, xmlhttp)
    }
    xmlhttp.open(method, url, true);
    xmlhttp.send();

--

const postBtn = document.getElementById("postBtn");
const resultadoPost = document.getElementById("resultadoPost");

postBtn.onclick = function(){
    post('post.php', 'lorem=ipsum&ipsum=lorem', (response) => {
       div.innerHTML = xmlhttp.responseText;
    })
};

@IgorDePaula
Copy link

Pra quem reclamou de var ontem, nao ta faltando const ae nao? kkkkkkkkkk

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment