I'm trying to make a post in the API, using JSON, but it always returns page error not found. But I'm sure the URL is correct, because when I use "POSTMAN" it 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?