Alessandro Zago
Alessandro Zago

Reputation: 803

update a php variable from external code

I have a question, there is a way to update $error when his value change on external listPagPrinc.php?

<div id="statoPag">
    <h3> Stato : <?php echo $error; ?> </h3>
</div>

<div class="headerCont">
    <?php
        include('procedure/listPagPrinc.php');
    ?>
</div>

Upvotes: 0

Views: 57

Answers (2)

LSerni
LSerni

Reputation: 57438

You need to update the text content of the tag; you can do this with e.g. jQuery at runtime. This is the preferred way if some tags, and only those, change during the lifetime of the application page, and you do not wish to reload the whole page from scratch.

In this case, from listPagPrinc.php, you can output some Javascript code:

echo <<<JAVA1
<script>
    alert("Ciao, mondo");
</script>
JAVA2;

or in your case using jQuery

echo <<<JAVA2
<script>
    $('#statoPag h3').text("Errore!");
</script>
JAVA2;

Very likely the call will need to be inside a jQuery onDocumentReady function to be sure that it executes.

A better and faster way (and as @arkascha observed, nicer and more robust): you can generate the header from listpagPrinc.php or from a wrapper.

// file listPagPrincWrapper.php, replace your current file

// Ideally listPagPrinc could return a text value. In case it is
// printing it, as seems likely, we capture the output. This way
// we don't neet to modify the existing code.

ob_start();
include('procedure/listPagPrinc.php');
$lpp = ob_get_clean();

// At the end, we do the output part.
print <<<HTML
<div id="statoPag">
    <h3> Stato : {$error}</h3>
</div>
<div class="headerCont">{$lpp}</div>
HTML;

Upvotes: 1

Andy Hoffner
Andy Hoffner

Reputation: 3337

Not as-is, no. Think of these HTML/PHP files like an office printer, once it prints out each line, you can't "go back" and print over it

In this example, all of the first 5 lines are run and effectively "set in stone" before anything is called in procedure/listPagPrinc.php.

If, and this is just speculation, you can't simply include procedure/listPagPrinc.php before you render $error because it also is printing additional HTML, you just need to encapsulate its code in functions as best as possible: One to set the value of $error, and a separate one to output the HTML you need.

Upvotes: 1

Related Questions