Javascript scope and sequentiality issue - javascript

I want to get an id from the query and display it in html.
I want to keep things in separate javascript files, because in the future, it will retrieve a json from php and will filter it based on some checkboxes, radio buttons, etc. and then display the result.
In this moment, I get a blank page, and the id value is not shown, so I'm doing something wrong.
http://localhost:10600/js1/index.php?id=5
index.php
<html>
<head>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>
<div class="results"></div>
</body>
</html>
<script type="text/javascript" src="config.js"></script>
<script type="text/javascript" src="display.js"></script>
<script type="text/javascript" src="sequence.js"></script>
config.js
function getId() {
id = "<?php echo $_GET['id']; ?>";
}
display.js
function updateHtml() {
window.onload = function() {
document.querySelector('.results').innerHTML = id;
}
}
sequence.js
function seq()
{
getId();
updateHtml();
}
seq();

Please try the following:
index.php
<html>
<head>
<script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js'></script>
</head>
<body>
<div class="results"></div>
</body>
</html>
<script type="text/javascript">
var id;
function getId() {
id = "<?php echo $_GET['id']; ?>";
}
</script>
<script type="text/javascript" src="display.js"></script>
<script type="text/javascript" src="sequence.js"></script>

function getParameters() {
var url_params = window.location.search.substring(1); // Removing characters : ?
var params = url_params.split("&");
var res = {};
for (var i = 0, c = params.length; i < c; i++) {
var split = params[i].split("=");
res[split[0]] = split[1];
}
return res;
}
Returns an object {param: value}

In index.php within body you can do like this one
<input type="hidden" name="hidden_id" id="hidden_id" value="<?=$_GET['id']?>">
In JS :
If you are using jQuery,then you should do like this one.
$(document).ready(){
var strHiddenId = $("#hidden_id").val();
$(".results").html(strHiddenId);
}

Related

How should I access a variable from javascript in PHP to perform some actions?

I have a file named sample.php, in which I have some JS code, and some PHP code. This is some sort of sample snippet of the code I have :
<!DOCTYPE html>
<html lang="en">
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<head>
<script type="text/javascript">
var ThunkableWebviewerExtension = {
receiveMessage: function(fxn) {
var callbackFunction = function(event) {
if (typeof fxn === 'function') {
fxn(event.data)
}
};
document.addEventListener('message', callbackFunction, false);
window.addEventListener('message', callbackFunction, false);
}
}
</script>
</head>
<body>
<script type="text/javascript">
var value;
ThunkableWebviewerExtension.receiveMessage(function(message) {
value = message;
});
//sending the value with ajax
$.ajax({
url : "./sample.php", //same file
method : "GET",
data: {"name": value},
success : (res) => {
console.log(value);
},
error : (res) => {
console.log(res);
}
})
</script>
<?php
echo $_GET['name'];
?>
</body>
</html>
The problem is the PHP code doesn't print anything - Are there any error/bug I need to fix? Or is there a better method for accessing a JS variable in PHP?
Thanks! :)
Here's how you can access PHP code within in a <script> (without using AJAX):
<?php
echo"<script>";
include ('javascriptStuff.js');
echo'let x = '.json_encode($phpVariable).';';
echo"</script>";
?>

Javascript src with variable

I need to embed a player by the following code:
<script type="text/javascript" src=***the url***></script>
A part in the url is the ID which is retrieved from mySQL database. I know that the string concatenation can't be directly handled in the src, so I add the function in the beginning:
<head>
<script>
function call(url)
{
var script = document.createElement('script');
script.type="text/javascript";
script.src = url;
document.body.appendChild(script);
}
</script>
</head>
In the body,
<body>
<?php ***...to retrieve ID***?>
<script type="text/javascript">
var videoid = "<?php echo $id; ?>"; //Transfer ID to javascript
var url="http://......"+videoid; //Url string finished
call(url); //Function call
</script>
Now the script is appended, but I can't see the player. Why?

How to reflect JStree changes to the original XML?

I'm using JStree to display an XML file, and after displaying it the user can create, rename, or delete some nodes, and sor sure these changes appear only on the displayed xml and not reflected on the original file, I want to know how to reflect this changes to the original XML fie back after clicking like a submit button, or at least how to get the data changed.
Update
The code:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>menu-editor</title>
<script type="text/javascript" src="src/jquery-1.10.1.min.js"></script>
<script type="text/javascript" src="src/jstree/jquery.cookie.js"></script>
<script type="text/javascript" src="src/jstree/jquery.hotkeys.js"></script>
<script type="text/javascript" src="src/jstree/jquery.jstree.js"></script>
<link href="themes/!style.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="src/jstree/!script.js"></script>
<script type="text/javascript" src="src/UIMTreeProcessor.js"></script>
<style type="text/css">
.
.
.
//css stuff
</style>
</head>
<body>
<div id="dummy"></div>
<div id="mylist">
<li id='root'><a href='#'>Root node</a><ul><li><a href='#'>Child node</a></li></ul></li>
</div>
<div id="submit" class="submit_btn">Submit</div>
</body>
<script type="text/javascript" class="source below">
var _url = "cafe.xml";
var _uimTree = null;
$(function () {
getTopContent();
});
getTopContent = function(){
$.ajax({
type: "GET",
url: _url,
dataType:"xml",
cache: false,
beforeSend:function(){
//do something before send
},
success: function(data){
processXML(data);
},
error:function(e){
alert("Error: "+e);
}
});
}
processXML = function(root){
_uimTree = new UIMTreeProcessor(root, $("#mylist"));
_uimTree.doProcess();
}
$('#submit').on('click',function(){
//alert the entire XML after edits via (getXML)
});
</script>
And the UIMtreeprocessor Library code
function UIMTreeProcessor(data, treeEl) {
this.data = data;
this.treeEl = treeEl;
}
UIMTreeProcessor.prototype.initTree = function(data){
this.treeEl.jstree({
"json_data" : {
"data":data,
"progressive_render":"true"
},
"plugins" : ["themes","json_data","ui","crrm","cookies","dnd","search","types","hotkeys","contextmenu"],
"core":{"animation":0}
});
}
UIMTreeProcessor.prototype.doProcess = function(){
//Find root:
var _root = $(this.data).children(':first-child');
var _a_feed = new Array();
this.vsTraverse($(_root), _a_feed);
var _treedata = [{"data":_root[0].nodeName,"children":_a_feed, "state":"open"}];
this.initTree(_treedata);
}
UIMTreeProcessor.prototype.vsTraverse = function(node, arr){
var _ch = $(node).children();
for(var i=0; i<_ch.length; i++){
var _vsArr = new Array();
this.vsTraverse(_ch[i], _vsArr);
var _a_att = this.vsTraverseAtt(_ch[i]);
if(null!=_a_att){
_vsArr.push([{"data":"Attributes "+"["+_ch[i].nodeName+"]","children":_a_att, attr : { "class" : "uim_attr"}}]);
}
if(null!=_ch[i].firstChild && 3==_ch[i].firstChild.nodeType){
arr.push([{"data":_ch[i].nodeName + ": " + _ch[i].firstChild.textContent,"children":_vsArr, "state":"open"}]);
}else{
arr.push([{"data":_ch[i].nodeName,"children":_vsArr, "state":"open"}]);
}
}
}
UIMTreeProcessor.prototype.vsTraverseAtt = function(node){
var _a_atts = null;
if(null!=node.attributes && node.attributes.length > 0){
_a_atts = new Array();
for(var i=0; i<node.attributes.length; i++){
_a_atts.push(node.attributes[i].nodeName + ":" + node.attributes[i].nodeValue);
}
}
return _a_atts;
}
Edit: I was really wrong in my original answer.
There is a get_xml method in the xml_data plugin, which is supposed to do what you describe. I have not tested it myself, but if it's anything like json_data.getJSON, the output will contain all kinds of JStree metadata which you will not want to put back into your XML.

window onload conflicts with body onload javascript

My client puts our below JS code in his website in the <head> and is complaining our tags are not firing. Below is the sample code from client:
<html>
<head>
<script type="text/javascript">
function create() {
try {
var baseURL = "https://serv2ssl.vizury.com/analyze/analyze.php?account_id=VIZVRM1125";
var analyze = document.createElement("iframe");
analyze.src = baseURL;
var node = document.getElementsByTagName("script")[0];
node.parentNode.insertBefore(analyze, node);
} catch (i) {
}
}
var existing = window.onload;
window.onload = function() {
if (existing) {
existing();
}
create();
}
</script>
</head>
<body onload="javascript:clientfunction();">
<script type="text/javascript">
function clientfunction()
{
//client code is replcad here
document.write("Hello testing");
}
</script>
</body>
</html>
On page Load clientfunction() is calling, our create() function is not firing.
Please can anybody help me why our tags are not firing and what is the alternative solution for this issue?
copy paste and check running following
<html>
<head>
<script type="text/javascript">
function create() {
alert("Gdfg");
try {
var baseURL = "https://serv2ssl.vizury.com/analyze/analyze.php?account_id=VIZVRM1125";
var analyze = document.createElement("iframe");
analyze.src = baseURL;
var node = document.getElementsByTagName("script")[0];
node.parentNode.insertBefore(analyze, node);
} catch (i) {
}
}
window.onload=create;
window.onload=clientfunction;
</script>
</head>
<body onload="clientfunction(); create()">
<script type="text/javascript">
function clientfunction()
{
alert("fdsfsdf");
//client code is replcad here
document.write("Hello testing");
}
</script>
</body>
</html>

Javascript not loaded correcly order?

I have a webpage where I load some javascript files in header. Some subpage will load aditional javascript files. On the main page everything is working just fine but on the subpage I get alot of exceptions like this :
Uncaught TypeError: Property '$' of object [object Object] is not a
function
I can see that this exception occurs in details.js, voteHandler.js and 4 times in the HTML page itself. The exception is always thrown on this line :
$("document").ready(function () {
This is how the main page that works looks like :
<head>
<script type="text/javascript" src=/Scripts/jquery-1.7.1.min.js></script>
<script type="text/javascript">
//URL for voting
var _postVoteUrl = 'http://localhost:5215/Post/Vote'
//URL for tags
var _tagsUrl = 'http://localhost:5215/Post/Tags'
//Keep track of if a cascading is loading, if so, cancel submits
var cascadingControlLoading = false;
window.latestClick = '';
function IsNotDblClick(objectID) {
if (window.latestClick != objectID &&
!cascadingControlLoading) {
window.latestClick = objectID;
return true;
} else {
return false;
}
}
$(document).ready(function () {
if($('#rightCon').text().trim().length < 1)
{$('#rightCon').hide();}
});
</script>
<script type="text/javascript" src=/Scripts/jquery-ui-1.8.20.min.js>"></script>
<script type="text/javascript" src=/Scripts/jquery.elastic.source.js></script>
<script type="text/javascript" src=/Scripts/jquery.validate.min.js></script>
<script type="text/javascript" src=/Scripts/jquery.validate.unobtrusive.min.js></script>
<script type="text/javascript" src=/Scripts/jquery.qtip.min.js></script>
<script type="text/javascript" src=/Scripts/formhandler.js></script>
<script type="text/javascript" src=/Scripts/taghandler.js></script>
<script src="/Scripts/voteHandler.js"></script>
<script type="text/javascript" src=/Scripts/select2.min.js %>"></script>
<script>
function TogglePostCon() {
$('#postListEditorCon').toggle();
}
SetupTagTextBox("txtTagBox", false);
SetupTagTextBoxPersonalTag("txtPersonalTagBox", true);
SetupTagTextBoxPersonalTag("txtPersonalIgnoreTagBox", true);
</script>
<script src="/Scripts/modernizr-2.5.3.js"></script>
</head>
And this is the subpage that throws the exceptions :
<head>
<script type="text/javascript" src=/Scripts/jquery-1.7.1.min.js></script>
<script type="text/javascript">
//URL for voting
var _postVoteUrl = 'http://localhost:5215/Post/Vote'
//URL for tags
var _tagsUrl = 'http://localhost:5215/Post/Tags'
//Keep track of if a cascading is loading, if so, cancel submits
var cascadingControlLoading = false;
window.latestClick = '';
function IsNotDblClick(objectID) {
if (window.latestClick != objectID &&
!cascadingControlLoading) {
window.latestClick = objectID;
return true;
} else {
return false;
}
}
$(document).ready(function () {
if($('#rightCon').text().trim().length < 1)
{$('#rightCon').hide();}
});
</script>
<script type="text/javascript" src=/Scripts/jquery-ui-1.8.20.min.js>"></script>
<script type="text/javascript" src=/Scripts/jquery.elastic.source.js></script>
<script type="text/javascript" src=/Scripts/jquery.validate.min.js></script>
<script type="text/javascript" src=/Scripts/jquery.validate.unobtrusive.min.js></script>
<script type="text/javascript" src=/Scripts/jquery.qtip.min.js></script>
<script type="text/javascript" src=/Scripts/formhandler.js></script>
<script type="text/javascript" src=/Scripts/taghandler.js></script>
<script src="/Scripts/details.js"></script>
<script src="/Scripts/voteHandler.js"></script>
<script>
$(function () {
//Google +1
$.getScript("http://apis.google.com/js/plusone.js", null, true);
//Twitter
$.getScript("http://platform.twitter.com/widgets.js", null, true);
//Facebook
$.getScript("http://connect.facebook.net/en_US/all.js#xfbml=1", function () {
$('body').append('<div id="fb-root"></div>');
FB.init({ status: true, cookie: true, xfbml: true });
}, true);
});
</script>
<script src="/Scripts/modernizr-2.5.3.js"></script>
</head>
I hade some of the scripts loaded at the bottom of the body before and this did not generate the exception but from what I read this is not a recomended way to go.
So why is my subpage generating these exceptions?
In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used, i.e.
jQuery(document).ready(function ($) {
By including the $ in parenthesis after the function call you can then use this shortcut within the code block.
Replace your code
$(document).ready(function () {
if($('#rightCon').text().trim().length < 1)
{$('#rightCon').hide();}
});
with this
jQuery(document).ready(function ($) {
if($('#rightCon').text().trim().length < 1)
{$('#rightCon').hide();}
});

Categories

Resources