Chome extension prevents <select> elements from expanding - javascript

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.

Related

Load more button with ajax request trigger only once

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.

Load Div Content from Another Page

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():
} );

Refresh browser / link and still "hit" javascript-function

I have created a list through normal html which have this link to a "details" page. URL: index.php?page=userDetails&usersId=10. This may be changed if I get the correct solution for my challenge :)
At the "details page" I have made a dropdown which basicly insert (GET) a id to PHP and PHP generates content.
The dropdown looks like this
<select name="users" onchange="showUser(this.value)" class="selectpicker">
<option data-tokens="10" value="10">user-10</option>
<option data-tokens="41" value="41">user-41</option>
<option data-tokens="9" value="9">user-9</option>
<option data-tokens="8" value="8">User-8</option>
</select>
<!-- This is where PHP-content will be printed..... -->
<div id=\"txtHint\"><b>Person info will be listed here...</b></div>
Javascript looks like this (function showUser)
function showUser(
{
if(str == "")
{
document.getElementById("txtHint").innerHTML = "";
return;
}
else
{
if(window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","logic/do.php?action=ajaxReceive&input="+str,true);
xmlhttp.send();
}
}
The Id (from database) is received as $_GET[input] and everything actually works fine, and I can print ID at the moment.
My problem is 2 things:
1) When I refresh browser the ID is not stored. I suppose this can be done by cookie or session, but how do I keep the ID and "insert" it into the function so I stay on user 8, 10, 14 or what ever user I was looking at?
2) The same problem is the actual link where I link from one page to a whole other page. This is neccesary since I am no super-expert so I am reluctant to run everything as pure javascript/jQuery. I fix things best at PHP-side so sometimes I need a little breath :)
I hope you understand my probably rather basic problem...
I am looking forward to some input concerning my little challenge :)
Cheers Nikolaj
You could use window.onbeforeunload to execute a script/function before a page is unloaded. You could send the userID to your PHP script and let that store the userID.
HTML
<element onbeforeunload="yourFunction()">
Reference: http://www.w3schools.com/tags/ev_onbeforeunload.asp
Javascript
window.onbeforeunload = function() { /* Your function send to e.g. PHP here */ }
jQuery
$(window).on('beforeunload', function(){ /* Your function send to e.g. PHP here */ });

Automatic refresh using AJAX not working?

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.

How can I embed an existing multi-level drop down menu without inserting the whole code?

I have a multi-level drop down menu (done using HTML + CSS) that I want to put on a number of different pages. In the future I will need to update this menu and change its contents, so I have saved the HTML in its own file so that I can roll out the changes to all the pages at once (instead of having to go through each page and repeatedly paste in the changed list items).
I have tried using iframe, but this cuts off the menu items with its limited height (setting a manual height that's big enough would leave tons of blank space, of course):
<iframe height="100%" src="menu.html" frameborder="no" width="100%" scrolling="no"></iframe>
I also tried using embed (this looks fine until you mouse over the menu items -- it just scrolls within the frame):
<embed type="text/html" src="menu.html" width="100%" height="100%"></embed>
The menu functions fine when the code is simply dumped into the individual pages I need it on, so I know that's not the issue. It's the embedding and calling it from its own HTML file that is the problem. Is there a simple way to do this that will allow the drop-down menu to appear as it should?
I should mention that while I have my IT department's blessing to do this, this is a project that they aren't supporting. I can only edit the HTML of my webpages in the body, and not the head. The exception being HTML pages I upload as files (like the menu code). So there are some constraints.
Well here is a bit of a long winded javascript approach that might keep your IT guys happy:
window.onload = new Function("load('embed-me.html','content')"); // Replace with URL of your file and ID of div you want to load into.
function ahah(url, target) {
document.getElementById(target).innerHTML = ' Fetching data...';
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req != undefined) {
req.onreadystatechange = function() {ahahDone(url, target);};
req.open("GET", url, true);
req.send("");
}
}
function ahahDone(url, target) {
if (req.readyState == 4) { // only if req is "loaded"
if (req.status == 200) { // only if "OK"
document.getElementById(target).innerHTML = req.responseText;
} else {
document.getElementById(target).innerHTML=" AHAH Error:\n"+ req.status + "\n" +req.statusText;
}
}
}
function load(name, div) {
ahah(name,div);
return false;
}
Not written by me(LINK) (I just added the run on page load bit).
Tested and working (in Chrome at least). Though your site will have no menu if the user has javascript disabled!
EDIT:
Example...
<body>
<script type="text/javascript" src="embed-me.js"></script> <!-- load the javascript -->
<div id="content"></div> <!-- html will be embedded here -->
</body>
I use the following php code and works very nice. It doesn't even show when you check the source code online.
<?php include("menu.php"); ?>
Use php Include !!
Okay first.. copy the menu code and save it on to a file called menu-1.php
then whenever you want to use your menu; just type the following code:
<?php include("menu-1.php"); ?>
This is a good way to do menu's because every time you need to update your menu, you wont have to update every single page, just update your menu-1.php
P.S. PHP might not show up on your local machine unless you are using wamp or xamp

Categories

Resources