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)
Related
My problem is that I have a JavaScript function written in a PHP file and when I call it from AJAX request, I want to run that JavaScript function on the main page too after successful AJAX request. As an example, I have a main.html file where I have written an AJAXX function as below.
main.html
<script type="text/javascript">
/* AJAX Function
----------------------------------------------- */
function ajaxFunction() {
var FD = new FormData();
var ajx = new XMLHttpRequest();
ajx.onreadystatechange = function () {
if (ajx.readyState == 4 && ajx.status == 200) {
document.getElementById("mainContent").innerHTML = ajx.responseText;
hello(); //Uncaught ReferenceError: hello is not defined
}
};
ajx.open("POST", "/example.php", true);
ajx.send(FD);
document.getElementById("mainContent").innerHTML = 'Loading...';
return false;
}
</script>
And my example.php file contains a JavaScript function as
example.php
<?php
echo 'Some contents and functions';
echo '<script type="text/javascript">
function hello() {
alert("Hello");
}
</script>';
echo 'Some contents and functions';
?>
Now when I run index.html file, I get Uncaught ReferenceError: hello is not defined error in console rest I am seeing the function body is written on HTML page while inspecting elements on-page.
As I know that innerHTML does not run scripts. So what's the workaround to this problem. You can view the below-linked answer also that I think is related to my question but tried and not working with my problem.
Researched Questions/Answers:
https://stackoverflow.com/a/3250386/3170029
https://stackoverflow.com/a/47614491/3170029
As I shared and you know that innerHTML does not run scripts. so we have to look around it then I found a solution on StackOverflow and I am sharing here with this problem's answer.
main.html
<script type="text/javascript">
/* AJAX Function
----------------------------------------------- */
function ajaxFunction() {
var FD = new FormData();
var ajx = new XMLHttpRequest();
ajx.onreadystatechange = function () {
if (ajx.readyState == 4 && ajx.status == 200) {
setInnerHTML(document.getElementById("mainContent"), ajx.responseText); // does run <script> tags in HTML
hello();
}
};
ajx.open("POST", "/example.php", true);
ajx.send(FD);
document.getElementById("mainContent").innerHTML = 'Loading...';
return false;
}
//https://stackoverflow.com/a/47614491/3170029
var setInnerHTML = function(elm, html) {
elm.innerHTML = html;
Array.from(elm.querySelectorAll("script")).forEach(oldScript => {
const newScript = document.createElement("script");
Array.from(oldScript.attributes)
.forEach(attr => newScript.setAttribute(attr.name, attr.value));
newScript.appendChild(document.createTextNode(oldScript.innerHTML));
oldScript.parentNode.replaceChild(newScript, oldScript);
});
}
</script>
Its concept is clear. When you get the response data from PHP file then first extract <script ..... </script> tags from it and add them in index.html file hear by using createElement('script') and copy all the script to this then you can easily call your function after response data anywhere.
In other words, You can create an executing script element outside of that initial parse using the DOM method of calling createElement('script'), setting its src/content, and adding it to the document. The alternative is what jQuery's getScript90 does.
I am trying to display an html file in my js-code.
It is an ordinary html file that I would like to see. I have already created an IFRAME for this, but somehow I cannot go further...
This is my code fragment:
var controlAddIn = document.getElementById('controlAddIn').src = 'index.html';
So the file I want to call is "index.html". But it is not working.
If I call it in that way:
var controlAddIn = document.getElementById('controlAddIn').srcdoc = '<div><meta charset="UFT-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"></div>';
It is working, but taht makes it very hard to read...
Do you have an idea, how I can call my entire code at this point, also multiline?
The both file should be same path if you are calling like that
else you have call the correct path
var controlAddIn = document.getElementById('controlAddIn').src = 'index.html';
save this file in index.html path and open it on browser
<script type="text/javascript">
function newSite() {
document.getElementById('myIframe').src = "index.html"
}
</script>
<input type="button" value="Change site" onClick="newSite()" />
<iframe id="myIframe" src="http://google.com/" ></iframe>
You Could use XMLHttp request to get Html File Content this code async
function httpGet(theUrl,callback)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, true ); // false for synchronous request
xmlHttp.send( null );
xmlHttp.onreadystatechange = function() {
callback(xmlHttp.responseText);
};
}
var controlAddIn;
httpGet("index.html",function(content){
controlAddIn = document.getElementById('controlAddIn').src =content;
});
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
Does anyone know of a tutorial on how to read data from a server side file with JS? I cant seem to find any topics on this when I google it. I tried to use but it does not seem to work. I just want to read some data from a file to display on the page. Is this even possible?
var CSVfile = new File("test.csv");
var result = CVSfile.open("r");
var test = result.readln();
To achieve this, you would have to retrieve the file from the server using a method called AJAX.
I'd look into JavaScript libraries such as Mootools and jQuery. They make AJAX very simple use.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script>
<script type="text/javascript">
//This event is called when the DOM is fully loaded
window.addEvent("domready",function(){
//Creating a new AJAX request that will request 'test.csv' from the current directory
var csvRequest = new Request({
url:"test.csv",
onSuccess:function(response){
//The response text is available in the 'response' variable
//Set the value of the textarea with the id 'csvResponse' to the response
$("csvResponse").value = response;
}
}).send(); //Don't forget to send our request!
});
</script>
</head>
<body>
<textarea rows="5" cols="25" id="csvResponse"></textarea>
</body>
</html>
If you upload that to the directory that test.csv resides in on your webserver and load the page, you should see the contents of test.csv appear in the textarea defined.
You need to use AJAX. With jQuery library the code can look like this:
$.ajax({ url: "test.csv", success: function(file_content) {
console.log(file_content);
}
});
or if you don't want to use libraries use raw XMLHTTPRequest object (but you I has different names on different browsers
function xhr(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();
} catch(e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
req = xhr();
req.open("GET", "test.cvs");
req.onreadystatechange = function() {
console.log(req.responseText);
};
req.send(null);
UPDATE 2017 there is new fetch api, you can use it like this:
fetch('test.csv').then(function(response) {
if (response.status !== 200) {
throw response.status;
}
return response.text();
}).then(function(file_content) {
console.log(file_content);
}).catch(function(status) {
console.log('Error ' + status);
});
the support is pretty good if you need to support browser that don't support fetch API you can use polyfill that github created
I need to create a javascript function that will write a page based on the url, so basically I am trying to create a javascript function that will check the url, and find the corresponding xml item from there.
The reason behind this is so that the html page can just be duplicated, renamed, and the xml updated, and the page will fill in everything else from the xml sheet.
please let me know whether this is the completely incorrect way to do it, of it there is a better way. thanks!!!
XML CODE::
<!--XML INFORMATION-->
<channel>
<design>
<motion><!--design content-->
<item><!--//////////POST//////////POST//////////POST//////////-->
<tag>/portfolio_dec.html</tag>
<!--RSS INFORMATION-->
<title>Decoze</title>
<link>http://payamrajabi.com/portfoliotest.html</link>
<description><img src="http://payamrajabi.com/thumbs/small_jump.png" title="JUMP!." /></description>
<!--PROJECT CONTENT-->
<project><!--project start-->
<titl>TITLE</titl><!--project title-->
<dsc>PROJECT DESCRIPTION</dsc><!--project description-->
</project><!--project end-->
</item><!--//////////END//////////END//////////END//////////-->
</motion>
</design>
</channel>
JAVASCRIPT:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "code/content9.xml",
dataType: "xml",
success: function(xml) {
var xpathname = window.location.pathname;
var xproject = $(xml).find('tag').text();
if (xpathname == xproject) {
$(xml).find('item').children('tag').text(xpathname).each(function(){
var ttl = $(this).find('titl').text();
$('<p>'+ttl+'</p>').appendTo('h1#ttl');
});
$(xml).find('item').children('tag').text(xpathname).each(function(){
var dsc = $(this).find('dsc').text();
$('<p>'+dsc+'</p>').appendTo('h1#ttl');
});
} else {
PUT ERROR MESSAGE HERE
}
}
});
});
and THE HTML:
<html>
<head>
<script type="text/javascript" src="code/jquery-1.3.1.js"></script>
<script type="text/javascript" src="code/project/project_design.js"></script>
</head>
<body>
<h1 id="ttl"></h1>
<p id="dsc"></p>
</body>
</html>
any help would really be appreciated, i am frairly new to javascript/jquery/xml, and am really having trouble with this. The primary thing I want to do is have an xml file that populates a site, with each item being the content for a new page, in this case of a portfolio item.
cheers!
willem
Hmm... I'm afraid you don't quite understand how jquery works.
Your code should look something like this:
var xpathname = window.location.pathname;
var xitem = $(xml).find('tag:contains(' + xpathname + ')').parent();
if (xproject.length != 0) {
$('#ttl').append('<p>' + xitem.find('titl').text() + '</p>');
$('#dsc').append('<p>' + xitem.find('dsc').text() + '</p>');
}
else {
$('#err').text('The page you requested does not exist');
}
Demo 1
Here's a quick demo. Take a look at the source to see the XML and the JavaScript.
http://jsbin.com/ujiho#itemOne
http://jsbin.com/ujiho#itemTwo
http://jsbin.com/ujiho#itemThree
Demo 2
I've created another demo that uses $.get to retrieve the XML from a separate URL.
http://jsbin.com/aqefo#nov
http://jsbin.com/aqefo#dec
The XML: http://jsbin.com/afiwa
Here's the JavaScript. Let me know if you need help understanding anything.
$(function(){
$.get(
'http://jsbin.com/afiwa',
function(xml){
var hash = window.location.hash.substring(1);
if ($.trim(hash) === '') {
showError();
return;
}
var xitem = $(xml).find('urlname:contains(' + hash + ')').parent();
if (xitem.length != 0) {
$('#ttl').append(xitem.find('titl').text());
$('#dsc').append( xitem.find('dsc').text());
}
else {
showError();
}
function showError() {
$('#err').text('The page you requested does not exist');
}
}
);
});