3

I have a variable set in my main file (main.php), and need the second file (uploads.php) to reference the variable as it is set in the first file. It is returning undefined right now tho.

The second file is loaded with $.load into the first file: code example below -

Main.php Contents:

<?php $accountName = get_option('account_name'); ?>

<div id="uploads"></div>

<a href="#" onclick="loadUploadsFile()">Load Your Playlist</a>

function loadUploadsFile() {
     jQuery('#uploads').load('uploads.php');
}


Uploads.php file contents

<?php echo $account_name; ?>    <== returns undefined

$url = 'http://www.somewebsite.com/' . $accountName . '/page/'

/* more code below running a query/loop etc. */


As you may be able to tell, I want Uploads.php to reference the variable decleration in Main.php but is is not pulling the value, it is just returning undefined. Uploads.php loads into the uploads div, but without the account name set the content is just blank.

Would I need to pass the variable to Uploads.php through ajax? I've tried session variables but couldn't get that to work. I was trying an ajax request but I am new to it so couldn't get that nailed. Any help would be great.

4 Answers 4

2

Session variables should work after all. Make sure you have the following:

In Main.php

session_start();

$_SESSION["account_name"] = "test";

In Uploads.php

echo $_SESSION["account_name"];
Sign up to request clarification or add additional context in comments.

Comments

1

You could pass it as a GET parameter in your jQuery call like:

jQuery('#uploads').load('uploads.php?account=<?php echo($accountName);?>');

And then in your uploads.php file get it from the request like:

$accountName = $_GET['account'];

Some other options are storing it in the session, setting a cookie, or using jQuery .post to send it as POST data.

1 Comment

Beautiful. Simple and exactly what I was after. I had no idea how to achieve this tho. Thank you so much for the help, you just ended two days of hair pulling! Will mark this as correct when I am allowed to.
1

Since you are doing jQuery, you might want to look at http://api.jquery.com/jQuery.post/.

Your code should be something like (not sure if exactly)

$.post('uploads.php', { account_name: "<?= get_option('account_name') ?>" }, function(data) {
  $('.result').html(data);
});

And then you can use this variable in your uploads.php by referencing $_POST['account_name'].

PS: I assume you are having PHP 5.4x

Comments

0

Save the account name in a session

Main.php

<?php 
session_start();
$accountName = get_option('account_name'); 
$_SESSION['accountName'] = $accountName;
?>

Uploads.php

<?php echo $_SESSION['accountName']; ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.