Nitish Bangad
Nitish Bangad

Reputation: 51

message box in PHP and navigation to another page

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.

Upvotes: 0

Views: 1357

Answers (4)

Swaraj Giri
Swaraj Giri

Reputation: 4037

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'; } } });

Upvotes: 0

Mr.MAD
Mr.MAD

Reputation: 121

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

Upvotes: 0

Kedar B
Kedar B

Reputation: 784

You can try this

echo "<script language='javascript' type='text/javascript'>alert('error');  
      </script>";
 echo "<meta http-equiv='refresh' content='1; URL=login.php'>";

Upvotes: 1

flauntster
flauntster

Reputation: 2016

For JS redirect, try;

window.location.href="http://url";

Hope this helps :)

Upvotes: 0

Related Questions