-1

I have php page which contains two javascript functions like this:

function PregledDokumenta(id)
{
    var info = id.split('-');
    var vrdok = info[0];
    var brdok = info[1];

    $.ajax({
        type: "POST",
        url: "../Php/Dokument/Pregled.php",
        data: { vrDok: vrdok, brDok: brdok },
        success: function(returnedData)
        {
            document.getElementById('Content').innerHTML = returnedData;
            <?php 
                $_SESSION['vrDok'] = vrdok;
                $_SESSION['brDok'] = brdok;
            ?>

    <?php
        $a = $_SESSION['vrDok'];
        echo("alert($a);");
        ?>
        }
    });
}

function UnosNoveStavke()
{
    var vrdok = <?php echo($_SESSION['vrDok']);?>;
    var brdok = <?php echo($_SESSION['brDok']);?>;

    <?php
        $a = $_SESSION['vrDok'];
        echo("alert($a);");
        ?>
    $.ajax({
        type: "POST",
        url: "../Php/Dokument/IzborRobe.php",
        data: {vrDok: vrdok, brDok: brdok},
        success: function(returnedData)
        {
            document.getElementById('Content').innerHTML = returnedData;
        }
    })
}

So when i load page and press button i run PregledDokumenta(id) function. In there i pass some values from id of element and then i echo back some other text and buttons as you can see i alert $_SESSION['vrDok'] to see if it is assigned and it returns value. Then when i click button (about 10 sec after running first function) that i echoed back from first function i run second UnosNoveStavke function. There you can see I again alert to see if $_SESSION return value but it return undefined. Why is that happening?

Aleksa Ristic
  • 2,394
  • 3
  • 23
  • 54

1 Answers1

2

You are very confused regarding how JavaScript and PHP communicate with each other!

For example, with the following code, you are effectively trying to assign JavaScript variables, which you get from an AJAX request, into PHP sections:

<?php 
    $_SESSION['vrDok'] = vrdok;
    $_SESSION['brDok'] = brdok;
?>

This can't work, because all PHP expressions are evaluated before the page even loads.

If you need to save these values in PHP sessions, you have to do it either in the file the AJAX request is sent, in your case Pregled.php, or a PHP file that you include in it.

Angel Politis
  • 10,955
  • 14
  • 48
  • 66