javascript - How to redirect user to a page by an ajax call? -
i have login page user enters email , password.
so, able make ajax call page configuration of data.
now, if email , password correct must redirect user new page called, "home".
tried, but, redirected div page.
solutions?
in advance, everyone!
<script type="text/javascript"> $(document).ready(function (e) { $(".login-form").on('submit',(function(e) { e.preventdefault(); $.ajax({ url: "verify/login.php", type: "post", data: new formdata(this), contenttype: false, cache: false, processdata:false, success: function(data) { $(".login-result").html(data); }, error: function() { } }); })); }); </script>
this simple request code, working fine.
now, in php file login.php.
if ($email == $dbemail && $password == $dbpassword) { header("location:home"); }
in code page, "home" being shown in div, "login-result".
the problem after ajax request, login.php
script sends header browser 302 (redirect) status code, browser sends request home page, , result of request returned success of ajax call. so, put complete home page inside .login-result
div.
now, if use window.location
call inside success function, of above plus request home page.
one solution send response json object success or error status. example:
// login.php if ($email == $dbemail && $password == $dbpassword) { die( json_encode( [ 'success' => 1 ] ) ); } else { die( json_encode( [ 'success' => 0, 'error' => 'invalid username or password' ] ) ); }
that way know whether login successful or not, , can choose appropriate action (redirect or show error). not mention avoiding of unnecessary requests.
datatype: 'json', success: function( data ) { if ( data.success ) window.location = "home.php"; // change location else $(".login-result").html( data.error ); }
Comments
Post a Comment