Jump to content

PHP Session with AJAX

G1K777

Hello,

is anyone using sessions with ajax?
I'm sending a login form to the backend "PHP" and it gets validated and now I'm trying to make a "session".
I know how to make it the "non AJAX" way, by just refreshing the page or redirecting it to "loggedin.php" or something.
But how is it done with AJAX? I can also get a response. Do I need to force a refresh on the page or can it be done without any refreshes/page reload?

AMD FX8320 | GTX660 | 4x4GB DDR3 | LG ZR2740W

Logitech Wireless Pro  | Logitech G413 | Nuforce uDAC5  | AKG K612

Link to comment
Share on other sites

Link to post
Share on other sites

If server side data needs to be displayed then best would be to refresh/redirect. If the AJAX request returns a success response then JS can do the refresh/redirect.

Link to comment
Share on other sites

Link to post
Share on other sites

Lets say I have two php files with session_start();

index.php
login.php

If I set some session variables for example:  $_SESSION['username']
Can I access it on index.php or is a refresh needed on the index?
If I include login.php inside index.php, is a refresh still needed?
If for example there is no session_start(); in index.php can I still use all the session variables inside login.php?

AMD FX8320 | GTX660 | 4x4GB DDR3 | LG ZR2740W

Logitech Wireless Pro  | Logitech G413 | Nuforce uDAC5  | AKG K612

Link to comment
Share on other sites

Link to post
Share on other sites

With AJAX you'll need to parse the response and execute actions according to that.

 

For example, if the log in is successful, the server can send a success response and the client can either refresh, redirect to another page, or do anything else, but that is up to how the site is designed. The client can display an error message if the server sends such response or the connection fails.

 

You can start and set the session while sending the server response, since PHP sets a cookie to identify the client and match it with a session, but the client must act on the response

🙂

Link to comment
Share on other sites

Link to post
Share on other sites

You can not access data that is set after the document is finished loading (because how would you, the PHP script is done).

 

Here's how you could do it via AJAX though:

JavaScript:

$.ajax({
  url : 'login.php',
  method : 'post',
  data : {
    //username and password are variable, which you'd have to fill before calling this AJAX function
    'username' : username,
    'password' : password
  },
  success : function(data) {
    //this function is executed when the php document returns 200 (the 'everything went well' code)
    //data is the response of the document, JSON in our case
    if (data.success == true) {
      //login successful, redirect
    } else {
      //login not successful, tell the user to input username & password again
    }
  }
});

PHP (login.php):

<?php

	//we need this header to return JSON (JavaScriptObjectNotation) to the AJAX call, so we can parse the response in JS
	header('content-type:application/json');

	$username = $_POST['username'];
	$password = $_POST['password'];

	//check if the username & password combination is correct, however you seem fit
	//this is a bad example how to do it, I'd recommend a database:
	switch ($username) {
      case 'admin':
        if ($password == 'admin') {
          echo json_encode(array('success' => 'true'));
        } else {
          echo json_encode(array('success' => 'false', 'error' => 'wrong password'));
        }
        break;
      case 'user123':
        if ($password == 'userPassword') {
          echo json_encode(array('success' => 'true'));
		} else {
          echo json_encode(array('success' => 'false', 'error' => 'wrong password'));
        }
        break;
      default:
        echo json_encode(array('success' => 'false', 'error' => 'unknown username'));
        break;
    }
?>

 

Disclaimer: I pretty much wrote this from memory, I didn't test any of this, but it should work

75% of what I say is sarcastic

 

So is the rest probably

Link to comment
Share on other sites

Link to post
Share on other sites

A better solution for logging someone in via PHP would be checking the username & password combination against a database, preferably with a hashed password (you can use PHP's password_hash() and password_verify() for that)

 

I assume you know how to interact with a database using PHP?

75% of what I say is sarcastic

 

So is the rest probably

Link to comment
Share on other sites

Link to post
Share on other sites

One thing I recommend here is that you study PHP with MVC, you will see how easy it is to prepare your environment not only for a small project but for even a big one, like initializing a sessions whenever you need a session data, try out small Frameworks, like PHP SlimFramework, who will take care of yours urls, its a great start and you should be able to structure your project to respect the Model View Controller standard.

 

Have a nice day!

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×