Pass variable from php to ajax and redirect using location.href

0

I have a function in ajax that receives form parameters and processes them in a php file that searches for the registry, if it matches it redirects to another page, otherwise it shows an error message. The problem is that I can not get the parameter $ id to redirect, I get the value 2 of the echo. Attachment code. It is a system to validate and activate users. I would appreciate your cooperation and thanks.

Ajax file:

submitHandler: function(form){
                    var thisForm = $(form);
                    $.ajax({
                        type: "POST",
                        url : "sesuser.php",
                        data: thisForm.serialize(),
                        success: function(msg){
                            $("#alert").show();
                            $("#alert").html("<strong>Procesando...</strong>");
                            setTimeout(function() {
                                $('#alert').fadeOut('slow');
                            }, 4000);

                            if(msg == "1"){
                                $("#alert").html("<div class='alert alert-danger alert-dismissible' role='alert'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>Usuario o Contraseña incorrectos... Por favor intente nuevamente.</div>");
                            }else if(msg == "2"){
                           /// aqui esta mi problema ////
                                var objJson=JSON.parse(msg);
                                location.href ='activar?id=' + objJson;
                            }else if(msg == "3"){
                                window.location.href="index";
                            }

                            setTimeout(function() {
                                $('#alert').fadeOut('slow');
                            }, 4000);
                            $("#iniciar")[0].reset();
                        }
                    });
                }

PHP File:

if ((isset($_POST['correo'])) and (isset($_POST['passw1']))) {

    $res = mysqli_query($con, "SELECT * FROM visitantes");
    $fila = mysqli_fetch_array($res);
    if ($fila){
        $usuario = mysqli_real_escape_string($con, $_POST['correo']);
        $pass    = mysqli_real_escape_string($con, $_POST['passw1']);
        $result = mysqli_query($con, "SELECT * FROM visitantes WHERE correo = '" . $usuario. "' and clave = '" . md5($pass) . "'");

        if ($row = mysqli_fetch_array($result)) {
            $act = $row['activado'];
            if ($act == "0"){
                $id = $row['id_vis'];  // no logro pasar este parametro $id ////
                echo "2";
            }else{
                session_start();
                $_SESSION['usr_id'] = $row['id_vis'];
                $_SESSION['usr_name'] = $row['usuario'];
                $_SESSION['usr_tipo'] = $row['id_tipo'];
                $_SESSION["ultimoAcceso"]=date("Y-n-j H:i:s");
                echo "3";
            }
        } else {
            echo "1";
            //$errormsg = "Usuario o Contraseña incorrectos!!!";
        }
    }
}
    
asked by javierm 13.11.2018 в 16:04
source

2 answers

0

You can return a JSON from PHP with the two values that interest you, for example:

...
if ($row = mysqli_fetch_array($result)) {
            $act = $row['activado'];
            if ($act == "0"){
                $id = $row['id_vis'];  
                echo json_encode(array('status' => 2,'id' => $id)); //valor para el control y el id
            }else{
                session_start();
                $_SESSION['usr_id'] = $row['id_vis'];
                $_SESSION['usr_name'] = $row['usuario'];
                $_SESSION['usr_tipo'] = $row['id_tipo'];
                $_SESSION["ultimoAcceso"]=date("Y-n-j H:i:s");
                echo json_encode(array('status' => 3,'id' => ''));
            }
        } else {
            echo json_encode(array('status' => 1,'id' => ''));
            //$errormsg = "Usuario o Contraseña incorrectos!!!";
        }
...

In this way you can access the values from js and redirect accordingly:

submitHandler: function(form){
                    var thisForm = $(form);
                    $.ajax({
                        type: "POST",
                        url : "sesuser.php",
                        data: thisForm.serialize(),
                        success: function(msg){
                            var objJson=JSON.parse(msg);
                            $("#alert").show();
                            $("#alert").html("<strong>Procesando...</strong>");
                            setTimeout(function() {
                                $('#alert').fadeOut('slow');
                            }, 4000);

                            if(objJson.status == "1"){
                                $("#alert").html("<div class='alert alert-danger alert-dismissible' role='alert'><button type='button' class='close' data-dismiss='alert' aria-label='Close'><span aria-hidden='true'>&times;</span></button>Usuario o Contraseña incorrectos... Por favor intente nuevamente.</div>");
                            }else if(objJson.status == "2"){


                                location.href ='activar?id=' + objJson.id; //el otro valor en el json retornado
                            }else if(objJson.status == "3"){
                                window.location.href="index";
                            }

                            setTimeout(function() {
                                $('#alert').fadeOut('slow');
                            }, 4000);
                            $("#iniciar")[0].reset();
                        }
                    });
                }
    
answered by 13.11.2018 в 16:25
0

Your problem is that you only print the statuses in numbers to the answer and that is what ajax will show if you want to pass more content to the answer I think of the following

print something like the following string on your backend:

echo "1|usuario";

in the result of ajax uses as a delimiter the | to separate the result with split

var res = msg.split("|");
//res[0]; status
//res[1]; usuario

but I recommend you use json better on the backend.

echo json_encode(array('status' => 1, 'usuario' => $id));

you must first add the option: dataType: 'json' to your ajax so that it can understand which result will return.

in your ajax response

msg.status //1
msg.usuario //id user
    
answered by 13.11.2018 в 16:40