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'); 
    }
    ?>
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
joao-m-santos
  • 178
  • 1
  • 2
  • 12
  • 1
    [Have you watched the AJAX request / response in the browser's developer tools? Have you included the jQuery library in the project? Are there any errors reported? Are you running this on a web-server?](http://jayblanchard.net/basics_of_jquery_ajax.html) – Jay Blanchard Jul 17 '17 at 16:43
  • 1
    [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Jul 17 '17 at 16:44
  • 1
    Because `success` is a callback being called after the AJAX completes, I think that your second `console.log()` is actually being run before that callback is completed, while `chronoID` is still undefined. If you want to do something with `chronoID`, do it inside your success function. – perfect5th Jul 17 '17 at 16:48
  • Javascript executes asynchronously so the ajax request and the second console start at virtually the exact same time, but you aren't updating the value of the variable until it gets a response in the `success` block – Matt Altepeter Jul 17 '17 at 16:50

1 Answers1

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.

David
  • 208,112
  • 36
  • 198
  • 279
  • But then how can I use chronoID later? It will always be undefined no matter what value it gets assigned inside _success_ ... – joao-m-santos Jul 17 '17 at 16:55
  • @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. – David Jul 17 '17 at 16:57
  • And how do I invoke the variable _after_ the AJAX call is complete but not inside _success_ ? – joao-m-santos Jul 17 '17 at 17:01
  • @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? – David Jul 17 '17 at 17:03