0

I have a question regarding a PHP variable being transferred to JavaScript through AJAX/JSON.

I want the var ChronoID to be updated on page load with the value it gets from the AJAX get, from the PHP code. Even though it's working fine in the AJAX, it goes back to undefined and doesn't update the variable for later use.

What am I doing wrong and what is the best way to transfer a PHP variable to Javascript?

-- scripts.js

$(document).ready(function () {
var jsonGet;
var chronoID;
var timeworked;
var startAt;

$.ajax({
        type: "GET",
        url: "detectopencrono.php",
        dataType: "json",
        success: function (response) {
            jsonGet = response;
            console.log(jsonGet); // JSON Array (works)
            var arr = $.map(jsonGet, function (el) {
                return el;
            });
            console.log(arr); // JavaScript Array (after parse, works)
            chronoID = arr[0]; // (works)
            $("#chrono" + chronoID + "").show(200);   
            console.log(chronoID); // Works, shows value
        }
    });

console.log(chronoID); // Undefined (doesn't work)

});

-- detectopencrono.php

<?php 
    include("connection.php"); 
    session_start();

    /*if (isset($_POST['projectname'], $_POST['startyear'], $_POST['startmonth'], $_POST['startday'], $_POST['deadyear'], $_POST['deadmonth'], $_POST['deadday'], $_POST['lider'], $_POST['hours'], $_POST['budget'])) 
    {*/

    $iduser = $_SESSION['ID'];

    if(isset($_SESSION['gbsn']))
    {
        $wasopenresult = mysqli_query($mysqli, "SELECT ID, IsGbsn FROM subtask WHERE Crono='Y' AND IsGbsn='Y' AND IDUser='$iduser'")
            or die("Não foi possivel executar o pedido.");
    }
    else
    {
        $wasopenresult = mysqli_query($mysqli, "SELECT ID, IsGbsn FROM subtask WHERE Crono='Y' AND IsGbsn='N' AND IDUser='$iduser'")
            or die("Não foi possivel executar o pedido.");
    }

    if(mysqli_num_rows($wasopenresult)==1)
    {
        $rowwasopen = mysqli_fetch_assoc($wasopenresult);
        $result1 = $rowwasopen['ID'];
        $result2 = $rowwasopen['IsGbsn'];
        echo json_encode(array('userid' => $result1,'gbsn'=> $result2));
        header('Content-Type: application/json'); 
    }
    ?>
4

1 Answer 1

1

The "A" in "AJAX" stands for asynchronous. To simplify what you're doing:

var chronoID;

$.ajax({
    // do something asynchronously, which will happen later
});

console.log(chronoID);

That is, you are trying to log chronoID before it's actually been given a value. Instead, you want to respond to the AJAX call itself for that value.

Which... you are already doing:

success: function (response) {
    // other code which assigns a value to chronoID
    console.log(chronoID);
}

So basically what you have here are simultaneous examples of both working and non-working code attempting to do the same thing. Basically, remove the non-working one and stick with the working one. You already have the code you need.

Sign up to request clarification or add additional context in comments.

4 Comments

But then how can I use chronoID later? It will always be undefined no matter what value it gets assigned inside success ...
@atherir: You can use it later, if by "later" you mean "at a later time". The "not working" line of code you're showing in the question executes before the AJAX call completes. You can use the value any time after the AJAX call completes, since that's where the value is set. Basically, you can't use a value that hasn't been set yet. But any time after it's been set, you can use it. Whatever operations require that value would need to be invoked after that value is set.
And how do I invoke the variable after the AJAX call is complete but not inside success ?
@atherir: The success callback is how you invoke code in response to the AJAX completion. If you have other events on the page, such as responding to mouse clicks and such, then those would also take place afterward (assuming the user doesn't quickly click before the initial AJAX call completes). It's really not clear what the problem is here, perhaps the example you provide is too contrived? Why can't you respond to the AJAX call in the success handler, which you currently demonstrate doing and which works? That is, why can't you use the working code that you already show us?

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.