I have two script files - one is perl-cgi and the other is javascript. Inside the cgi script I have written the Javascript function for retrieving data from a text file (using ajax). I then pass the contents of the data into another function called main_function(). This writes into the javascript file (seq_new.js). When I load the page, the console.log reports main_function was not defined. Then I refresh the page and the result displays. I don't know why it behaves this way.
The Perl script as follows:
#!/usr/bin/perl
print "Content-type:text/html\n\n";
use CGI;
my $a= new CGI;
my $processId = $a->param("processId");
.
.
my $file_path = "/$processId/$file_name[1]";
print <<HTML;
<!DOCTYPE html>
<html>
<head>
<title>RepEx - Result</title>
<script type="text/javascript" src="/min.js"></script>
</head>
<body>
<script>
file_load("$file_path","$filename");
function file_load(f1,f2)
{
var fileNm = f2;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (xhttp.readyState == 4 && xhttp.status == 200)
{
var pt = xhttp.responseText;
main_function(pt,fileNm,"$file_path",$file_cnt,"$head_st");
}
};
xhttp.open("GET", f1, true);
xhttp.send();
}
</script>
<script type="text/javascript" charset="utf-8" src='/seq_new.js'> </script>
</body>
</html>
My javascript file contains this:
function main_function (a,file_seq,main_file,fle_cnt,header_set)
{
.
..
}
The problem I am encountering
Loading the page for the first time, the console.log reports that the main_function was not defined and no results are displayed. After refreshing the page (by pressing F5 or clicking the reload button), the result is displayed.
Related
I am using google maps API to build my own world.
The problem I am running in to is that the data number of markers/locations cause the page to become unresponsive.
So I believe; and could be wrong; that the solution is to call only the markers/location that are with in the bounds(that is to say visible on the window) and at the zoom level.
I was thinking that if i get the bounds of the window and zoom level and pass that to a php script that would build the js marker function and then call that function.
However i have tried a rudimentary scripts that looks like it returns the function but it does not activate the script.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("script").innerHTML = this.responseText;
eval(this.responseText);
}
};
xhttp.open("GET", "fjack.php", true);
xhttp.send();
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<div onclick="loadDoc();"> click </div>
<div id="script"></div>
<div id="demo"></div>
</body>
</html>
this is the php script:
<?php
echo "<script>";
echo "function me(){
document.getElementById(\"demo\").innerHTML=\"ITS WORKING\";
}
me();";
echo "</script>";
?>
I have tried eval() but that did nothing.
You're almost there, just return .js code from the server without <script> tags and evaluate the string using eval, so you'll have to change this:
if (this.readyState == 4 && this.status == 200) {
document.getElementById("script").innerHTML = this.responseText;
eval(this.responseText);
}
with this:
if (this.readyState == 4 && this.status == 200) {
eval(this.responseText);
return;
}
and the server(php script) response looks like this:
<?php
echo "function me(){
console.log('hello world!');
}
me();";
It works but using eval() is not the best choise; I recommend to use a function object for this(new Function('dynamic content -server response here')) or even better, a js module loader, which check your module's dependencies and dinamically loads the required js files in the right order, in the header section, using <script> tags, no need for XHR requests, as it was already mentioned in a previous reply to your question. Take a look at http://requirejs.org
I have:
test.json - contains the content to be uploaded into the HTML page
test.js - contains the function that sends an Ajax request to the JSON file, parses, compiles with Handelbars Temlate and puts the content into the HTML page (using innerHTTML).
addcontent.js - javascript file which calls the function from the test.js file
index.html - contains the Handlebars Template, Div
where the content will be placed after processing, and a link to the
addcontent.js.
Everything works, if inside index.html there is a link directly to test.js.
Everything works if I wrap the code inside test.js in a function with variables and call this function in the same file.
But if I call this function from addcontent.js and connecting addcontent.js and test.js using commonJS module approach, it does not work.
Probably I made a syntax mistake somewhere, but I don't see it.
P.S. I use NodeJS, NPM, HTTP-server and I'm going to merge all javascript files using browserify after all
//test.js
module.exports = function addContent (jsonDir, templId, finId){
function sendGet(callback) {
/* create an AJAX request using XMLHttpRequest*/
var xhr = new XMLHttpRequest();
/*reference json url taken from: http://www.jsontest.com/*/
/* Specify the type of request by using XMLHttpRequest "open",
here 'GET'(argument one) refers to request type
"http://date.jsontest.com/" (argument two) refers to JSON file location*/
xhr.open('GET', jsonDir);
/*Using onload event handler you can check status of your request*/
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
alert(xhr.statusText);
}
};
/*Using onerror event handler you can check error state, if your request failed to get the data*/
xhr.onerror = function () {
alert("Network Error");
};
/*send the request to server*/
xhr.send();
}
//For template-1
var dateTemplate = document.getElementById(templId).innerHTML;
var template = Handlebars.compile(dateTemplate);
sendGet(function (response) {
document.getElementById(finId).innerHTML += template(response);
})
}
/* test.json */
{
"time": "03:47:36 PM",
"milliseconds_since_epoch": 1471794456318,
"date": "08-21-2016-123",
"test": "lalala 123"
}
/* addcontent.js */
var addContent = require('./test');
addContent("json/test.json", "date-template", 'testData');
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="handlebars-v4.0.5(2).js"></script>
</head>
<body>
<!-- template-1 -->
<div id="testData"></div>
<script id="date-template" type="text/x-handlebars-template">
Date:<span> <b>{{date}}</b> </span> <br/> Time: <span><b>{{time}}</b>
</span>
</script>
<script type="text/javascript" src="addcontext.js"></script>
</body>
</html>
I'm a beginner in HTML, PHP and web programming in general.
My first project is a PHP page connected to a MySQL database. I am using this javascript code to send information to another PHP page :
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>ERP</title>
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css.css" />
<script type="text/javascript" src="oXHR.js"></script>
<script type="text/javascript"></script>
<script>
function DelRow(callback)
{
alert("FIRSTALERT");
var xhr = XMLHttpRequest();
alert("SecondALERT");
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0))
{
callback(xhr.responseText);
}
};
var Comp = encodeURIComponent(document.getElementById("ComboBoxCompany").value);
xhr.open("GET", "DeleteRow.php?Comp=" + Comp, true);
xhr.send(null);
}
function readData(sData)
{
alert(sData);
};
</script>
</head>
The function is called by this bad boy right here :
<input class="btn btn-primary" type="button" value="Confirmer" name="ConfirmDel" onclick="DelRow(readData)" />
If you look at my javascript code, I've put 2 alert. The first one is appearing, but the second one is not. It seems like the getXMLHttpRequest is not working.
I'm using Google Chrome. I've found some thread saying that I need to execute this command line :
C:\Users\User>C:\Program Files (x86)\Google\Chrome\Application
--allow-file
-access-from-files
But it changed nothing.
I'm in the dark and looking for some insight.
If you aren't getting the second alert, you can pretty much rule out everything that comes after the second alert because none of it is going to be executed. This makes the problem VERY easy to track down, because it must be this line:
var xhr = XMLHttpRequest();
You're simply missing the new keyword.
var xhr = new XMLHttpRequest();
I want to load js on the fly which is happening but the one more js file which is included in index is loading before (file i am loading dynamically) is there way to fix the order
i am adding global.js dynamically and i want variable declared in global.js shoud be initialised before dynamicjs.DynamicJs is loaded
------------- Index.html -------------
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.commons"
data-sap-ui-theme="sap_goldreflection" >
</script>
<!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->
<script src="js/dyn.js"></script>
<script></script>
<script>
sap.ui.localResources("dynamicjs");
var view = sap.ui.view({id:"idDynamicJs1", viewName:"dynamicjs.DynamicJs", type:sap.ui.core.mvc.ViewType.JS});
view.placeAt("content");
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>
function loadScript(url){
var xhrObj = createXMLHTTPObject();
// open and send a synchronous request
xhrObj.open('GET', url, false);
xhrObj.send('');
var e = document.getElementsByTagName("script")[1];
var d = document.createElement('script');
d.src = url;
d.type = 'text/javascript';
d.async = false;
d.defer = false;
e.parentNode.insertBefore(d,e);
}
function addScriptDynamically(){
loadScript('js/global.js'+'?scheme=12345');
}
function createXMLHTTPObject(){
var xmlhttp=new XMLHttpRequest();
if( typeof xmlhttp == 'undefined' || xmlhttp == null )
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlhttp;
}
/*call function */
addScriptDynamically();
Why won't you try to load script with jQuery.getScript()
http://api.jquery.com/jQuery.getScript/
If you want compatibility with other libraries like prototype or mootools you can set jQuery.noConflict()
I am following along with a tutorial book on AJAX and I seem to be failing on some basic concept.
Here is the HTML and Javascript I am using (this is saved as ajax.html on my godaddy hosted web server):
<html>
<head>
<title>AJAX Example</title>
<script language="javascript">
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function getData(dataSource, divID) {
if (XMLHttpRequestObject) {
var obj = document.getElementById(divID);
XMLHttpRequestObject.open("GET", dataSource);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readystate == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
</script>
</head>
<body>
<H1>This is an AJAX Example</H1>
<form>
<input type="button" value="Fetch the Message" onclick="getData('data.txt', 'targetDiv')">
</form>
<div id="targetDiv">
<p>The fetched message is supposed to appear here...</p>
</div>
</body>
</html>
And is the contents of data.txt (saved in the same directory as ajax.html):
<p>This is some text in a file that I am using to be</p>
<p>queried with an ajax process to display dynamically.</p>
The problem is that nothing happens when I press the button on the page. I have tried to step through the Javascript using Chrome's developer tools and I see a DOMException:
.
Can someone please point out if there is an issue with this javascript, or point me in the right direction to deal with the DOMException that I am seeing?
using the answer found here I read that my readystate should really be readyState. Changing that fixed my problem.