I am trying to use a PHP variable in JS and have read tons of questions and answers on many forums and help sites but the explained explanations are not working in the script.
This is the index.js (it works if I use a url in the loadJSON function in place of MyData but this allows the PHP file to be viewed in the browser)
// PHP Variable containing json data
var MyData = "<?php echo $wheelData; ?>";
//load your JSON (you could jQuery if you prefer)
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', MyData, true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
//Call the anonymous function (callback) passing in the response
callback(xobj.responseJSON);
}
};
xobj.send(null);
}
alert(xobj);
// function capture the results
function myResult(e) {
//e is the result object
console.log('Spin Count: ' + e.spinCount + ' - ' + 'Win: ' + e.win + ' - ' + 'Message: ' + e.msg);
// userData object
if(e.userData){
console.log('User defined score: ' + e.userData.score)
}
}
// function to capture errors
function myError(e) {
//e is error object
console.log('Spin Count: ' + e.spinCount + ' - ' + 'Message: ' + e.msg);
}
function myGameEnd(e) {
// e is gameResultsArray
console.log(e);
}
function init() {
loadJSON(function(response) {
// Parse JSON string to an object
var jsonData = JSON.parse(response);
// spin it
var mySpinBtn = document.querySelector('.spinBtn');
//create new instance and pass in the vars object
var myWheel = new Spin2WinWheel();
// button
myWheel.init({data:jsonData, onResult:myResult, onGameEnd:myGameEnd, onError:myError, spinTrigger: mySpinBtn});
});
}
//And finally call it
init();
The most common way I found is to use this (as above)…
var MyData = "<?php echo $wheelData; ?>";
The PHP variable is passed from the controller to the view and is json_encoded in the controller and called in the index.js via script tags in the views index.tpl file.
(I have also tried encoding in the view and in the script all fail the same way) .
But all I am getting is a string being returned and not the json in the PHP variable, like this…
I know the json in the variable is working as validated it.
Why am I getting an echo/print of
var MyData = "<?php echo $wheelData; ?>";
And not the json data? I have tried with and without double quotes and its the same, i tried escaping the php tags like
var MyData = '; echo $wheelData; echo ';
Again same result… What am I missing here?
Any advice appreciated as once this is working I can do my thing in PHP…
Thank you!