Insertion of record with webservice returns error but inserts in the database

Asked

Viewed 95 times

2

Hello, I have a javascript function that makes an ajax call to a php file that must insert the records in the Mysql database. Well, I am able to enter the records but the function is returning me an error. Can anyone say the reason for the error? Thanks in advance.

Error displayed in Alert:

Answer: {"readyState":0,"status":0,"statusText":"error"}

functions js.

function salvar(){
$.ajax({
    type: 'POST',
    dataType: 'json',
    data: {operationType: 'insert', nome: $('#nome').val(), sobrenome: $('#sobrenome').val(), idade: $('#idade').val() },
    url: 'http://localhost/projetos/wstest/cadastrar.php',
    ContentType: 'application/json',
    success: function(response){
        alert('Resposta: '+JSON.stringify(response));
    },
    error: function(err){
        alert('Resposta: '+JSON.stringify(err));
        alert('Erro ao inserir registro!');
    }
});}

register.php

include './conexao.php';

header("Access-Control-Allow-Origin: *");

$link = conectar();

$nome = mysqli_real_escape_string($link, $_REQUEST['nome']);
$sobrenome = mysqli_real_escape_string($link, $_REQUEST['sobrenome']);
$idade = mysqli_real_escape_string($link, $_REQUEST['idade']);

$query = "INSERT INTO `usuario`(`nome`, `sobrenome`, `idade`) "
    . "VALUES ('$nome','$sobrenome','$idade')";

$res = mysqli_query($link, $query);

if(isset($_POST['operationType']))
{

    if ($_POST['operatioType'] == "insert") 
{        
    $query = "INSERT INTO `usuario`(`nome`, `sobrenome`, `idade`) "
            . "VALUES ('$nome','$sobrenome','$idade')";

    $res = mysqli_query($link, $query);

    if ($res == true) 
    {
        $resultado = 1;

        return $resultado;
    } 
    else
    {
        $resultado = 0;

        return $resultado;
    }

    echo json_encode($resultado);
}

else if($_POST['operationType'] == "login")
{

}
}
else
{
    echo "Formato de requisição inválido! O aplicativo não conseguiu se comunicar "
. "de maneira correta com o servidor.";
}
  • It doesn’t seem like a mistake in PHP, it’s pretty simple. What can be is the return not being a valid JSON, day jquery is not able to parse it. Try changing the type of dataType: 'json' to 'html', for example, and see if the error continues. Another important detail is that the script may be littering in the buffer, for example, a warnning, and this will zicar the json output, so you need to treat these erroneous buffer outputs. Another important detail, check the possibility of using PDO instead of mysqli, besides unsafe, is discontinued

  • I see that you do not need to convert to JSON, just return the variable value $resultado.

1 answer

0

the error may be here:

    else if($_POST['operationType'] == "login")
{

}
}
else
{
    echo "Formato de requisição inválido! O aplicativo não conseguiu se comunicar "
. "de maneira correta com o servidor.";
}

There’s an extra key closing, try to erase it and see what happens. and add something if == login, even if it is a done variable ex $a = "";

Browser other questions tagged

You are not signed in. Login or sign up in order to post.