0

Im working with a combination of Ajax (with native JavaScript) and php to construct a login from.

The from sits in a php file (login.php). When it gets submitted, it runs a JS onlclick function which posts the form data to another php file which validates the form data :

<input type="button" name="submit" value="Submit" onclick="JavaScript:xmlhttpPost('validator.php')"/>

The results from validator.php are returned in a div using JavaScript:

function updatepage(str){

document.getElementById("result").innerHTML = str;

}

Finally if the password and username are both correct, validator.php runs a redirect like this:

if ( // form data is valid ) {

    header("Location: welcome.php");

}

However, because everything's running through ajax, this results in the "welcome.php" page being displayed in the "results" div on the original login page.

Is there a way to send a redirect via JavaScript instead?

user3143218
  • 1,738
  • 5
  • 32
  • 48

5 Answers5

1

You can redirect via JavaScript using this code:

window.location.href = 'welcome.php';

When you make an AJAX call, you can not redirect via a server-side application like PHP.

You have to get a response and do it in your JavaScript.

Here is an ajax request example with jQuery and PHP.

Put this code on your front-end (view):

<script type="text/javascript">
    $(document).ready(function(){
        $.ajax({
            url: 'your-php-file.php',
            dataType: 'html',
            success: function(response) {
                window.location.href = response;
            }
        });
    });
</script>

https://api.jquery.com/jQuery.ajax/

In your PHP file, after you did what you want; echo the path or file to redirect as a response.

<?php
    echo "file-or-path-to-redirect.php";
Dharman
  • 30,962
  • 25
  • 85
  • 135
Canser Yanbakan
  • 3,780
  • 3
  • 39
  • 65
1

In lieu of an answer that actually works, I've figured out a workable solution. I'm not sure whether this is the correct way of doing this but it works well.

In my validator.php when the form values are correct I put the following:

if ( // form data is valid ) {

    echo 'redirect';

}

Then, on my login page, when returning the string from the php page I put this:

function updatepage(str){

   if (str.match(/redirect/)) {
      window.location.replace('welcome.php');
   }
   else {
      document.getElementById("result").innerHTML = str;
   }
}

The idea is that when validator.php confirms the login credentials are correct it returns a string.

If that string matches "redirect", JavaScript will redirect the page.

If anyone has any input on this, please comment. I feel this is a pretty good solution. Surprised I didn't think of it earlier.

user3143218
  • 1,738
  • 5
  • 32
  • 48
0
window.location.href='welcome.php';

or using real path

window.location.href='http://www.yourdomain.com/welcome.php';
MD SHAHIDUL ISLAM
  • 14,325
  • 6
  • 82
  • 89
0

you can use window object

window.location.href="http://example.com/welcome.php";
ashishmaurya
  • 1,196
  • 10
  • 18
0

The easiest way to do this is to emulate it with a json response. then you parse the json to see what kind of response you got . here is a working example :

Index.html

<!DOCTYPE html>
<html>
<head>
<script>

function updatepage(str){

document.getElementById("result").innerHTML = str;

}


function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }

xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {

      var jsonParse = JSON.parse(xmlhttp.responseText);

      if(jsonParse.redirect){
        window.location.replace(jsonParse.redirect);
      }
      if(jsonParse.success){
        updatePage(success);
      }
    }
  }

xmlhttp.open("GET","login.php",true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

login.php

<?php


// if($error)
echo json_encode(array('redirect'=>'welcome.php'));

//else
echo json_encode(array('success'=>'<div>logged in</div>'));

?>
Paul Bele
  • 1,514
  • 1
  • 11
  • 12
  • No, you can't. The XMLHttpRequest object handles redirects transparently. It will never provide you with access to the `301` response because it will obey the redirect, fetch the next resource and then give you the `200` respond for that resource. – Quentin Apr 27 '14 at 10:57
  • Ah I see. So you check with JavaSCript on the front-end to see if a php redirect has been called from the back-end. If it has you redirect the page with JavaSCript. Is that correct? – user3143218 Apr 27 '14 at 10:58
  • @user3143218 — That's what seblaze is trying to do but, for the reasons it explained in my comment, it won't work. – Quentin Apr 27 '14 at 10:58
  • Ahh I see. Could you use a match/onchange function to check if the result div matches a string and then redirect? – user3143218 Apr 27 '14 at 11:01
  • @user3143218 why not return a json object, and then parse it in your javascript instead of redirect it ? for example, in your php you will return json_encode(array('redirect'=>'welcome.php')); and it's way easier to do this in javascript – Paul Bele Apr 27 '14 at 11:03
  • How do you handle the json parsing? – user3143218 Apr 27 '14 at 11:36
  • check here : http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript – Paul Bele Apr 27 '14 at 11:37
  • Sorry I meant how would you parse the json to a redirect? – user3143218 Apr 27 '14 at 11:43
  • after you parse the JSON. you would do something like : if(response.redirect){ window.location.href = response.redirect;} – Paul Bele Apr 27 '14 at 11:49
  • I found a workable solution! See my answer below and tell me what you think. – user3143218 Apr 27 '14 at 12:11
  • @user3143218 i added a full example for this question using json responses – Paul Bele Apr 27 '14 at 12:59