I am using caledar.js file by adding it to html code.
Till server migration, it was working perfectly. But now Instead of showing calendar, calendar.js code is shown...
My code to add calendar.js is as follows :
<div id="Calendar" src="calendar.php"> </div>
<div id="Events" src="events.php"> </div>
<script language="javascript" TYPE="text/javascript" src="calendar.js"></script>
Now instead of showing calendar, calendar.js code is shown on webpage as follows (eg):
var bustcachevar=1; //bust potential caching of external pages after initial request? (1=yes, 0=no)
var bustcacheparameter="";
function createRequestObject(){
try {
xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert('Sorry, but your browser doesn\'t support XMLHttpRequest.');
};
return xmlhttp;
};
function ajaxpage(url, containerid){
var page_request = createRequestObject();
if (bustcachevar) bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
}
function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1)) {
document.getElementById(containerid).innerHTML=page_request.responseText;
};
}
function LoadMonth(month, year) {
ajaxpage("calendar.php?month="+month+"&year="+year, "Calendar")
}
function LoadEvents(date) {
ajaxpage("events.php?date="+date, "Events")
}
LoadMonth();
I also tried adding following code in css file
script{
display:none;
}
head{
display:none;
}
Is there any need to change in above calendar.js code as server is migrated from php5.3 to php5.4 ?
Here I Got Solution. I am posting it as an answer so others may get answer if they are facing same issue...
I added following code in my root .htaccess file and now it works....
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [QSA,L]
Related
Looking for advise on whether is it possible to have a footer.html and duplicate it to all pages without using PHP.
I know I can use include("footer.php"), but all my pages are in HTML now and I will have to change all css paths.
I read up w3school on how to use w3-include-html & javascript. However I realize the javascript is lagging every pages, making page loading longer.
Is there any other option?
<body>
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/* Loop through a collection of all HTML elements: */
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/* Make an HTTP request using the attribute value as the file name: */
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/* Remove the attribute, and call this function once more: */
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/* Exit the function: */
return;
}
}
}
</script>
<div w3-include-html="footer.html"></div>
<script>
includeHTML();
</script>
You could think different, but I don't know if it is, what you want, because the architecture of your application will grow up / become a littlebit ugly.
You define a php-script, that is loading your static html and appends the php-code you want. Then you need a rewrite rule, to get the script as the center of your tiny html-universe ;-)
An example, that should work on an apache with rewrite-mod enabled.
Mention, that you create this directory-structure on your server:
.../.htaccess
.../index.php <<< this renders the "header", content of your html-files and last footer
.../html-pages <<< place your files here
Place an .htaccess in the root-folder:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond "%{REQUEST_URI}" !^.*/index\.php$
RewriteRule ^(?!.*index\.php)(.*)$ /index.php/$1 [QSA,L]
Place an index.php in the samefolder:
<?php
... here could be your header-code
define ('PAGES_DIR', __DIR__ . '/html-pages')
define ('DEFAULT_PAGE', 'index.html')
// we need to handle virtual pathes
$requestPath = false;
if (isset($_SERVER['PATH_INFO'])) {
$requestPath = $_SERVER['PATH_INFO'];
} elseif (isset($_SERVER['ORIG_PATH_INFO']) && strpos($_SERVER['ORIG_PATH_INFO'], basename(__FILE__)) === FALSE) {
$requestPath = $_SERVER['ORIG_PATH_INFO'];
}
if ($requestPath == '/' || strlen(trim($requestPath)) == 0 || strlen(trim($requestPath)) == basename(__FILE__)) {
$requestPath = DEFAULT_PAGE;
}
// this sends the content of your file to the browser
#readfile(PAGES_DIR . "/$requestPath");
... now your footer-code
And your html-files needs be placed into the "html-pages"-folder.
If you have done, your server should handle http://domain.tld/bla-fasel-blub.html as followed:
redirect the not existing path to index.php
RewriteRule ^(?!.index.php)(.)$ /index.php/$1 [QSA,L]
render the header
read the requested html-file (the $1 of the RewriteRule will be "bla-fasel-blub.html" and becomes value of "$requestPath") and send the content to the browser
render the rest of index.php (the footer or whatever)
I hope it helps, generating an idea for your problem.
So this is our scenario... First thing we do is, we append a piece of javascript code which adds external script to document like this:
(function() {
var e = document.createElement('script'); e.type = 'text/javascript'; e.async = true; e.src = 'http://blabla.com/script.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(e, s);
})();
Then in script.js following happens:
function ajaxCall() {
//... some script to send ajax request which calls createDiv() after success
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
createDiv(xmlhttp.responseText);
}
};
xmlhttp.open("GET","http://blabla.com/api/");
xmlhttp.send();
}
function parseResponse(response) {
var parser = new DOMParser();
var dom = parser.parseFromString(response, "text/html");
return dom;
}
function createDiv(responsetext)
{
var dom = parseResponse(responsetext);
var _ws = dom.getElementById('styles');
var h = document.getElementsByTagName('head')[0];
h.appendChild(document.importNode(_ws, true));
var _jr = dom.getElementById('script1').outerHTML;
var _vc = dom.getElementById('script2').outerHTML;
var _rv = dom.getElementById('script3').outerHTML;
var _rw = dom.getElementById('my_div');
var _b = document.getElementsByTagName('body')[0];
var _d = document.createElement('div'); _d.id = 'just_id';
_d.innerHTML = _jr + _vc + _rv;
_d.appendChild(document.importNode(_rw, true));
_b.appendChild(_d);
}
ajaxCall();
Everything works fine, script's and a div are being appended as expected and where expected, but appended script doesn't get executed and doesn't affect appended div. Why is that? And how can I make it execute? We also don't get any warnings/errors in console. Using latest firefox.
EDIT 1
Comment: The example script you showed just defines function, but it never actually calls them
It actually calls a function which makes an ajax request, please check edited code snippet.
EDIT 2
Comment: Have you tried to put the logic in a callback and then call it in createDiv? May be add some logs to test if its getting called but it unable to find div
I just tried console.log('hello world'); call in one of scripts which are being appended by createDiv() function, but it does nothing.
EDIT 3
For more details. When page is loaded, I can see
<script type="text/javascript" id="script1" src="http://blabla.com/script1.js"></script>
<script type="text/javascript" id="script2" src="http://blabla.com/script2.js"></script>
<script type="text/javascript" id="script3" src="http://blabla.com/script3.js"></script>
<div id="just_id">Content here</div>
In DOM-Inspector and as mentioned above, there is console.log('hello world'); to test it, but it doesnt get executed.
EDIT 4
Added some CSS through createDiv() function to document's <head></head> and it affects my div with id 'just_id'. JS still isn't working.
EDIT 5
Also tried to append inline javascript instead of external one in my function, but still no success. Can see following in DOM-Inspector, but code doesn't log anything.
<script type="text/javascript">
console.log('test');
</script>
EDIT 6
I also tried to import nodes from as suggested here
This method is not allowed to move nodes between different documents. If you want to append node from a different document the document.importNode() method must be used.
and also tried to changed order. 1.css 2.div 3.js like this but still no success... Anyone has an idea what is going on here?
Check the code above
EDIT 7
As suggested in How do you execute a dynamically loaded JavaScript block? I set innerHTML of my div to scripts + content and then appended to DOM like this:
Check the code above
But still without any success.
EDIT 8
Added ajax function code. 3rd paramter in xmlhttp.open("GET","http://blabla.com/api/"); true (asynchronous) and false (synchronous) already tried. Still no success.
EDIT 9
function createDiv() as suggested in answer:
var dom = parseResponse(responsetext);
var _jr = dom.getElementById('script1'); //<script> tag with src attribute
var _vc = dom.getElementById('script2'); //inline <script> for test purposes only, it should actualy be external script also
var _rv = dom.getElementById('script3'); //inline <script>
var _rw = dom.getElementById('external_div');
var _b = document.getElementsByTagName('body')[0];
var _d = document.createElement('div'); _d.id = 'internal_div';
_d.appendChild(document.importNode(_rw, true));
_d.appendChild(document.importNode(_jr, true));
_d.appendChild(document.importNode(_rv, true)); //without second parameter TRUE, I dont get script content
_d.appendChild(document.importNode(_vc, true)); //without second parameter TRUE, I dont get script content
_b.appendChild(_d);
Doesn't work. Work's only if I take innerHTML of inline scripts from other document, create elements like suggested in answer, set their innerHTML and then append do current document. External script's wont load at all.
EDIT 10
.htaccess from localhost... :
<Files *.html>
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Files>
<Files *.php>
Order Deny,Allow
Deny from all
Allow from 127.0.0.1
</Files>
<Files index.php>
Order Allow,Deny
Allow from all
</Files>
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /page1/
#RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.+)$ index.php?url=$1 [QSA,L]
</IfModule>
.htaccess from 192.*** ... :
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /direktexpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /page2/index.php [L]
</IfModule>
# END WordPress
EDIT 11
So I am probably going to give bounty #Drakes, just for the effort and his spent time on my question and going to show some screenshots what is going on. It is definitely firefox bug, I just tested on chrome and it works.
1st picture: source code of 192.168.2.197/testing/whatever/etc. .htaccess remains the same as in example above
2nd picture is source code for script.js, which is being loaded on 192.168.2.197/testing/whatever/etc. .htaccess remains the same as in example above:
3rd picture is a screenshot of inspector, how does my dom look like:
4th picture.... nothing happens. Just a warning which has nothing to do with my problem (I hope so), because even when I remove all scripts, it still appears.
Is it a firefox bug?
The problem is that the code above is mixing appendChild with innerHTML. It's not intuitively obvious that the two perform differently in some cases. The former allows newly inserted script nodes to be executed as they are attached to the DOM. The latter doesn't. This has been a head-scratcher for many people. Kindly Google "script and innerHTML" and you will find that you are not alone facing this similar problem.
If you (1) change
_d.innerHTML = _jr + _vc + _rv
to
_d.appendChild(document.importNode(_jr));
_d.appendChild(document.importNode(_vc));
_d.appendChild(document.importNode(_rv));
and additionally (2) change
var _jr = dom.getElementById('script1').outerHTML;
var _vc = dom.getElementById('script2').outerHTML;
var _rv = dom.getElementById('script3').outerHTML;
to
var _jr = dom.getElementById('script1');
var _vc = dom.getElementById('script2');
var _rv = dom.getElementById('script3');
then your scripts will get executed. Here is a demonstration:
var b = document.getElementsByTagName('body')[0];
/* Works */
var s1 = document.createElement('script');
s1.innerHTML = "console.log('I will execute')";
b.appendChild(s1);
/* Fails */
var s2 = document.createElement('script');
s2.innerHTML = "while(1){alert('Do not worry! I will not execute');}";
b.innerHTML = s2.outerHTML;
console.log("It didn't execute");
Tested
I ran the OP's code on my server to replicate the problem as best I can. Given the supplied code I can make it work as intended on my server. I only changed the AJAX URL from http://blabla.com/api/ to api.html and supplied my own file as none was provided by the OP, but I pieced together what it should contain from the OP's JavaScript). Here are sample results:
index.html
<html lang="en">
<body>
<script>
(function() {
var e = document.createElement('script'); e.type = 'text/javascript'; e.async = true; e.src = 'script.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(e, s);
})();
</script>
</body>
</html>
script.js
This is the OP's code modified to my specifications above (using appendChild instead of innerHTML, and the AJAX call returns the contents of api.html below)
function ajaxCall() {
//... some script to send ajax request which calls createDiv() after success
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4&&xmlhttp.status==200){
createDiv(xmlhttp.responseText);
}
};
xmlhttp.open("GET","api.html");
xmlhttp.send();
}
function parseResponse(response) {
var parser = new DOMParser();
var dom = parser.parseFromString(response, "text/html");
return dom;
}
function createDiv(responsetext)
{
var dom = parseResponse(responsetext);
var _ws = dom.getElementById('styles');
var h = document.getElementsByTagName('head')[0];
h.appendChild(document.importNode(_ws, true));
var _jr = dom.getElementById('script1');
var _vc = dom.getElementById('script2');
var _rv = dom.getElementById('script3');
var _rw = dom.getElementById('my_div');
var _b = document.getElementsByTagName('body')[0];
var _d = document.createElement('div'); _d.id = 'just_id';
_d.appendChild(document.importNode(_jr, true));
_d.appendChild(document.importNode(_vc, true));
_d.appendChild(document.importNode(_rv, true));
_d.appendChild(document.importNode(_rw, true));
_b.appendChild(_d);
}
ajaxCall();
api.html (returned by the AJAX call)
<!DOCTYPE html>
<html>
<body>
<style type="text/css" id="styles"></style>
<script type="text/javascript" id="script1" src="script1.js"></script>
<script type="text/javascript" id="script2">console.log("incline script 2")</script>
<script type="text/javascript" id="script3">console.log("incline script 3")</script>
<div id="my_div"></div>
</body>
</html>
script1.js
console.log("src script1");
Here are the DevTools results to show this is working.
The JavaScript of the page has already been parsed, you need to eval the result to put it into the window context.
function evalRequest(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
eval(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send(null);
};
UPDATE : you might need to get the script as text and then eval it )
function getScriptsAsText() {
var div = document.createElement('div');
var scripts = [];
var scriptNodes = document.getElementsByTagName('script');
for (var i = 0, iLen = scriptNodes.length; i < iLen; i++) {
div.appendChild(scriptNodes[i].cloneNode(true));
scripts.push(div.innerHTML);
div.removeChild(div.firstChild);
}
return scripts;
};
The problem is your method is asynchronous not synchronous execution. Meaning the page is still loading while you insert your dynamical scripts.
There are few ways to do so:
The easiest way is to use jQuery $(document).append instead of
document.createElement, if you don't mind using the library.
You can also use jQuery $.getScript.
If you prefer not to include 3rd libraries, you have to think of a way to delay page load while you insert your scripts, something like an alert to creat a prompt window will work, but user experience not so good, think of a more smooth way.
Use XMLHTTPRequest to retrieve your scripts. This is synchronous and I can see you are familiar with it because you are using it in your script already.
Good luck and happy coding.
Have you tried getting the URL of the src file and excuting it with jQuery's getScript() function?
Change your creatediv() function :
var _jr = dom.getElementById('script1').outerHTML;
var srcScript1Left = _jr.split('src="');
srcScript1Right = srcScript1Left[1].split('"');
srcScript1 = srcScript1Right[0];
console.log(srcScript1);
$.getScript(srcScript1, function()
{
// The external script has been executed.
});
EDIT
Similar method in pure Javascript :
var _jr = dom.getElementById('script1').outerHTML;
var srcScript1Left = _jr.split('src="');
srcScript1Right = srcScript1Left[1].split('"');
srcScript1 = srcScript1Right[0];
console.log(srcScript1); // Display the name of the external script file
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
eval(xmlhttp.responseText); // Execute the external script
}
};
xmlhttp.open("GET",srcScript1);
xmlhttp.send();
You are currently loading a script into your page. This happens AFTER the page js was already executed (since is async and usually loading an external resource takes longer than the script execution).
So... basically you have the right function definitions and everything, and calling them from console later should work (I think you already tried that and was fine).
Still, the calls to your functions, even thought they are there won't execute since will not be computed after load.
To work around this, you can create an ajax request to a page that has the script, and in its callback to call whatever function you need to call.
I would say remove async, as the action comes after the initial page load
(function () {
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(CreateScriptTag('http://blabla.com/script.js',true), s);
})();
function CreateScriptTag(src, isAsync) {
var e = document.createElement('script')
e.type = 'text/javascript';
e.async = isAsync;
e.src = src;
return e;
}
function ajaxCall() {
//... some script to send ajax request which calls createDiv() after success
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.open("GET", "http://blabla.com/api/");
xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState === 4 && xmlhttp.status === 200) createDiv(xmlhttp.responseText); };
xmlhttp.send();
}
function parseResponse(response) {
var parser = new DOMParser();
var dom = parser.parseFromString(response, "text/html");
return dom;
}
function createDiv(responsetext) {
var head=document.getElementsByTagName('head')[0],dom = parseResponse(responsetext),_div=document.createElement('div');
head.appendChild(document.importNode(dom.getElementById('styles'), true)); //Assuming stylesheets are working fine.
_div.id = 'just_id';
//div.innerHTML = _script1 + _script2 + _script3;
document.getElementsByTagName('body')[0].appendChild(_div.appendChild(dom.getElementById('my_div')));
head.appendChild(CreateScriptTag(dom.getElementById('script1').getAttribute("src"),true));
head.appendChild(CreateScriptTag(dom.getElementById('script2').getAttribute("src"),true));
head.appendChild(CreateScriptTag(dom.getElementById('script3').getAttribute("src"),true));
/* or another idea;
document.write(_script1 + _script2 + _script3);
*/
}
ajaxCall();
I'm relatively new to JS, and I'm currently working on XMLHttpRequests and closures. My main goal is to (1) have all the xhr code on one .js file (2) pull it in to my index.html page via an src tag, and finally (3) call the xhr function on the index.html page.
The trouble comes when I try to do number 3... I'm able to call my function to trigger the xhr on its native .js file, but not in the index.html.
Here's what I've written so far:
var experiment = function(callback){
return function(destination){
var xhr = new XMLHttpRequest();
xhr.onload = function(){
if(xhr.readyState === 4){
if(xhr.status === 200){
var text = xhr.responseText;
callback(text);
}
else{
console.log(xhr.statusText);
}
}
}
xhr.open("get", destination, true);
xhr.send(null);
}
}
function closure(url){
return experiment(alert)(url);
}
And then, in my index.html page, pull in something like this:
<script type="text/javascript" src="exp.js">
closure("url.com/json");
</script>
But the XHR never fires. What am I doing wrong?
<script type="text/javascript" src="exp.js"/>
<script>
closure("url.com/json");
</script>
I have a really simple ajax script for loading HTML files into a div.
The script looks like:
<head>
<script>
function fetchResults(){
/*$(document).ready(function() {*/
$('#slideshow').cycle({
fx: 'fade',
pager: '#smallnav',
pause: 1,
speed: 1800,
timeout: 3500
});
});
</script>
<script type="text/javascript">
var bustcachevar=1 (1=yes, 0=no)
var loadedobjects=""
var rootdomain="http://"+window.location.hostname
var bustcacheparameter=""
function ajaxpage(url, containerid){
var page_request = false
if (window.XMLHttpRequest) // if Mozilla, Safari etc
page_request = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
page_request = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
page_request = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
page_request.onreadystatechange=function(){
loadpage(page_request, containerid)
}
if (bustcachevar) //if bust caching of external page
bustcacheparameter=(url.indexOf("?")!=-1)? "&"+new Date().getTime() : "?"+new Date().getTime()
page_request.open('GET', url+bustcacheparameter, true)
page_request.send(null)
}
function loadpage(page_request, containerid){
if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
document.getElementById(containerid).innerHTML=page_request.responseText
}
function loadobjs(){
if (!document.getElementById)
return
for (i=0; i<arguments.length; i++){
var file=arguments[i]
var fileref=""
if (loadedobjects.indexOf(file)==-1){
if (file.indexOf(".js")!=-1){ //If object is a js file
fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript");
fileref.setAttribute("src", file);
}
else if (file.indexOf(".css")!=-1){ //If object is a css file
fileref=document.createElement("link")
fileref.setAttribute("rel", "stylesheet");
fileref.setAttribute("type", "text/css");
fileref.setAttribute("href", file);
}
}
if (fileref!=""){
document.getElementsByTagName("head").item(0).appendChild(fileref)
loadedobjects+=file+" "
}
}
}
</script>
</head>
Which loads said HTML file neatly into this div:
<div id="rss">
<script type="text/javascript">
ajaxpage('news.html', 'content');
</script>
</div>
But on one of these HTML files, I have a tiny bit of javascript that won't load in the div, but loads fine when viewing the page directly.
<script src="http://feeds.feedburner.com/xxx/QFMN?format=sigpro" type="text/javascript" ></script>
I know there's an issue with javascript in ajax, but also know there's a work-around.
Being a noob to javascript, I'm not completely sure how to work this.
Any suggestions?
As you're already seem to be using jQuery, please, please, please use jQuery's Ajax methods to do asynchronous requests. All your code can be replaced with something like
$(function () {
$('#container').html($.get('/some/other/url.html'));
});
Here's an example of a link, clicking on which replaces the contents of a div with the result of an AJAX call:
<a class="ajaxLink" href="/some/other/url.html">next</a>
<div id="container">
Hello there
</div>
<script type="text/javascript">
$(function () {
$("a.ajaxLink").click(function () {
$('#container').load($(this).attr('href'));
return false;
});
});
</script>
Note how we cleverly using the href attribute of the link to specify the URL - if the client does not have JavaScript enabled the link will just work as usual.
JQuery documentation on AJAX methods is a valuable source of information. See "loading page fragments" and "script execution" in the documentation of the .load() method for explanation how scripts in the loaded pages are executed.
(also, using jslint or a similar service is immensely helpful)
In fact,
you can't execute a Javascript coming from an ajax call.
You can either do an eval(result) if result is pure javascript, or get the data out of your result by using some jquery like selector.
The main problem is that you shouldn't export your data as html but in JSON or XML
Your code could look like this:
$.ajax({
url: "url",
type: "GET",
datatype: "xml",
cache: false,
success: function(response) {
alert($("Result",response).text())
eval($("Code",response).text())
}
});
with this output:
<?xml version='1.0' encoding='UTF-8'?>
<Result>Hi</Result>
<Code>console.log(1)</Code>
This code will alert Hi and execute the code console.log(1)
I'd like to load/insert an external html page into my web page. Example :
<b>Hello this is my webpage</b>
You can see here an interresting information :
XXXX
Hope you enjoyed
the XXXX should be replaced by a small script (the smaller as possible) that load a page like http://www.mySite.com/myPageToInsert.html
I found the following code with jquery :
<script>$("#testLoad").load("http://www.mySite.com/myPageToInsert.html");</script>
<div id="testLoad"></div>
I would like the same without using an external javascript library as jquery...
There are 2 solutions for this (2 that I know at least):
Iframe -> this one is not so recommended
Send an ajax request to the desired page.
Here is a small script:
<script type="text/javascript">
function createRequestObject() {
var obj;
var browser = navigator.appName;
if (browser == "Microsoft Internet Explorer") {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} else {
obj = new XMLHttpRequest();
}
return obj;
}
function sendReq(req) {
var http = createRequestObject();
http.open('get', req);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if (http.readyState == 4) {
var response = http.responseText;
document.getElementById('setADivWithAnIDWhereYouWantIt').innerHTML=response;
}
}
sendReq('yourpage');
//previously </script> was not visible
</script>
Would an iframe fit the bill?
<b>Hello this is my webpage</b>
You can see here an interresting information :
<iframe id="extFrame" src="http://www.mySite.com/myPageToInsert.html"></iframe>
Hope you enjoyed
You can set the src attribute of your iframe element using plain old javascript to switch out the page for another
I think what you are looking for are in the Jquery source code.
you can see more details here $(document).ready equivalent without jQuery