简体   繁体   中英

Creating a PHP session variable after successful AJAX call

I am having problems creating a PHP session following a successful AJAX call. Here is the AJAX code:

function onSignIn(googleUser) {
 var profile = googleUser.getBasicProfile();
 var id = profile.getId();
 var em = profile.getEmail();
 var name = profile.getName();
 var pic = profile.getImageUrl();
 var xhttp = new XMLHttpRequest();
 xhttp.onreadystatechange = function() {
 if (this.readyState == 4 && this.status == 200) {
   document.getElementById('confirm-login').style.display = 'block';
 }
};
 xhttp.open("GET", "./assets/inc/profile.php?id="+id+"&e="+em+"&n="+name+"&p="+pic, true);
 xhttp.send();  
}

This part works perfectly. I only include it for completeness sake.

Here's the contents of profile.php

<?php

$id = $_GET["id"];
$email = $_GET["e"];
$name = $_GET["n"];
$pic = $_GET["p"];

require_once("db.php");

$result = $mysqli->query("SELECT googleid FROM user_tbl WHERE googleid = '$id' LIMIT 1");

if($result->num_rows == 0) {
    $sql = "INSERT INTO user_tbl (googleid, email, fullname, pic, loc) VALUES ('$id', '$email', '$name', '$pic', '')";
    if (mysqli_query($mysqli, $sql)) {
        echo "New record created successfully";
    } else {
        echo "Error: " . $sql . "" . mysqli_error($mysqli);
    }
} else {
    echo "already exists";
}

$mysqli->close();

session_start();    
$_SESSION['gid'] = $id;

?>

All of this code works except for session_start(); and $_SESSION['gid'] = $id; when I return to another PHP page (which correctly has session_start(); at the very top of the page) the variable has not been created in profile.php

Any help as to what I'm doing wrong would be much appreicated.

You can't start a session after the script has sent output. (There should have been output to that effect; if there wasn't, try changing PHP's warnings.) The session_start() call must come before any echo call that is actually executed.

On an unrelated topic, you will want to learn how to escape your database parameters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM