user381800
user381800

Reputation:

PHP how come global variable does not work when utlizing ajax to fetch content?

So I have this code snippet.

function get_box_ajax() {
    global $box;

    $box = get_box(); // creates box object

    ob_start();
    get_template( '/filepath/content.php' );
    $output = ob_get_clean();
}

// in the content.php file

global $box;

<form action="<?php echo box_url( $box->url ); ?>" method="post"> // error on this line
...
</form>

So with this code, I am getting a non-object error on the call to $box->url. Take note this is done via ajax.

So I thought in my ajax function I have already globalized $box and that will take but it doesn't seem to work? Any thoughts?

Upvotes: 0

Views: 107

Answers (2)

exussum
exussum

Reputation: 18550

Set box to null before the function. There's no reference in the global scope

$box = null;
function get_box_ajax() {
    global $box;

    $box = get_box();

Change the start to that

Upvotes: 0

federicot
federicot

Reputation: 12341

Two things:

When is your get_box_ajax function called? And what does the function get_box do? Both things are relevant.

I don't think the problem is whether box is global or not (which it is), but rather if the url variable of box is being defined or if box is being initialized at all.

Upvotes: 1

Related Questions