Avoiding getting css style with page using InnerHTML - html

using the code below, by clicking a link in my nav menu, i get an html page in a certain div (InnerHTML), but, i have my menu il css style, and after clicking a link and getting the page to the div , it seems that my nav li css is corrupted and gets the css style of the page i clicket and got within the div... how can i avoid getting the css with the page im requesting please demonstrate me, i cant find something related.
thank you.
<script>
function processAjax(url) {
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv;
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv;
req.open("GET", url, true);
req.send();
}
}
return false;
}
function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById("containerDiv").innerHTML = req.responseText;
} else {
alert("Problem: " + req.statusText);
}
}
}
</script>

Related

Read a text file using XMLHttpRequest?

I have been trying to use the XMLHttpRequest to read a text file and display the text. The text file I is going to be linked externally. So far I have the following code
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest object</h2>
<script>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", XMLHttpRequest.txt, true);
</script>
</script>
</body>
</html>
I do not see my text file showing up and I am completely lost. I looked around on stack overflow already for answers and I did not find anything.
You haven't specified where your text file is located.
Here's an example of a working XMLHttpRequest with a remote api (not a real api endpoint, just an example url). You could adapt this to use a text file instead of json. Remember to call your function in the end! findCity( city ) for instance.
function findCity(elem) {
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
document.getElementById("city").value = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "https://api.example.com/api/postcodes.json?pnr=" + elem.value + '&clientUrl=http://localhost', true);
xmlhttp.send();
}

html <script> tag headers

I'm trying to require a script that is firewalled with a header authentication system and trying to find a way around it.
So far it's pretty evident that you can't add custom headers to the script tag its self but I have seen something about customizing the headers on the page before requesting or on the server side.
Until this point, I can't say I've seen any solid answers.
You can load it via xhr and eval() it in-page. For example with jQuery, you can use:
http://api.jquery.com/jquery.ajax/ - see beforeSend to set headers; use this to retrieve the file content.
Then use https://api.jquery.com/jquery.globaleval/ globalEval() to eval the gotten content in-page.
You could achieve the same with vanilla HttpRequest and eval(), but I was always too lazy to do it that way. Or maybe not... I just found a piece of code in the project I'm working:
var evalScript = function(e) {
var h = evalScript.node,
s = document.createElement("script");
s.type = "text/javascript";
s.text = e;
h.appendChild(s);
h.removeChild(s);
};
evalScript.node = document.getElementsByTagName("head")[0] || document.getElementsByTagName("*")[0];
// TODO: make async
function loadJs(js) {
var req = new XMLHttpRequest();
req.open("GET", js, false);
req.send(null);
evalScript(req.responseText);
}
Just add the headers to this.
Here's a simple Ajax function you could use to get the contents of the script:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
Since you need to set custom headers, you'd also use the request.setRequestHeader method, like this:
function get(url, callback) {
var request = new XMLHttpRequest();
request.open("GET", url, true);
// BEGIN: CUSTOM HEADERS
request.setRequestHeader("Header-Name", "header/value");
request.setRequestHeader("Other-Header", "other/value");
// END: CUSTOM HEADERS
request.onreadystatechange = function() {
if(this.readyState === 4) {
if(this.status >= 200 && this.status < 400) {
callback.apply(this, [this.responseText, this]);
} else {
// something went wrong.
}
}
};
request.send();
}
And finally, you'd use the function, like this:
get("url/to/your/script", function(response) {
// perform checks...
window.eval(response);
});
WARNING: be very, VERY careful when using eval, don't ever eval something you don't trust and remember eval can be evil.

Ajax html Domparser

I have some ajax code in an html doc that changes the text of a button to text stored in another html doc in the same domain. The text is in the body tag of the second html document.Like this:
<body> Text</body>
So the code makes an ajax request, parses the response to create an xmldoc. When I try to use the
getElementByTagName("body") or even getElementByTagName("html")
I get an emepty HTMLcollection. But when I use the
queryselector("body") I can get to the text. The log to console prints undefined.
Here's the full code:
function gettxt()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "http://localhost/ajax2.html", true);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200)
{
allText = xmlhttp.responseText;
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(allText, "application/xml");
var bodyobj=xmlDoc.getElementsByTagName("body");
console.log(bodyobj.lemgth);
document.getElementById("secbtn").value=bodyobj;
}
}
}
xmlhttp.send(null);
}
What am I missing? Thanks.
I know what I was doing wrong. I was setting the button's text to bodyobj instead of bodyobj[0].innerHTML.

Adding animation into ajax

I wrote code in which .getJSON api from jquery is used to fetch images from flickr public api. Please see this link. I have made each of the images to slide after each request gets finished. Now, I want the first set of image to slide downward and then following sets to slide up first and then replaced by images from ajax request maintaining the same animation as used for the first set of images. I think a very little modification is enough. I thank you for your comment and suggestion before hand.
Is this what you had in mind?
getFlickr();
setInterval(getFlickr, 20000);
function getFlickr() {
$.getJSON('http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?', {
'format': 'json'
}, function(data) {
if ($('p').length < 1) {
addPiecePiece('#main',true,null);
}
else {
$('.flickr').each(function(i) {
$(this).delay(4000*i).slideUp(2000,function(){
addPiecePiece($(this),false,i);
$(this).remove();
});
});
}
function addPiecePiece(element,aoa,index) {
$.each(data.items, function(key, value) {
if(index == null || index == key){
title = value.title;
description = value.description;
photo = value.media.m;
html = $('<p class="flickr"></p>').html(description).css({
'display': 'none'
});
if(aoa == true){
$(html).appendTo(element).slideDown(2000);
}else{
$(html).insertAfter(element).slideDown(2000);
}
}
});
}
})
}

html ajax doesn't load in firefox

I'm a total newbie at web programming but I have to make a home page for college and i'm stuck. I have an html file that loads a .jsp page inside a div using ajax. I have a couple of links that load different files. My problem is that Firefox doesn't respond when I click on the links(No error message nor visible activity). In Internet Explorer on the other hand the first link(About Me) works just fine(loads the .jsp inside the div). My second link however (Photos) should load a .jsp containing javascript and that doesn't work on either browsers. In IE, the .jsp loads but the javascript doesnt`t work.
I would really appreciate some help. Here's my code:
mainPage:
<head>
<title>Titi's HomePage</title>
<link rel="stylesheet" type="text/css" href="homeStyle.css"/>
<script type="text/javascript">
function loadXMLDoc(file, div)
{
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById(div).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send();
}
</script>
</head>
<body class="body">
<div align="center"><img src="images/header2.jpg" width="1074" height="162" /></div>
<div align="center">
<table width="1075" height="41" border="1" class="mainTable">
<tr>
<th width="215" scope="col">About Me</th>
<th width="227" scope="col">Photos</th>
</tr>
</table>
<table class="displayTable">
<tr>
<td><div id="display"></td>
</tr>
</table>
</div>
</body>
Photos.jsp
<head>
<title>Photos</title>
<SCRIPT language=JavaScript>
theImages = new Array("images/Constanta/c1.jpg", "images/Constanta/c2.jpg", "images/Constanta/c3.jpg","images/Constanta/c4.jpg");
function displayImages() {
for(x in theImages){
document.write('<img SRC="' +theImages[x]+' " width=80, height =80 onmouseover=addSource(\"'+theImages[x]+'\") onmouseout =removeSource()>');
}
}
function addSource(name){
document.getElementById("biggie").src = name;
var newImg = new Image();
newImg.src = name;
document.getElementById("biggie").height = newImg.height;
document.getElementById("biggie").width = newImg.width;
}
function removeSource(){
document.getElementById("biggie").src = "";
document.getElementById("biggie").height = 0;
document.getElementById("biggie").width = 0;
}
</SCRIPT>
</head>
<body>
<SCRIPT language=JavaScript>
displayImages();
</SCRIPT>
<br/>
<center><img src="" id="biggie" width="0" height="0" align="middle"></center>
</body>
if I load directly the Photos.jsp then it works just fine with both IE and FireFox but not through the links of the main page.
What am i doing wrong?? Keep in mind that I'm totally new to this so feel free to tutor me on anything :D
Thanks in advance!
You should try using something like this - but i am shure that is jQuery the best solution
I adjusted the code, so, now you have that what you need (like function which you suggested).
Main problem is callback function, because ajax call is asynchronous (there is option in jQuery where it can be synchronous call) and function returns undefined value before ajax call complete.
Now, in this function 'div' name is passed as function parameter, so you don't need function callback.
This code is tested on my computer in Firefox 3.6.13
function isIE(){return/msie/i.test(navigator.userAgent)&&!/opera/i.test(navigator.userAgent);}
function loadXMLDoc(filename, div)
{
try
{
if (isIE())
{
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
var xmlhttp = false;
}
if (!xmlhttp && typeof XMLHttpRequest != 'undefined')
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
if (!xmlhttp && window.createRequest)
{
try
{
xmlhttp = window.createRequest();
}
catch (e)
{
xmlhttp = false;
}
}
xmlhttp.open("GET", filename);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4)
{
document.getElementById(div).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
catch (e)
{
alert(e);
}
}