Data not maintained when page is reloaded

I am in the process of implementing a login panel on my index page. The login data will be sent via an ajax call. Upon successful verification of the username and password, I am storing the user data in a session and then reloading the index page upon ajax success. I have ensured that the config file is included on all pages where the session_start() method is written to ensure availability throughout. Additionally, I have confirmed that session support is enabled by checking phpinfo. Despite setting values in the session on the ajax PHP page, after the index page reloads, the session array appears to be empty.

Any assistance or guidance on resolving this issue would be greatly appreciated.

This excerpt is taken from my config.php file

<?php
session_start();
$mysql_host = "****";
$mysql_user = "****";
$mysql_password = "****";
$mysql_db = "****";
$link = mysql_connect($mysql_host,$mysql_user,$mysql_password) or die('');
mysql_select_db("$mysql_db")or die("cannot select DB");
include 'includes/user_model.php';
$fgmembersite = new FGMembersite();
$fgmembersite->InitDB($mysql_host,$mysql_user,$mysql_password,$mysql_db);
?>

The user_model.php handles the database checking and session setup.

function Login()
{
    if(empty($_POST['Email']))
    {
        $this->HandleError("UserName is empty!");
        return false;
    }

    if(empty($_POST['password']))
    {
        $this->HandleError("Password is empty!");
        return false;
    }

    $username = trim($_POST['Email']);
    $password = trim($_POST['password']);

  //  if(!isset($_SESSION)){ session_start(); }
    if(!$this->CheckLoginInDB($username,$password))
    {
        return false;
    }

    $_SESSION[$this->GetLoginSessionVar()] = $username;

    return true;
}

function CheckLoginInDB($username,$password)
 {
    $this->tablename='users';
    if(!$this->DBLogin())
    {
        $this->HandleError("Database login failed!");
        return false;
    }          
    $username = $this->SanitizeForSQL($username);
    $pwdmd5 = md5($password);
    $qry = "Select * from $this->tablename where username='$username' OR email = '$username' and password='$pwdmd5' and active_status=1";

    $result = mysql_query($qry,$this->connection);

    if(!$result || mysql_num_rows($result) <= 0)
    {
        $this->HandleError("Error logging in. The username or password does not match");
        return false;
    }

    $row = mysql_fetch_assoc($result);


    $_SESSION['name_of_user']  = $row['first_name'].' '.$row['last_name'];
    $_SESSION['email_of_user'] = $row['email'];
    $_SESSION['user_id'] = $row['user_id'];
    $_SESSION['type_id'] = $row['type_id'];

    return true;
  }

ajax.php

   <?php
   include 'includes/config.php';
   if(isset($_POST['Email'])) {
    if($fgmembersite->Login()) {
      echo 1;
    }
  else {
   echo $fgmembersite->error_message;    
   }
  }

In Index.php, I am utilizing jQuery to submit the login form:

   <script> $(document).ready(function()
   {
$("button#login").click(function()

    {$("#ErrorMessages").hide(); 

     $("#ErrorMessages").html("");            

     var username = $("#username").val();            

     var pwd = $("#password").val();            

     if(username =='' || pwd == '')                

     $("#ErrorMessages").show();                

     $("#ErrorMessages").html("Invalid Username or Password");                  

     $.ajax({  type: "POST",

               url: "loginChk.php",         

               data: $('form.login').serialize(),               

               success: function(msg)

               { if(msg == 1){

                 // $(location).attr('href','index.php');                            
                location.reload();
               }                            

               else

               {   

                $("#ErrorMessages").show();                     

                $("#ErrorMessages").html(msg);                              

                }},         

                error: function(){                            

                $("#ErrorMessages").html(msg);              

                return false;}                  

                });                        

                return false; });});

                </script>       

Answer №1

The issue I encountered was related to the session save path on the server. To resolve it, I had to specify the path before starting the session in my configuration file.

session_save_path("/home/users/web/***/cgi-bin/tmp"); // The directory where session data is saved.
session_start(); 

After this adjustment, the session functionality started working correctly.

For more information, you can also refer to the PHP manual.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to manage the back button using jQuery?

I'm currently facing a challenge when it comes to managing the Browser's History. While plugins like History.js can be helpful for smaller tasks, I find myself struggling with more complex scenarios. Let me provide an example: Imagine I have a m ...

Sending dynamic boolean model property via AJAX dynamically

I am facing an issue while passing a property from my model to an AJAX form. The boolean value is resolving as "true/false" and causing problems in the process. $.ajax({ url: '/Projects/SearchTable2', type: "GET", data: { sub ...

Accessing PHP output within Jquery

Even though I know PHP is a server-side script and JavaScript is client-side, I encountered an issue. I struggled to bypass browser security when making an AJAX request to another domain. Feeling lost, I decided to turn to PHP for help. The challenge I f ...

Error: The expression `xmlDoc.load` returns a value of undefined, which is not an object

My current challenge involves loading an XML file using Javascript in IE, Firefox, and Safari. I have yet to find a function that works well across all three browsers. The load function I am currently using is similar to the one found in w3schools tutorial ...

Using jQuery to Send Data Back to Parent Popup Window

Is there a way to achieve the following functionality with jQuery: create a popup window that sends a value back to the main window when a link in the popup is clicked, then closes the popup and automatically submits a form in the main window based on the ...

Using jQuery to dynamically insert a table row with JSON data into dropdown menus

I'm working on a web form that includes a table where users can add rows. The first row of the table has dependent dropdowns populated with JSON data from an external file. Check out the code snippet below: // Function to add a new row $(function(){ ...

What is the reason behind ASP MVC model binder's preference for JSON in POST requests?

Is there a way to bind data to a model when sending a 'GET' request with JSON.stringify() using AJAX? Currently, the model value is always null when using 'GET', but it works fine with 'POST'. Are there any solutions for this ...

Scrolling to zoom in on the div content

I need the ability to resize the content within a div without changing the size of the div itself when the user scrolls. The function I currently have is as follows: var zoomable = document.getElementById('zoomable'), zX = 1; window.addEvent ...

Tips for organizing data and dynamically linking options to another select value?

One of my challenges involves working with two select elements. The first select allows for multiple options, while the second select is dependent on the choice made in the first one. <select class="form-control" id="select1"> <option value=""& ...

Detecting a targeted POST event in JavaScript without any libraries

In a situation I'm facing, an AngularJS website is not loading jQuery (except for jQLite). My goal is to monitor events with particular parameters. Unfortunately, I'm unable to make any changes to the source code. However, by examining the event ...

Is it possible to stop an AjaxBehaviorEvent listener or send extra information to the f:ajax onevent function?

In the controller, I have created a listener that looks something like this: public class FooController { public void doSomething(AjaxBehaviorEvent evt) { closeDialogFlag = true; .. if(!isValid){ closeDialogFlag = f ...

Error: Cannot read property 'X' of undefined in JavaScript when using Django framework

Using p5.js, I am creating drawings with data from a JSON provided by my Django backend. The draw function is defined at the base level of my HTML document within the script element: function draw(json) { if (json["leaf_text"]) { stroke(100) el ...

Creating interactive lists on Android devices with PhoneGap and jQuery Mobile

I am facing an issue with my code. It works perfectly in Chrome, but when I try to run it on Android, the alert("test") function is never called. I created an apk using PhoneGap and am also using jQuery Mobile. Can anyone help me figure out what I am missi ...

Discovering XMLHttpRequest Issues within a Chrome Application

Is there a way to identify XMLHttpRequest errors specifically in Chrome App? For instance, I need to be able to recognize when net::ERR_NAME_NOT_RESOLVED occurs in order to display an error message to the user. While XMLHttpRequest.onerror is activated, ...

Combining various postponed JavaScript file imports in the HTML header into a single group

I've been facing an issue with my code structure, particularly with the duplication of header script imports in multiple places. Every time I need to add a new script, I find myself manually inserting <script type="text/javascript" src=&q ...

Is there a way to modify the window's location without having to reload it and without resorting to any sne

Initially, I believed that the hash hack was a necessity, but after observing the recent updates from Facebook, my perspective has shifted. The original hash hack (not certain if this is the correct term) involved changing location.hash to save a state in ...

jQuery modal fails to display

I am currently experiencing an issue with my jQuery dialog that is not displaying after clicking a radio button. Previously, the dialog was showing properly, but after implementing some script for submitting from the dialog, it stopped showing up when th ...

Struggling to get .parent().toggleClass to function properly

Check out this fiddle: https://jsfiddle.net/qxnk05ua/2/ I'm trying to get the background color to change when I click the button, but it's not working. Can you help me figure out why? This is the Javascript code I'm using: $(document).rea ...

Despite encountering Error 404 with AJAX XHR, the request is successfully reaching the Spring Controller

I am attempting to upload a file with a progress bar feature. var fileInput = document.getElementById('jquery-ajax-single') var form = new FormData(); form.append('uploadFile',fileInput.files[0]); $.ajax({ url: "fi ...

featherlight.js - Execute code when modal is triggered

Situation with HTML <div id="form-lightbox"> <div class="form"> <div id="ajaxreplace"> <script type="text/javascript"> jQuery(function() { jQuery.ajaxReplace({ //parame ...