When I set the session in a file called signin.php:
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'array.php',
type: 'post',
data: {'user': $user}
});
";
In another file (index.php), I want to get:
<?php
session_start();
echo "log in as <span id=\"user\"></span><br/>";
$user = $_POST['user']
echo "
<script>
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
</script>
";
?>
I know I completely messed up with the code. What I want is that when the session is set in the signin.php file, I want $user in the content in “log in as $user” automatically updated without refresh the page, any help will be greatly appreciated!
First, work on diligently formatting your code more effectively. That code you posted was all over the place. This is a bad practice to get in and leads to errors, bugs, and other effects which can be difficult find due to the formatting.
If I follow what you’re doing, when someone logs in and then hits the
index.phppage, you want to be able to load a user’s information from another file that will give back the user data asynchronously?signin.php
Your code is confusing in what it appears to be doing; you simply have not told us enough both in code and explanation to understand what the workflow entails.
For instance, in
signin.php, you’reechoing a<script>tag that does an$.ajax()request, but who/what get’s this code? Is this part of thesignin.phpcontent, if the user successfully logs in? Does this mean thesignin.phpwill load the page to use the$.ajax()here, or is that meant to run from the$.ajax()onsuccess?If it’s the latter, you need to return regular Javascript with no markup (like a
<script>tag wrapped around it) and usedataType: 'script'in the options.Also, I would at least use a more descriptive word than
array.php; if you’re getting user data from it, name that file something likeuserdata.php.Then in
userdata.php, you can access it with$_POST['json'].index.php
This honestly makes no sense:
Why is the
setInterval()in an anonymous function that’s run while setting$.text()? This is one of those What? moments, where I’m not even sure what you’re trying to accomplish.Before that though, you have:
Why is this a
$_POST? Does thesignin.phpuse$_POSTto log a user in? Here, I believe you want$_SESSION(I think, hope, ??), since that’s where you stored the username when the user logged in usingsignin.php.This is my best guess as to what you’re trying to do (assuming you’re returning JSON-formatted data):