I am trying to load a div content from another page(this page is in another project which is running in tomcat all together) with javascript ajax.
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://localhost:8080/prob-services/clogin#login_page');
xhr.onload = function() {
alert(xhr.status);
console.log(xhr);
if (xhr.status === 200) {
var modal = document.getElementById("modal_dialog");
modal.innerHTML = xhr.responseText;
}
};
xhr.send();
The problem is when I log xhr I see that responseURL is until #, so ajax takes only http://localhost:8080/prob-services/clogin instead of http://localhost:8080/prob-services/clogin#login_page. That's why it loads whole page.
Is there any way to get only div content without JQuery?
Solution to filter the whole page:
Create a dummy hidden DOM element like
<div style='display: none' id="loadedHTML"></div>
then put the HTML of the whole page you received from the server into it:
document.getElementById('loadedHTML').innerHTML = xhr.responseText;
now you can search the html inside this component. Say the part you want to is in a div called "MyDiv" inside the page:
var modal = document.getElementById("modal_dialog");
modal.innerHTML = document.getElementById('MyDiv').innerHTML;
fell free to ask more if it's not clear enough.
Use this jQuery load() function
$('#modal_dialog').css('opacity','1').load('http://localhost:8080/prob-services/clogin',function() {
alert():
} );
Related
I need an explanation about this code :
page2.php
<?php
if (isset($_POST['p'])) { echo $_POST['p'];}
page.php
<body>
<button name="bouton" id="bouton"> TEST </button>
<script>
document.getElementById('bouton').addEventListener("click", function() {
var xhr = new XMLHttpRequest();
xhr.open('POST', 'page2.php');
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send('p=2');
xhr.addEventListener('load', function() { /*document.body.innerHTML += xhr.response;*/ document.getElementById('bouton').insertAdjacentHTML('beforebegin',
xhr.response); });
});
</script>
</body>
It's a load more script for testing purpose. While this code works fine, if I replace
document.getElementById('bouton').insertAdjacentHTML('beforebegin',
xhr.response);
By the comment :
document.body.innerHTML += xhr.response;
The xhr.response file is adding only once. I can't understand why.
Thanks a lot !
Setting the innerHTML of the body is replacing the entire body of your document with a new one, the new button does not have a click handler attached to it like the old button so nothing will happen when you try to click it.
For insertAdjacentHTML nothing is replaced, you're just adding content before the button. The original button is still there and its click handler responds to your clicks with the ajax request.
I have developed a very simple Chome extension that exposes a single toolbar button. When the button is clicked, the page content is POSTed to the server using XMLHttpRequest and then the innerHtml of the <html> element is replaced by the new content returned from the server.
For some reason this prevents <select> elements from expanding. I have verified this by disabling the extension which makes then work again.
Any ideas why this might be happening and how to fix it? The code is below for reference:
chrome.extension.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.msg == "get_content") {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
document.getElementsByTagName('html')[0].innerHTML =
xmlhttp.responseText;
} else {
alert('Cannot reach russiangram.com');
}
}
}
xmlhttp.open("POST", "https://russiangram.com/translate/Default.aspx", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(document.getElementsByTagName('html')[0].innerHTML);
sendResponse({ data: 'success' });
}
});
At a guess I would say where you are replacing the contents of the documents HTML tag that you are possibly also replacing any associated JS/CSS references that were originally on that page as well.
Maybe as a test instead of replacing the contents of the HTML tag, add a new DIV element or something to the page and target that instead. That should hopefully allow you see whether or not the select functionality still works.
I've got a chat function in my website for two users to chat with each other, and I'm using JavaScript, AJAX, and PHP for it.
At the moment, it won't refresh the chat area automatically unless I submit a reply to the chat or refresh the page. I can't figure out why.
JavaScript Function
function checkReply(threadid) {
// XMLHttpRequest
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("chatwrap").innerHTML = xmlhttp.responseText;
setInterval(checkReply(threadid), 10000);
}
}
xmlhttp.open("GET","inc/chatreply.php?chatid="+ threadid,true);
xmlhttp.send();
}
The event handler is on the <div> the responseText will end up in:
<div id="chatwrap" onload="checkReply('.$threadid.')"></div>
$threadid is a GET variable set at the top of the page:
$threadid = (int)$_GET['chatid'];
UPDATE
Seeing that you were in a PHP state already, the syntax was correct.
The problem is that the div doesn't possess an onload event. You'll have to attach it to the body tag, or include a script in the head or below the div, as it will only execute after the div has been rendered.
You're not including the PHP variable correctly. At the moment you are passing the string .$threadid. to the checkReply function. You will have to drop into PHP mode again before using this syntax by using the delimiters <?php & ?>.
<div id="chatwrap" onload="checkReply(<?php echo $threadid; ?>)"></div>
This should work better.
I am trying to code a java script function for my page. The "index.html" page has the basic layout with all the necessary tags (html, head, title and body). My question is, how will I go to the next page (if you click on a menu item) without having to code the same tags and copy all the data from the "index.html" page - i.e. not having redundant code.
e.g. There are 3 main pages excluding the "index.html" page (this one has all the main tags on it). The other pages are 1-About 2-Contact 3-Gallery. On each page the tags will only have:
Bla bla bla
some other tags with text, photos etc
What is the code for the java script function to change the text/content within the tags without having to copy the entire document's code on each page?
I want to use Chrome as the default browser and I am only using HTML and Java script (no PHP)
Thanks
Use can use this function this will solve your problem just pass your div Id where you want to load the contents of page with index layout. In my example i load my contents in container div.
/**
* Load page into url
*
* #param url The url to load
* #param onleave The function to call before leaving
* #param onenter The function to call after loading
*/
function loadPage(url, onleave, onenter)
{
alert(url);
console.log("loadPage("+url+")");
// If onleave function specified
if (onleave) {
onleave();
}
var xmlhttp = new XMLHttpRequest();
// Callback function when XMLHttpRequest is ready
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState === 4){
if (xmlhttp.status === 200) {
console.log("Received content"+xmlhttp.responseText);
document.getElementById('container').innerHTML = xmlhttp.responseText;
// If onenter function specified
if (onenter) {
onenter();
}
}
else {
document.getElementById('container').innerHTML = "Error loading page " + url;
}
}
};
xmlhttp.open("GET", url , true);
xmlhttp.send();
return;
}
Ok try this:
<!doctype html>
<html>
<head>
<script type="application/javascript">
function menuClick(x) {
if(x == "About"){
var menu1 = document.getElementById("menuButton_1");
menu1.innerHTML = "The HTML content for your about section";
} else if (){
// replicate the same for your other two menu sections
// here #2
} else if() {
// here #3
}
}
</script>
</head>
<body>
<div id="menuButton_1" onclick="menuClick('About')">
</div>
<div id="menuButton_2" onclick="menuClick('Contact')">
</div>
<div id="menuButton_3" onclick="menuClick('Gallery')">
</div>
</body>
</html>
You can execute an "onclick" function to fire when your menu buttons are clicked. In your javascript function you can test which menu button was clicked and set the innerHTML of particular elements on the page to show the correct content.
You can change the content of multiple elements by targeting each of their id's. Just create more javascript variables and use them to target the innerHTML of the specific HTML elements you want to change.
If I am way off on how to employ this code then please forgive me, but is it possible to use something like
var url = 'http://www.maxcashtitleloans.com/lmapp.html'
document.write('<script src="'+url+'"></scr'+'ipt>')
to somehow display an html form inside many websites across different servers?
I have a single HTML form that will be continually updated as the needs of the company change, and would like to get them off of IFRAME calls.
A different questions towards the same goal "How can I display off site content on a website and not use IFRAME"
I know of an affiliate marketing company that uses
<script type='text/javascript'>
var inputOptions = {
UserID: '35696',
Product: 'payday',
ProductTemplate: 'lights',
Server: 'https://altohost.com/',
mobileDevices: true,
parseDefaultValue: true,
visitor: {
referrer: (document.cookie.match("rfrrr[\r\n\t ]*=[\r\n\t ]*(.*?)(;|$)") || [,''])[1],
subaccount: (document.cookie.match("src[\r\n\t ]*=[\r\n\t ]*(.*?)(;|$)") || [,''])[1],
keyword: (document.cookie.match("kwrd[\r\n\t ]*=[\r\n\t ]*(.*?)(;|$)") || [,''])[1],
clickid: (document.cookie.match("clcid[\r\n\t ]*=[\r\n\t ]*(.*?)(;|$)") || [,''])[1]
},
};
document.write('<scr'+'ipt type="text/javascript" src="https://altohost.com/system/applicationforms/init.php?vn=inputOptions"></scr'+'ipt>');
</script>
I'd propose a slightly different approach.
Use JavaScript to create the HTML form and include that script into all other websites using the same source.
Assume form.js is the file you want to include in every website.
Live DEMO
forms.js
var company = {};// Avoid name clashes!!!
company.form = function() {
this.render();
};
company.form.prototype.render = function() {
var url = "blablabla";
this.form = document.createElement("form");
this.form.setAttribute("method", "post");
this.form.setAttribute("name", "company-specialform");
this.form.setAttribute("action", url);
var input = document.createElement("input");
input.setAttribute("type", "text");
input.setAttribute("value", "test");
var submit = document.createElement("input");
submit.setAttribute("type", "submit");
submit.setAttribute("value", "submit");
this.form.appendChild(input);
this.form.appendChild(submit);
var that = this;
this.form.onsubmit = function(event) {
that.submit.call(that, event);
};
};
company.form.prototype.submit = function(event) {
event.preventDefault(); // if needed
alert(" Custom submit was called");
};
company.form.prototype.getForm = function() {
return this.form;
};
company.form.append = function(container) {
var form = new company.form();
container.appendChild(form.getForm());
};
var target = document.getElementById("container");
company.form.append(target);
Now simply include forms.js on any other website, but make sure you use the same src for all of those websites, so you can keep the script up to date.
Now on every of those website, they can add the form with company.form.append(someDiv) and when you update the script the update will be available on all websites.
Okay, there is solution for you. Your embed code like this;
<script>
var url = 'http://www.maxcashtitleloans.com/lmapp.js'
document.write('<script src="'+url+'"></scr'+'ipt>')
</script>
And http://www.maxcashtitleloans.com/lmapp.js like this :
function ajaxex()
{
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200){
document.write(xmlhttp.responseText);
}
}
xmlhttp.open("GET","lmapp.htm",true);
xmlhttp.send();
}
ajaxex();
Thats work fine. And demo for you : http://commention.com/lmappjsexample/
That solution like javascript proxy, you have to create a javascript file for render your html page.
You can use simple jQuery:
<script>
$('body').load(url);
</script>
well, a <script> tag is for including javascript, not HTML. You want to look into ajax. You want to load the html file via ajax into a div.
Alternatively, leave it as an iframe. Iframes are for including one page into another.
Edit
The example you included from the affiliate is meaningless for you. They are loading javascript that is generated programmatically from a PHP server side script based on input from client side cookies. You are trying to load en external html file, these are two different tasks.
javascript in your HEAD tag
<!-- Include the jquery library - never re-create the wheal -->
<script type='text/javascript' src='http://code.jquery.com/jquery-1.9.1.min.js'></script>
<script type='text/javascript'>
$(document).ready(function() {
// Run once the page is loaded
$('#putFormHere').load('http://www.maxcashtitleloans.com/lmapp.html');
});
</script>
Replace your current iframe with this
<div id='putFormHere'></div>
Assumption
I'm assuming that www.maxcashtitleloans.com is the same domain as your current page. If not then they only way to do this is via an iframe. Javascript will not support cross-site scripting.
Script tags do not HTML rendering. You have to add HTML render to your html page. Maybe you can add this code to your html page. This code render your html codes on javascript.
document.write($(body).html());