0
I’m trying to post on the API using JSON, but it always returns page error not found. But I’m sure that the URL is correct, because when I use "POSTMAN" works perfectly.
Follow the javascript code.
var btncadastro = document.querySelector("#cadastrar");
btncadastro.addEventListener("click", function(event){
event.preventDefault();
console.log("fui clicado");
var idnome = document.querySelector("#nome");
var idra = document.querySelector("#ra");
var idsenha = document.querySelector("#senha");
var idemail = document.querySelector("#email");
//Pega o status
var idstatus = document.select.status.selectedIndex;
var status_id = document.select.status[idstatus].value;
var nome = idnome.value;
var ra = idra.value;
var senha = idsenha.value;
var email = idemail.value;
var usuario = ({
"ra" : ra,
"senha" : senha,
"nome" : nome,
"email" : email,
"status_id" : status_id
});
console.log(nome);
console.log(status);
if (nome == '' || ra == '' || senha == '' || email =='') {
var labelerro = document.querySelector("#erro");
labelerro.textContent = "Algum dos campos está em branco";
}
else{
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if(window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
var data = JSON.stringify(usuario);
xhr.open("POST", "http://www.dev-android.hol.es/Api/novousuario", true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.send(data);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4){
console.log("Foi");
if(xhr.status == 200){
console.log("funcionou");
console.log(xhr.responseText);
}
else{
console.log("Erro no servidor");
console.log(xhr.status);
}
}
else{
console.log("erro no servidor");
}
}
}
});
follows the API code, in PHP
$app->post('/novousuario','postUsuario');
function postUsuario(){
$request = \Slim\Slim::getInstance()->request();
$usuario = json_decode($request->getBody());
$sql = "INSERT INTO usuario (
ra,
senha,
nome,
email,
status_id)
values (
:ra,
:senha,
:nome,
:email,
:status_id) ";
$conn = getConn();
$stmt = $conn->prepare($sql);
$stmt->bindParam("ra",$usuario->ra);
$stmt->bindParam("senha",$usuario->senha);
$stmt->bindParam("nome",$usuario->nome);
$stmt->bindParam("email",$usuario->email);
$stmt->bindParam("status_id",$usuario->status_id);
$stmt->execute();
$usuario->id = $conn->lastInsertId();
echo json_encode($usuario);
}
Can you help me?
Error shown in console?
– Hiago Souza
You are in the same domain as the request you are citing (http://www.dev-android.hol.es) ?
– Don't Panic
It gives error 404, saying that the page was not found. I am not in the same domain.
– Kaio
2cadastroUsuario.js:54 OPTIONS http://www.dev-android.hol.es/Api/novousuario 404 (Not Found) (Anonymous) @registration.js:54 user.html:1 Xmlhttprequest cannot load http://www.dev-android.hol.es/Api/novousuario. Response for preflight has invalid HTTP status code 404
– Kaio