I got a problem where preventDefault() are not working properly.
This ajax request is working and I get the php page to show in the selected div, but the preventDefault is not working. For the map area that have a link I got redirected to the page, and for the ones that have no link, the address bar got an added "#" to the url. (in this last case, the ajax calls get correctly appended to the div, but still, preventDefault not doing its job).
After doing some digging I found out something : stopImmediatePropagation()
I was really hyped by this for a few seconds before seeing that it had absolutely no effect on my side too. I must be missing something but I can't find it.
More infos: The website is on joomla 3x, on localhost and showing K2 itemview categories on this ajax request.
Any help really really welcomed.
window.addEventListener('DOMContentLoaded', (event) => {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
let links = document.querySelectorAll('map area')
console.log(links)
for (let i = 0 ; i < links.length ; i++) {
let link = links[i]
link.addEventListener('click', function (e) {
e.preventDefault
e.stopImmediatePropagation()
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('maploc-loc').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", '../index.php?option=com_k2&view=itemlist&layout=category&task=category&id=1&id=Itemid=1',true);
xmlhttp.send();
})
}
});
Related
I have checked all the similar questions to this but not found anything that helped... so here goes!
I am writing designing a site for my college project. It simply is an image gallery. I have a counter displayed for each image that increments each time the image is clicked. When the page refreshes the new number is displayed. With me so far?
The problem is that after the database update is completed the return does not complete the rest of the code...
echo "<div class='gridImg'><a href=".$imgpath." data-lightbox='countryside' data-title='".$row['ldesc']."' onclick='"."showUser('".$fname."')'>";
The above line is in a php file and the function in question is showUser, which passes a variable $fname...
function showUser(str) {
if (str === "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML =
this.responseText;
}
};
xmlhttp.open("GET","../php/countrysideupdateviews.php?q="+str,true);
xmlhttp.send();
return;
}
}
The above script takes the passed value and hands it over to countrysideupdateviews.php (Sorry if this script is a mess, I am new to AJAX and took it from the W3Schools site.
<?php
$q = $_GET['q'];
$conn=new mysqli('localhost','user','pass','dbname');
$sql="UPDATE countryside SET views = views + 1 WHERE fname = '".$q."'";
$result=$conn->query($sql);
mysqli_close($conn);
?>
The above php file updates the database.
Ok...
So, a user clicks on one of the images on-screen, which opens a lightbox gallery, BUT also updates the view count and then returns control - except that everything works - the update takes place - but the lightbox does not start, instead a static larger image of the one that was clicked is shown. The only way to clear it is to refresh the site, which does reflect the updated counter.
I have added returns to the onclick function call which does return control but the counter is not updated. Where am I going wrong? Bear in mind please I am still learning and I hope this makes sense :)
The argument to onclick must be a function. showUser("foo") is not a function. You're also missing event.preventDefault() which prevents the click action from opening the link.
Change your showUser to
function showUser(str) {
return function(event) {
if (str === "") {
document.getElementById("txtHint").innerHTML = "";
} else {
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../php/countrysideupdateviews.php?q="+str,true);
xmlhttp.send();
}
event.preventDefault();
};
}
Ok, after playing around with #apaatsio's answer I got it working, this is what the function now looks like...
function showUser(str) {
if (str === "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","../php/countrysideupdateviews.php?q="+str,true);
xmlhttp.send();
event.preventDefault();
}
}
It looks like preventing the click opening the link worked just fine - thanks :)
I'm trying to update a status page live.
I'm using Ajax to update the page. The update is set to update every 3 seconds. But whenever the update is being called the browser freeze at least for a second or two.
<script type="text/javascript">
window.onload = updateStatus;
function updateStatus() {
updateinfo();
setTimeout(updateStatus, 3000);
}
function getJson(theUrl, update) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
update(xmlhttp.responseText);
}
}
xmlhttp.open("GET", theUrl, false);
xmlhttp.send();
}
function updateinfo() {
getJson('backend/status', function(update) {
var jsono = JSON.parse(update);
document.getElementById('name').innerHTML = jsono.name;
document.getElementById('online').innerHTML += jsono.online;
document.getElementById('ip').innerHTML = jsono.ip + ':';
document.getElementById('ip').innerHTML += jsono.port;
document.getElementById('memory').innerHTML = jsono.memory + " MB";
});
}
</script>
If someone can give me tips on improving this. To make it less laggy or make it go away.
2) I have been thinking about using JQuery. Should I make the move? Pros and Cons? Also how is JQuery performance wise comparing to just JavaScript ?
You are letting the AJAX request run synchronously - which you never ever need to so, since that prevents it from being AJAX in the first place, because the A stands for asynchron.
Change the third parameter of the xmlhttp.open call to true (or just leave it out, since that is the default).
Hey guys, this is driving me absolutely insane so I wanted to ask the experts on this site to see if you know how to do it =)
I'm trying to create some javascript code that can read out elements of a web page (eg. what does the first paragraph say?). Here's what I have so far, but it doesnt work and I cant figure out why:
<script type="text/javascript">
<!--
var req;
// handle onreadystatechange event of req object
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
//document.write(req.responseText);
alert("done loading");
var responseDoc = new DOMParser().parseFromString(req.responseText, "text/xml");
alert(responseDoc.evaluate("//title",responseDoc,null,
XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue);
}
else {
document.write("<error>could not load page</error>");
}
}
}
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", "http://www.apple.com", true);
req.send(null);
// -->
The alert that keeps appearing is "null" and I can't figure out why. Any ideas?
This may be due to cross domain restriction... unless you're hosting your web page on apple.com. :) You could also use jQuery and avoid writing all that out and/or dealing with any common possible cross-browser XML loading/parsing issues. http://api.jquery.com/category/ajax/
Update:
Looks like it may have something to do with the source web site's Content-Type or something similar... For example, this code seems to work... (Notice the domain loaded...)
var req;
// handle onreadystatechange event of req object
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
//document.write(req.responseText);
//alert("done loading");
//alert(req.responseText);
var responseDoc = new DOMParser();
var xmlText = responseDoc.parseFromString(req.responseText, "text/xml");
try{
alert(xmlText.evaluate("//title",xmlText,null,XPathResult.FIRST_ORDERED_NODE_TYPE,null).singleNodeValue);
}catch(e){
alert("error");
}
}
else {
document.write("could not load page");
}
}
}
req = new XMLHttpRequest();
req.onreadystatechange = processReqChange;
req.open("GET", "http://www.jquery.com", true);
req.send(null);
I also tried loading espn.com and google.com, and noticed they both have "Content-Encoding:gzip" so maybe that's the issue, just guessing though.
I'm dynamically loading content into a div when the user clicks a link using this code:
function ahah(url, target) {
document.getElementById(target).innerHTML = 'Opening form...';
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;
}
This works fine, however I can't get any javascript to work in this new content, such as a jquery datapicker, or even just a document.write hello world. The js in there in the code, just not working. I've loaded the content directly in a browser and it works fine.
I'm at loss, any ideas greatly appreciated!
If you are using jquery anyways, might as well try using jquery.ajax().
You could include whatever scripts you need in the <head> and then call your datepicker or w/e in the callback function of your jquery ajax call.
After pressing a button, I'm sending the whole HTML content from a webpage (the part within the <html> tags) to a CGI script which manipulates the content and sends it back.
Now I'm trying to replace the existing content with the new one. Unfortunately after assignment, every single <head> or <body> tag (as well as the closing ones) will be killed.
By using some alerts I looked through the returning value as well as the original HTML stuff. Both are absolutely as expected.
But after the assignment there is some magic going on. Please help me to figure out what's going on.
Here is the used JavaScript code I used:
var originalBodyInnerHTML = document.body.innerHTML;
var htmlNode = document.getElementsByTagName('html')[0];
var post_parameters = encodeURIComponent(htmlNode.innerHTML);
makePOSTRequest("POST", "http://whatever.com/cgi-bin/doit.cgi", post_parameters, htmlNode);
function makePOSTRequest(method, url, parameters, htmlNode) {
var http_request = getRequestObj();
if (!http_request) {
alert('Cannot create XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function()
{
if (http_request.readyState < 4)
{
var waitingPageBody = '< img src="/img/ajaxloader.gif" alt="in progress..."/>';
document.body.innerHTML = waitingPageBody;
}
else //if (http_request.readyState == 4)
{
if (http_request.status == 200)
{
alert('1response: ' + http_request.responseText);
alert('2innerhtml: ' + document.getElementsByTagName('html')[0].innerHTML);
document.getElementsByTagName('html')[0].innerHTML = http_request.responseText;
}//end of if (http_request.status == 200)
else
{//other http statuses
alert("There was a problem (" + http_request.statusText + ", " + http_request.status + ' error)');
bodyNode.innerHTML = originalBodyInnerHTML;
}
}//end of else if http_request.readyState == 4
}
http_request.open(method, url, true); //async
http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http_request.setRequestHeader("Accept", "application/atom+xml,application/xml,text/xml");
http_request.setRequestHeader("Connection", "close");
http_request.send(parameters);
}
function getRequestObj() {
var http_request = false;
if (window.XMLHttpRequest)
{ // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/html');
}
}
else if (window.ActiveXObject)
{ // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return http_request;
}
This is a simple solution that worked for me. Just as a reference.
document.clear();
document.write(newHtml);
where newHtml is the complete html of new web page.
well, with this
document.getElementsByTagName('html')[0].innerHTML = http_request.responseText
you are replacing everything insidee the html, "killing" body, head and everything...
maybe you wanted
document.body.innerHTML = http_request.responseText
Also, I'd use jquery, it makes your life sooo much easier
You cannot do that. It's not possible to replace the contents of the whole html tag. You can get away with replacing only the contents of the body tag. The head element is kind of magical and browser generally don't support replacing it.
If you want to change the whole document, redirect to it.
If you want to change only parts of the head, try sending them in a different form (like JSON), and make appropriate changes using javascript APIs.
Thanks qbeuek for your answer!
To change only the header, Firefox in fact will allow something like this:document.getElementsByTagName('head')[0] += "e.g. some scripts"
But for Internet Explorer it is necessary to add each element separately to the DOM tree.
var script = document.createElement("script");
script.setAttribute('type','text/javascript');
objHead.appendChild(script);
However, it is really weird that Firefox behaves like this and not popup with some error...