I am creating a login page in PHP. On entering wrong username/password I am showing a javascript alert box. I now want to navigate user back to login page on clicking "OK" button of alert box . Am using "header(location:url)", but then javascript code is not working. Is there any other way to do this.
You can try this
echo "<script language='javascript' type='text/javascript'>alert('error');
</script>";
echo "<meta http-equiv='refresh' content='1; URL=login.php'>";
For JS redirect, try;
window.location.href="http://url";
Hope this helps :)
Put this code in the login error page ..
<script>
alert('Wrong Username/Password');
window.location = "http://www.google.com";
</script>
But if you are familiar with jquery i advice you to do the login process with ajax request and show the notifications in the same page instead of navigating back and forth.
If you need i can create a simple one in plnkr
For the js redirect, u can use
window.location.href='http://whereEver';
Note: Username/ password validations are server side. Assuming its an ajax call, after you get the validation results, instead of triggering an alert, have a div in the page itself where you can inject the server response. Alerting looks unprofessional.
Better approach would be something like
HTML
<div class="response"></div>
CSS
.response {
display:none;
}
.error {
color: red; // find a better color
}
PHP
On validation failure, have a variable, lets call it status
and make it false. The validation response can be something like,
$response = ['status' => false, 'message' => 'Username / password mismatch'];
Then send back the results
die(json_encode($response));
Note: If you are using PHP < 5.4, use
$response = array('status' => false, 'message' => 'Username / password mismatch');
JS
$.ajax({ url: 'url-to-post', type: 'POST', data: $('form[name="your-form-name"]').serialize(), dataType: 'json', success: function(data) { if (!data.status) { // inject into response $('.response').addClass('error').html(data.message).show(); } else { // redirect them to home page, i assume window.location.href = '/home'; } } });