8 Replies - 449 Views - Last Post: 01 November 2013 - 12:21 PM

#1 DoxramosPS  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 07-October 12

Logging in then refreshing using javascript

Posted 31 October 2013 - 06:44 PM

I'm trying to get a javascript function that will call on a php code to log a user in.
For Instance
The User puts in their username and email then clicks login in. Rather than directing them to my functions/login.php script I want javascript to simply send the data through the login script to set the variables then refresh the page with the new session variables set unless they put in the wrong information at which time I would like it to redirect them to the incorrect information page. Being as more of my knowledge is with PHP my attempt at javascript broke it ha.
function Login() {
event.preventDefault();
$.post('functions/login.php');
}


That's just my attempt to send it through without the redirect
And then my forms submit buttons
<input type="submit" id="login" value="Login" onclick="Login();">


Not sure if I'm completely messed up of if it just needs a little cleaning.

Is This A Good Question/Topic? 0
  • +

Replies To: Logging in then refreshing using javascript

#2 Atli  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 3635
  • View blog
  • Posts: 5,756
  • Joined: 08-June 10

Re: Logging in then refreshing using javascript

Posted 31 October 2013 - 08:14 PM

Is it fair to assume, based on your use of $.post, that you are using jQuery?

The whole onclick="Login();" method of setting event handlers is a little bit outdated. It still works, but these days you should be trying to set events using Javascript, rather than using HTML attributes. It's just cleaner that way. So, instead of doing:
<script>
function Login() {
    // ...
}
</script>
<input type="submit" id="login" value="Login" onclick="Login();">


You should really be doing:
<input type="submit" id="login" value="Login">
<script>
function onLoginClick(event) {
    // ...
}

var loginInput = document.getElementById("login");
loginInput.addEventListener("click", onLoginClick, true);
</script>



Actually, since you seem to be trying to handle a login form's submit, you should really be capturing the form's submit event, rather than the submit button's click event. So, try something more like:
<form id="theForm" action="functions/login.php" method="post">
    <input type="submit" id="login" value="Login">
</form>

<script>
function onTheFormSubmit(event) {
    event.preventDefault();
    // ...
}

var theForm = document.getElementById("theForm");
theForm.addEventListener("submit", onTheFormSubmit, true);
</script>



That's the basics. Now, of course, you need to worry about handling the actual login POST. Assuming we can use jQuery here, that greatly simplifies this. jQuery has the .serialize() function, which can easily read an entire form into a string ready to be posted via a standard jQuery AJAX call, like .post(). So, inside the onTheFormSubmit function above, you could do this.
function onTheFormSubmit(event) {
    event.preventDefault();
    
    // Since this event is bound to the form
    // element, the "this" variable will reference
    // the form, allowing us to do things like:
    var $self = $(this);
    
    // Now $self will be a jQuery wrapper around
    // the form element. Meaning we can get the
    // "action" attribute on it like so:
    var actionUrl = $self.attr("action");
    
    // And we can create a POST'able string of data
    // from the form using ".serialize()"
    var postData = $self.serialize();
    
    // And now we can post this data to the action URL
    // using any of jQuery's AJAX functions.
    $.post(actionUrl, postData, function(data) {
        // This anonymous callback function is called
        // once the request has been sucessfully
        // completed. If you need to handle errors
        // (which you kind of should) then you may
        // want to use $.ajax instead. Or, depending
        // on the jQuery version, use promises. (Read
        // up on that!)
        
        // Assuming the PHP script returns "success" as
        // text on successful login, you can now do:
        if (data == "success") {
            window.location.reload(true);
        }
        else {
            alert("Login failed: " + data);
        }
    });
}


Was This Post Helpful? 0
  • +
  • -

#3 DoxramosPS  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 07-October 12

Re: Logging in then refreshing using javascript

Posted 31 October 2013 - 09:16 PM

Afraid I don't completely understand, so where you put
 var actionUrl = $self.attr("action");


For mine would it be
var actionURL = $self.attr("functions/login.php");


Sorry, I've got my own code that's working for the most part, but I want to handle errors not just refresh the page.
I got
<script> 
    $(document).ready(function() { 
        $('#login').ajaxForm(function() { 
           window.location.reload();
        }); 
    }); 
</script>


To work, so now I'm looking at the way you're handling errors and in my head it's reading out as

<script> 
    $(document).ready(function() { 
var $self = $(login); //Replace $(this); with $(login) IE. The name of my form.
 var actionUrl = $self.attr("action"); //Leave the action or change to $self.attr("functions/login.php"); ???
 var postData = $self.serialize(); 
$.post(actionUrl, postData, function(data) {
if (data=="success"){

        $('#login').ajaxForm(function() { 
           window.location.reload();
}
else {
alert("Login Failed");
}
        }); 
   } }); 
</script>


Sorry if I butchered that, just trying to fully understand what I'm doing.
Was This Post Helpful? 0
  • +
  • -

#4 DoxramosPS  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 07-October 12

Re: Logging in then refreshing using javascript

Posted 31 October 2013 - 09:32 PM

So I'm trying to do it your way and I have
 <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script> 
<script>
function onTheFormSubmit(event) {
	event.preventDefault();
	var $self = $(login);
	var actionUrl = $self.attr("action");
	var postData = $self.serialize();
	var theForm = document.getElementById("login);
	theForm.addEventListener("submit", onTheFormSubmit, true);
		$.post(actionUrl, postData, function(data) {
			if (data == "success") {
				window.location.reload(true);
			}	
		else {
			alert("Login failed");
		}
	});
}
</script>



But it's just taking to the function page, so not sure what I did wrong.
Was This Post Helpful? 0
  • +
  • -

#5 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3392
  • View blog
  • Posts: 9,586
  • Joined: 08-June 10

Re: Logging in then refreshing using javascript

Posted 01 November 2013 - 02:25 AM

line #10 belongs outside the onTheFormSubmit() function, because this part ties the function to the event. (otherwise JS doesn’t know that this function is to be called on submit).
Was This Post Helpful? 0
  • +
  • -

#6 DoxramosPS  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 07-October 12

Re: Logging in then refreshing using javascript

Posted 01 November 2013 - 09:56 AM

So if I understand right.
 function onLoginSubmit(event) {
	    event.preventDefault();
	    var $self = $(login);
	    var actionUrl = $self.attr("action");
	    var postData = $self.serialize();
	    var LoginForm = document.getElementById("login);
            }

LoginForm.addEventListener("submit", onLoginSubmit, true);
	        $.post(actionUrl, postData, function(data) {
	            if (data == "success") {
	                window.location.reload(true);
	            }  
	        else {
	            alert("Login failed");
	        }
	    });
	}


And Then for my Form
<form action="functions/login.php" method="post">
<input type="text" name="email" id="email">
<input type="password" name="password" id="password">
<input type="submit"  id="login" value="Login" class="Login-Button"  >


And Last but not least my PHP Code
<?php
include '../config.php';
session_start();
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$email = $_POST['email'];
$password = $_POST['password'];
$query = "SELECT * FROM user WHERE email='$email' AND password='$password'";
$result = mysqli_query($con,$query);
$num_rows=mysqli_num_rows($result);
$row=mysqli_fetch_array($result);
if($num_rows==1)
{
$_SESSION['username']=$row['username'];
$_SESSION['permissions']=$row['permissions'];
echo "success";
}
else{
$query2 = "SELECT * FROM user WHERE username='$email' AND password='$password'";
$result2 = mysqli_query($con,$query2);
$num_rows2=mysqli_num_rows($result2);
$row2=mysqli_fetch_array($result2);
if($num_rows2==1)
{
$_SESSION['username']=$row2['username'];
$_SESSION['permissions']=$row2['permissions'];
echo "success";
}
else {

}
}
?>


My other issue is my $_SESSION['permissions'] isn't setting, I got a code working, but I'm starting to think I understand this one better and that it would be easier to create an onload function instead of a submit so that when the user logs in I could have a on page load that checks if the user as mail or not. Appreciate everyones help.
Was This Post Helpful? 0
  • +
  • -

#7 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3392
  • View blog
  • Posts: 9,586
  • Joined: 08-June 10

Re: Logging in then refreshing using javascript

Posted 01 November 2013 - 11:19 AM

Quote

So if I understand right.

nope. line #10 (post #4) only. the lines afterwards are your AJAX call.
Was This Post Helpful? 0
  • +
  • -

#8 DoxramosPS  Icon User is offline

  • D.I.C Head

Reputation: 4
  • View blog
  • Posts: 143
  • Joined: 07-October 12

Re: Logging in then refreshing using javascript

Posted 01 November 2013 - 12:16 PM

I now have in the head of my header.php file.
<script>
theForm.addEventListener("submit", onLoginSubmit, true);

function onLoginSubmit(event) {
	event.preventDefault();
	var $self = $(login);
	var actionUrl = $self.attr("action");
	var postData = $self.serialize();
	var theForm = document.getElementById("login);
	
		$.post(actionUrl, postData, function(data) {
			if (data == "true") {
				window.location.reload(true);
			}	
		else {
			alert("Login failed");
		}
	});
}
</script>


And for my Form itself I now have
<form  action ="functions/login.php" method="post" id="login">
<input type="text" name="email" id="email">
<input type="password" name="password" id="password">
<input type="submit"  id="login" value="Login" class="Login-Button"  >


And in my PHP code I have
echo $true;


On successful login, but it's still redirecting to the function itself.
Was This Post Helpful? 0
  • +
  • -

#9 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3392
  • View blog
  • Posts: 9,586
  • Joined: 08-June 10

Re: Logging in then refreshing using javascript

Posted 01 November 2013 - 12:21 PM

View PostDoxramosPS, on 01 November 2013 - 08:16 PM, said:

And in my PHP code I have
echo $true;


if $true is not defined (looks like it) it will return nothing. hence your condition will not match.

personally, I would make the distiction by sending either a 204 HTTP header (success, no content) or a 403 HTTP header (access denied). so you’re independent of any text.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1