Including HTML page within HTML Page using jQuery - javascript

I am including a HTML page, named test.html in a webpage. As below:
<head>
<meta charset="utf-8">
<title>load demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<b>Content I want to Include is here: </b>
<div id="success"></div>
<script>
$( "#success" ).load( "test.html", function( response, status, xhr ) {
if ( status == "error" ) {
var msg = "Sorry but there was an error: ";
$( "#success" ).html( msg + xhr.status + " " + xhr.statusText );
}
});
</script>
</body>
</html>
I get an error reading:
Sorry but there was an error: 0 NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'file://machd/.../HTML/test.html'.
What does this error mean? And how best to solve it?

You can make use of Angular js for including another HTML file
Read docs here
https://docs.angularjs.org/api/ng/directive/ngInclude
Example:
<div class="container">
<div ng-include="'filename.htm'"></div>
</div>

Maybe you can try:
Give the absolute path to test.html as argument and debug

The only browser which allowed ajax requests through file:// protocol was old IE and was remove due to security issues. Your code will work fine on any web server such as XAMPP, or UWAMP. simply run Uwamp, put yout project to www folder and open http://localhost

I am in agreement with swornabsent and monxas above.
This code works without issue when uploaded and the page viewed on the server.

the easy way...
1> Add the js file and include code
<script src="https://www.w3schools.com/lib/w3data.js"></script>
<script> w3IncludeHTML();</script>
2> Just call your html file like example
<div w3-include-html="h1.html"></div>

Related

`Uncaught SyntaxError: Unexpected token <` when referencing existing javascript file

Important edit at bottom of some strange behavior.
I'm trying to include a javascript file into my html via a <script> tag and I'm getting the error Uncaught SyntaxError: Unexpected token <
In case it matters, I'm using the Velocity templating engine.
Any help is greatly appreciated!
Here is my directory structure.
Here is my index.vm file.
<html lang="en">
<head>
<meta charset="utf-8">
<title>Velocity Demo</title>
</head>
<body>
<input type="text" onkeydown="filter(this)"></input>
#foreach ($person in $personList)
<div>
<h4>$person.name</h4>
</div>
#end
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="../static/js/filter.js"></script>
</body>
</html>
And here is the javascript file.
function filter(element) {
$.ajax({
url: '/updateFilter?filter=' + element.value,
success: location.reload(true),
error: location.reload(true)
})
}
Editing to add this image. For some reason this is the filter.js file when I inspect the sources in Chrome.
EDIT: For some reason, every request other than the one I have mapped to the controller, including filter.js, is returning the raw html from index.vm
You have an unnecessary closing tag for your element - pasting your html into plnkr highlights this.
I would also perform a "trial and error" process of elimination, as it may not be the inclusion of the JS file that is the cause.

Jquery ajax is giving me a 404 not found error

I have the following code:
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="description" content="">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
function loadPhotos(folderName){
var folder = "assets/photos/"+folderName+"/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
$("body").append( "<img src='"+ folder + val +"'>" );
}
});
}
});
}
</script>
</head>
<html>
<div onclick="loadPhotos('7thAnnual')">7th Annual</div>
</html>
For some odd reason when I click on the div, the loadPhotos function throws a 404 not found error on the ajax call.... but the directory that it is saying it can't find, does exist.
For the record I am running this on localhost (http://127.0.0.1:8020/).
the directory structure is Ljf/assets/photos/7thAnnual ....
so the full path would be http://127.0.0.1:8020/Ljf/assets/photos/7thAnnual
the 7thAnnual directory holds all the images
Any thoughts?
Okay.... so it seems that I have to fully qualify the name in the url like so:
var folder = "127.0.0.1:8020/Ljf/assets/photos/7thAnnual";
instead of using just:
var folder = "Ljf/assets/photos/7thAnnual"
This answer brings a
"Cross origin requests are only supported for protocol schemes: http,
data, chrome, chrome-extension, https, chrome-extension-resource."
which is a different issue than this post, but it does solve the
404 not found
So I'll mark it as the answer
You must create the directory assets/photos/7thAnnual/. Be sure you did that
If you run this in chrome and open the nifty little inspector
(right click on the background somewhere, choose inspect, then go to the network tab on the inspection window)
then click the div that should trigger the ajax, it should show you the path it tries to get to. (on your little network panel at the very bottom)
Make sure that the path looks right
Look at the response to see if there is any other potentially useful info
let me know what you find!

JQuery AJAX "Not Found" Error

hello Whenever I click on the button that says "Get External Content" I get a javascript alert that says "Not Found" (this is the error's status text).
Why can it not find the text file I am trying to load via ajax?
This is my folder hierarchy:
--public_html
--app
--ajaxTestHome.php
--ajaxTestText.txt
And this is the file I am trying to load (via ajax) the text file into.
//ajaxTestHome.php
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#ajax").click(function(){
$.ajax(
{
url:"/app/ajaxTestText.txt",
success:function(result){
$("#div1").html(result);
},
error: function(abc) {
alert(abc.statusText);
},
cache: false
}
);
});
});
</script>
</head>
<body>
<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button id="ajax">Get External Content</button>
</body>
</html>
EDIT: I had a typo in the question. the file is called "ajaxTestText.txt" not "ajaxTestTest.txt"
The URL parameter is incorrect:
$(document).ready(function(){
$("#ajax").click(function(){
$.ajax(
{
url:"ajaxTestText.txt",
success:function(result){
$("#div1").html(result);
},
error: function(abc) {
alert(abc.statusText);
},
cache: false
}
);
});
});
You shouldn't need the /app/ in the url.
Also your file is called ajaxTestTest.txt and the url you are calling is ajaxTestText.txt they have different names
I found the solution.
The problem did not have anything to do with it being in the wrong directory or me referencing the file with or without the "/" or the "/app/" or "app/".
Rather I changed the extension from .txt to .html. I was accessing this from a server I was FTPing to, and I guess the server won't correctly let you see/access the contents of a txt file but will an HTML? If you happen to know, please enlighten me.

get variable from csv file for HTML code using Javascript or jquery function

I want to have different numbers in my html code depending on a .csv file, so I want to be able to grab data from a .csv file to an html page using jquery or java script. I thought I found a webpage that shows how to do this in Jquery, but I can not figure it out. This webpage is at: http://code.google.com/p/jquerycsvtotable/
On the left side of this webpage there is even a download .zip file that should give me a working model of what this site describes, with even the final index.html file, but I can not get it to work. Could someone please show me what has changed or what I am doing wrong? Please, show me what I need to do to get this to work or give me another small example. I am new to JavaScript and Jquery.
( I finaly decided to post this question with this example page because this is the closest answer I have found to my question)
thanks
Tom,
Jay here is the code:
I have made sure JavaScript is enabled on the firefox brozer I use to test my file and I have a test.csv file sitting in the directory. This actually gives me the same result as if I download the .zip file from the left side of the website. It gives me an .html page with a link to a test.csv file which I can download, but it does not use the data in the code to make a table or do anything else?
thanks,
tom
enter code here
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery CSVToTable</title>
<link rel="stylesheet" href="css/csvtable.css" type="text/css" />
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/jquery.csvToTable.js"></script>
<script type="text/javascript" src="js/jquery.tablesorter.dev.js"></script>
<script>
$(function() {
$.get('test.csv', function(data) {
$('#CSVSource').html('<pre>' + data + '</pre>');
});
$('#CSVTable').CSVToTable('test.csv', { loadingImage: 'images/loading.gif', startLine: 0 });
$.get('test.tsv', function(data) {
$('#TSVSource').html('<pre>' + data + '</pre>');
});
$('#TSVTable').CSVToTable('test.tsv', { loadingText: 'Loading TSV Data...', loadingImage: 'images/loading.gif', startLine: 0, separator: "\t" });
$('#CSVTable2').CSVToTable('test.csv', { loadingImage: 'images/loading.gif', startLine: 1, headers: ['Album Title', 'Artist Name', 'Price ($USD)'] }).bind("loadComplete",function() {
$('#CSVTable2').find('TABLE').tablesorter();
});;
});
</script>
</head>
<body>
[back to google code...]
<br><br>
This is a test of the CSVToTable plugin.
<br><br>
Original CSV Source of test.csv:<br>
<div id="CSVSource" style="background-color: #FAFAFA; border: 1px solid #999999">
</div>
<br><br>
CSV To Table:<br>
<div id="CSVTable">
</div>
CSV To Table2:<br>
<div id="CSVTable2">
</div>
</body>
</html>
A few general things to check:
Keep your console open in dev tools of your choice, ensure there are no Javascript errors occurring.
Again inside your dev tools, go to your network tab and look at the raw response that is being retrieved when the $.get occurs. Is it even able to retrieve it?
Check that your server is able to serve .csv files. It may be locked down to only serve certain mime types.
Without more info, it's hard to give you a more formal answer. Good luck with your app.

Update a div with jQuery [duplicate]

This question already has answers here:
jQuery AJAX cross domain
(15 answers)
Closed 8 years ago.
I have a jQuery script for refresh the content of a div. The content is get from an external page like mypage.php. The code is this:
page.html:
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
//var first_load =
function firstLoad()
{
$('#load_tweets').load('mypage.php');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('mypage.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body onLoad="firstLoad()";>
<div id="load_tweets"> </div>
</body>
</html>
If i get the content from mypage.php, that is a php script with an echo command at the end, all work fine. But now i need to get the content of div from here:
http://37.187.90.121:3874/currentsong?sid=1&c=
The output of this source is like this:
Inna - Un Momento
If i replace "myage.php" with "37.187.90.121:3874/currentsong?sid=1&c=" the jquery script in page.htm don't work and return a blank output. What is the problem?
EDIT1:
ok is a policy problem, how i can resolve it?
EDIT2:+
The proxy php page solution don't work.
I have make this php page:
<?php
echo file_get_contents("http://37.187.90.121:3874/currentsong");
?>
But i have this error message:
Warning: file_get_contents() [function.file-get-contents]: http:// wrapper is disabled in the server configuration by allow_url_fopen=0 in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2
Warning: file_get_contents(http://37.187.90.121:3874/currentsong) [function.file-get-contents]: failed to open stream: no suitable wrapper could be found in /home/mhd-01/www.radiowhitecrash.com/htdocs/Player/GTitle/current_g2.php on line 2
Edit3:
The external service give me a javascript to get the information:
window.centovacast===undefined&&(window.centovacast={}),window.centovacast.options===undefined&&(window.centovacast.options={}),window.centovacast.loader===undefined&&(window.centovacast.loader={attempts:0,external_jquery:!1,loaded:!1,ready:!1,widget_definitions:{},url:"",load_script:function(e){var t=document.createElement("script");t!==undefined&&(t.setAttribute("type","text/javascript"),t.setAttribute("src",e),t!==undefined&&document.getElementsByTagName("head")[0].appendChild(t))},load_widget:function(e){var t=this.widget_definitions[e];t.ref===null&&(t.ref=t.define(jQuery))},jq_get_jsonp:function(e,t,n){return jQuery.ajax({type:"GET",url:e,data:t,success:n,dataType:"jsonp"})},jq_ready:function(){this.ready=!0;for(var e in this.widget_definitions)typeof this.widget_definitions[e].init=="function"&&this.widget_definitions[e].init(jQuery)},jq_loaded:function(){this.external_jquery||jQuery.noConflict(),jQuery.getJSONP=this.jq_get_jsonp;for(var e in this.widget_definitions)this.load_widget(e);this.loaded=!0;var t=this;jQuery(document).ready(function(){t.jq_ready()})},wait:function(){setTimeout(function(){window.centovacast.loader.check()},100)},check:function(){typeof jQuery=="undefined"?(this.wait(),this.attempts++):this.jq_loaded()},init:function(){var e=document.getElementsByTagName("script"),t=e[e.length-1],n;n=t.getAttribute.length!==undefined?t.getAttribute("src"):t.getAttribute("src",2),n.match(/^https?:\/\//i)||(n=window.location.href),this.url=n.replace(/(\.(?:[a-z]{2,}|[0-9]+)(:[0-9]+)?\/).*$/i,"$1"),this.external_jquery=typeof jQuery!="undefined",this.external_jquery||this.load_script(this.url+"system/jquery.min.js"),this.check()},add:function(e,t,n){this.widget_definitions[e]||(this.widget_definitions[e]={define:n,init:t,ref:null}),this.loaded&&this.load_widget(e),this.ready&&t(jQuery)}},window.centovacast.loader.init()),window.centovacast.loader.add("streaminfo",function(e){e.extend(window.centovacast.streaminfo.settings,window.centovacast.options.streaminfo),window.centovacast.streaminfo.settings.manual||window.centovacast.streaminfo.run()},function(e){return window.centovacast.options.streaminfo=e.extend({},window.centovacast.options.streaminfo,window.centovacast.streaminfo?window.centovacast.streaminfo.config:null),window.centovacast.streaminfo={pollcount:0,settings:{poll_limit:60,poll_frequency:6e4},state:{},registry:{},check_username:function(e){e+="";if(!this.registry[e]){if(this.registry.length==1){for(var t in this.registry)e=t;return e}return""}return e},get_streaminfo_element:function(t,n){return e("#"+this.registry[t].id[n])},_handle_json:function(t){if(!t)return;var n=this.check_username(t.rid);!n.length&&t.requestdata&&(n=this.check_username(t.requestdata.rid));if(!n.length)return;if(t.type=="error"){var r=t?t.error:"No JSON object";this.get_streaminfo_element(n,"song").html('<span title="'+r+'">Unavailable</span>'),typeof this.settings.on_error_callback=="function"&&this.settings.on_error_callback(r)}else{var i,s=t.data[0];this.state=s,t.data[0].songchanged=s.song!=this.settings.lastsong,typeof this.settings.before_change_callback=="function"&&this.settings.before_change_callback(t);for(i in s)i!="song"&&(typeof s[i]=="string"||typeof s[i]=="number")&&this.get_streaminfo_element(n,i).html(s[i]);if(typeof s.track=="object"){for(i in s.track)i!="buyurl"&&i!="imageurl"&&i!="playlist"&&(typeof s.track[i]=="string"||typeof s.track[i]=="number")&&this.get_streaminfo_element(n,"track"+i).html(s.track[i]);this.get_streaminfo_element(n,"playlist").html(typeof s.track.playlist=="object"?s.track.playlist.title:"");var o=s.track.buyurl?s.track.buyurl:"javascript:void(0)";e("img#"+this.registry[n].id.trackimageurl).attr("src",s.track.imageurl),e("a#"+this.registry[n].id.trackbuyurl).attr("href",o)}typeof this.settings.after_change_callback=="function"&&this.settings.after_change_callback(t);var u=s.song;u&&u!=this.registry[n].current_song&&(this.get_streaminfo_element(n,"song").fadeOut("fast",function(){e(this).html(u),e(this).fadeIn("fast")}),this.registry[n].current_song=u)}},handle_json:function(e,t,n){e&&window.centovacast.streaminfo._handle_json(e)},poll:function(t){var n=(this.settings.local?"/":window.centovacast.loader.url)+"external/rpc.php",r={m:"streaminfo.get",username:t,charset:this.registry[t].charset,mountpoint:this.registry[t].mountpoint,rid:t};e.getJSONP(n,r,this.handle_json)},_poll_all:function(){for(var e in this.registry)typeof e=="string"&&this.poll(e);(this.settings.poll_limit===0||this.pollcount++<this.settings.poll_limit)&&setTimeout(this.poll_all,this.settings.poll_frequency)},poll_all:function(){window.centovacast.streaminfo._poll_all()},register:function(e,t,n,r){this.registry[t]||(this.registry[t]={charset:n,mountpoint:r,current_song:"",id:{}});var i=e.match(/^cc_strinfo_([a-z]+)_/);i&&(this.registry[t].id[i[1]]=e)},load:function(){var t=e(this).attr("id");if(typeof t!="string")return;var n=t.replace(/^cc_strinfo_[a-z]+_/,""),r="",i="",s=/_cs-([A-Za-z0-9\-]+)$/,o=s.exec(n);o&&(r=o[1],n=n.replace(s,"")),s=/_mp-([A-Za-z0-9\-]+)$/,o=s.exec(n),o&&(i=o[1],n=n.replace(s,"")),window.centovacast.streaminfo.register(t,n,r,i)},run:function(){e(".cc_streaminfo").each(window.centovacast.streaminfo.load),window.centovacast.streaminfo.poll_all()}}});
You can check it at this link:
http://cp.eu2.fastcast4u.com:2199/system/streaminfo.js
Unfortunaly with no identation and in add i have few experiences with javascript i cant' edit the output of this script.
This script give me an output like:
"Radio Name - Author - Title of song"
and this is a link (if you click on it open another page).
I need to get only "Author - Title of song" with no link. Any idea?
Edit4:
I have make another test, i have call the streaminfo.js in a span and i prove to use the document.getX of javascript to get the content of the span in various ways, but i get "undefined" output:
<html>
<head>
<script language="javascript" type="text/javascript" src="http://cp.eu2.fastcast4u.com:2199/system/streaminfo.js"></script>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
var div = document.getElementsByClassName('cc_streaminfo')[0];
document.write("w1" + document.getElementsByClassName('cc_streaminfo')[0]);
document.write("w2" + document.getElementsByClassName('cc_streaminfo')[1]);
document.write("w3" + document.getElementsByClassName('cc_streaminfo')[2]);
var container = document.getElementById ("cc_strinfo_summary_radiowhite");
var spans = div.getElementsByTagName("span");
document.write("il mio script: " + spans[0] + "!");
document.write("il mio script: " + container + "!");
//var first_load =
function firstLoad()
{
$('#load_tweets').load('current_g.php?song=ciao');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('current_g.php?song=' + cc_streaminfo).fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
</head>
<body onLoad="firstLoad()";>
<br>
<span id="cc_strinfo_summary_radiowhite" class="cc_streaminfo">sss</span>
<div id="load_tweets"> </div>
</body>
</html>
I think this has something to do with CORS. Basically, unless the webpage at 37.187.90.121 explicitly states that it trusts the sources of the domain under which your website is running, your browser will not make the request.
If you are the owner of 37.187.90.121, you can add custom headers to allow inclusion of your response in other webpages.
Check your javascript console of your browser to get more details.
Using jQuery to get (.load()) the contents from a div on another page ( same domain ) to add to a div on the current page is like :
$("#dividoncurrentpage").load("/otherpage.php #dividonotherpage");
Is this what you need ?
It's because:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
mstaessen has explained on the post above.
The alternative solution is: You can create a file called, for example song.php and add the following code.
<?php
echo file_get_contents("http://37.187.90.121:3874/currentsong?sid=1&c=");
?>
And update the script to
<script type="text/javascript">
//var first_load =
function firstLoad()
{
$('#load_tweets').load('song.php');//.fadeIn("slow");
}
var auto_refresh = setInterval(
function ()
{
$('#load_tweets').load('song.php').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
Its better to use jQuery $.ajax to get the content. Link
By using $.ajax you have many ways to work around this issue like crossDomain or get the result in Json format by setting the dataType that you will receive from the server to JSON or JSONP

Categories