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');
}
?>