Perform redirection by getJSON

Asked

Viewed 42 times

1

I’m making the login screen using getJSON. I’d like to know how I can do the redirect once it’s successful.

The idea of redirecting login.php is not to get too exposed the Javascript code.

login file.PHP

$Array[] = Array(
    "sucesso" => "<script>window.location='painel.php'</script>",
);
$json_encode = json_encode($Array);
echo $json_encode;

INDEX.PHP file

$("#acessar").click(function() {
    usuario = $("#usuario").val();
    senha = $("#senha").val();

    // carregamos o JSON passando o nome
    $.getJSON("login.php", {usuario:usuario, senha:senha}, function(json){

        json[0].sucesso;

    });
});

1 answer

1


You need only return the targeting URL, not a script.

Change the array in PHP to return only the desired URL:

$Array[] = Array(
    "sucesso" => "painel.php",
);

And in Ajax you redirect this way:

$.getJSON("login.php", {usuario:usuario, senha:senha}, function(json){
   location.href = json[0].sucesso;
});
  • Sam, is giving internal error in the server when use location.href = json[0].sucesso;

  • There should be no server error, because this code is Javascript.

  • I decided, inside the getJSON I have a IF that checks whether returned successfully or not. I put in the else and it worked.

Browser other questions tagged

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