I'm trying to write my first Firefox-Extension. The extension is supposed to display FOAF-Files in a nice way using XSLT. Right now I just want to add the XSL Stylesheet to the rdf file when I press a button. The function is called but the presentation of the rdf-file does not change.
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send("");
return xhttp.responseXML;
}
function displayMyResult()
{
alert("test")
xml=loadXMLDoc("http://www.example.com/me.rdf");
xsl=loadXMLDoc("http://www.example.com/test.xsl");
if (window.ActiveXObject)
{
ex=xml.transformNode(xsl);
content.document.location.replace(ex)
}
// code for Mozilla, Firefox, Opera, etc.
else if (document.implementation && document.implementation.createDocument)
{
xsltProcessor=new XSLTProcessor();
xsltProcessor.importStylesheet(xsl);
resultDocument = xsltProcessor.transformToFragment(xml,document);
content.document.location.replace(ex)
}
}
The first function loadXMLDoc is copied from another post here, and should probably work. The Probem is in the displayMyResult Method. The test alert confirms, that the function is called but the me.rdf file is not displayed any different.
I believe that the line content.document.location.replace(ex) is wrong but have not found anything on the web that would explain to me what to use instead.
Can anybody tell me how to load the XLST stylesheet to present the RDF File?
Why does your code intended for a Mozilla extension do checks for IE objects like "ActiveXObject"?
Anyway, your code does not make much sense, your Mozilla branch never assigns to the variable named ex, yet you then call replace(ex).
Some more meaningful code would be
var resultFragment = xsltProcessor.transformToFragment(xml, content.document);
content.document.replaceChild(resultFragment, content.document.documentElement);
But I am not sure that will work in general, in particular if content.document is of a different type than the result document of the XSLT (i.e. one being an HTML document, the other being an SVG document).
Related
So I have some code, which checks for whether a one time use discount code exists, and if so, it applies it and then marks it as used in the database. The problem is, it ends up being useable more than once if you spam click it, and then some time maybe 15-20 seconds later it stops being useable.
The relevant javascript component:
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) {
discountAmount += parseFloat(xmlhttp.responseText);
modifyCartOrder();
}
}
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
xmlhttp.send();
This is processed over in the php file, and when a match is found we echo that amount and then delete the entry
$mysqli->query("DELETE FROM discounts_available WHERE `index`=$index");
The php file is indeed doing what its supposed to. When you click apply code, it is immediately deleted from the database. The problem is, even with the code no longer in the db, you can still apply the code over and over for some amount of time before the js file finally realises there is no entry in the db. Why is this?
You should first check if it exists in DB then only you should proceed with request, it should be very first statement.
If it does not exists you can send response saying code already applied.
You most likely need to lock the table ASAP so no other instances can modify the table concurrently.
http://dev.mysql.com/doc/refman/5.0/en/lock-tables.html
I did not get your problem, exactly I am assuming lost of things, so..
//this is triggered on some click, right?
//TODO:- check if button is disabled? you can have some js variable or check button attribute disbled
//TODO:-if its not disaled->{so first disable the button when it is clicked } else do nothing
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) {
discountAmount += parseFloat(xmlhttp.responseText);
// if succefull keep button disabled
// else renable it, so that it can be clicked again.
modifyCartOrder();
}
}
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
xmlhttp.send();
thers's no syntax problem here in your code its logical,
ajax call is asynchronous call, it does not happen in sequence
1) You clicked
2) Request Sent
3) Request Processed
4) JS is informed : your modifyCartOrder function executed
what I am trying to say here is that, there is no 3 immediately after 2, 3 will take time to start, js has no control over it, whenever php is done it will reply there's no guarantee. so you can repeat 1 again and again, and 2 will keep repeating... and so 3 will...
I hope I understood your problem, and you understood what I am trying to say :)
Problem is : You are sending asynchronous ajax calls from following code :
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,true);
Solution : as defined , for opening an ajax call , method is :
xmlhttp.open(method,url,async)
So, You have to modify above line as:
xmlhttp.open("GET","forms/jsPromoCode.php?code="+code+"&type="+order_name,false);
I've this function to make an ajax request:
I want to replace content in
var dialog_body = document.querySelector('#dialog .body')
in page1.php with the content of
page2.php#load
that is located in
var href = 'page2.php'
.......
function load(div_where_change, url) {
var xmlhttp;
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) {
div_where_change.innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
load(dialog_body, ref+'#load');
And It doesn't work..
My final process is similar to jquery load, but I wanna use only vanilla js and I've not found any documentation or article for load only one element of another page, but only full page load......
Please help me..
function getPage(url, from, to) {
var cached=sessionStorage[url];
if(!from){from="body";} // default to grabbing body tag
if(to && to.split){to=document.querySelector(to);} // a string TO turns into an element
if(!to){to=document.querySelector(from);} // default re-using the source elm as the target elm
if(cached){return to.innerHTML=cached;} // cache responses for instant re-use re-use
var XHRt = new XMLHttpRequest; // new ajax
XHRt.responseType='document'; // ajax2 context and onload() event
XHRt.onload= function() { sessionStorage[url]=to.innerHTML= XHRt.response.querySelector(from).innerHTML;};
XHRt.open("GET", url, true);
XHRt.send();
return XHRt;
}
arguments:
getPage(
URL : Location of remote resource ,
FROM : CSS selector of source tag on remote page ,
TO: CSS selector of destination tag
)
EX 1. (typical use) virtually grab the next page:
when on http://www.codingforums.com/forumdisplay.php?f=2
show table from http://www.codingforums.com/forumdisplay.php?f=2&order=desc&page=2
getPage("/forumdisplay.php?f=2&order=desc&page=2",
"#inlinemodform",
"#inlinemodform" );
notice how "#inlinemodform" is repeated? It's moving the same block to the same block on another page.
You can omit the 2nd CSS selector when it's a duplicate, so the following is 100% equivalent to the above:
getPage("/forumdisplay.php?f=2&order=desc&page=2",
"#inlinemodform" );
EX 2. (defaults) replace this whole page with another post :
getPage("http://www.codingforums.com/showthread.php?t=281163")
EX 3. (external content) inject event listings from UIUC into the current page:
getPage("//www.it.illinois.edu/news/", ".list.events.vcard.clearfix", ".tcat" )
one difference from $.load() is that script tags on the remote page are not executed, which i rather like. Prototype.js has a good script-tag-finding regexp that you can use to eval inline scripts, and you can re-add the urls of any .src-based scripts if you need all that functionality. I also cache the fetch in sessionStorage, so if your external content rotates or updates, use a random query param or remove the sessionStorage check by changing the 2nd line to var cached="";
EDIT: fixed a really dumb bug i created when renaming the variables for public readability; forgetting one.
I'm trying to use JavaScript to manipulate page content in a dummy webpage I'm building.
To that end, I wrote a little function called writeText(file_name, location) that gets a HTML file specified by the file name, and prints the content of that file to the innerHTML of a pair of <div> tags whose id attribute correspond to the location field.
I then wrapped the calls in other functions to automate building full pages like this.
So I call something that looks like this:
function displayHome() {
writeText('homeMain.html', 'mainFrame');
writeText('homeSide.html', 'sideFrame');
}
...to display the home page.
However, when I call this function, the display only updates the 'sideFrame' object and doesn't make any changes to the content of 'mainFrame'. But if I interrupt the function with an alert("Dummy") between the two writeText() calls, then both of the contentFrames update correctly.
I was wondering if anyone has seen anything like this before, and if anyone knows how to fix it.
For completeness' sake (this was copied nearly verbatim from the w3schools website):
function writeText(script_file, location) {
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
document.getElementById(location).innerHTML = xmlhttp.responseText;
}
xmlhttp.open("GET",script_file,true);
xmlhttp.send();
}
You are using a global variable xmlhttp, so it gets clobbered the 2nd time the function runs. The request itself is asynchronous, so the second call runs while the first one is still running.
To fix this, use a local variable instead (so each call to the function has its own xmlhttp) by using the "var" keyword before xmlhttp:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
I am using a simple "live search" script that displays the results from a MySQL database as the user types into a text box. It works perfectly fine if the Javascript is pointing to a completely separate page but I need it to point to the same page. Unfortunately when I try and do this the page is duplicated within itself as the results are generated.
This works as expected:
Document called: "test.php" containing JavaScript below and test2.php containing the PHP code
xmlhttp.open("GET","test2.php?livesearch="+str,true);
xmlhttp.send();
This creates a page within a page:
Document called: "test.php" containing both the JavaScript and PHP code below
xmlhttp.open("GET","?livesearch="+str,true);
xmlhttp.send();
I understand that it's because it is opening itself in a loop but I'm not sure what I am supposed to change in the code to avoid this. Any help would be greatly appreciated as I haven't found much help via Google.
Here is all my code:
Javascript
function showResult(str)
{
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("livesearch").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","&livesearch="+str,true);
xmlhttp.send();
}
PHP Code
if(isset($_GET['livesearch'])) {liveSearch();}
function liveSearch() {
$q=$_GET["livesearch"];
$sqlQuery = "SELECT * FROM something WHERE something LIKE '%" . $q . "%' ;
etc etc etc
}
Why would you want the code to point to itself? Seems logical to have a web service that would return only the content that is needed. It is not like you have to duplicate the code, just make some common method that spits out the content in the full page or in the web service.
If you need to call the same page, you can always use a regular expression to rip out the content that you need instead of replacing the whole page.
I have a small JS function that does Ajax for me and another like it that adds in POST data to the request. With Ajax being such a big topic with so many libraries about it, what am I missing from my function, is it insecure or something else worrying?
function loadPage(pagePath, displayElement)
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
document.getElementById(displayElement).innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open("GET", pagePath, true);
xmlHttp.send(null);
}
I strongly recommend you not roll your own Ajax code. Instead, use a framework such as Prototype, Dojo, or any of the others. They've taken care of handling all the ReadyStates you're not handling (2 means it's been sent, 3 means it's in process, etc.), and they should escape the reponse you're getting so you don't insert potentially insecure javascript or something into your page.
Another thing a more robust framework will give you is the ability to do more than just use innerHTML to replace items in the DOM. Your function here can only be used to replace one element with the response from the ajax call. There's a lot more you can do with Ajax.
I would remove this line.
alert("Your browser does not support AJAX!")
Shouting at the user in a language he probably doesn't understand is worse than failure. :-)
I've never been a fan of nested try/catch blocks, so I'd do it something like:
var xmlHttp;
if (window.XMLHttpRequest) {
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (xmlHttp) {
// No errors, do whatever you need.
}
I think that'll work. But as has been mentioned before - why reinvent the wheel, use a library. Even better - find out how they do it.
jQuery is probably one of the lightest popular libraries out there.
The same thing in prototype:
function loadPage(pagePath, displayElement) {
new Ajax.Updater(displayElement, pagePath);
}
Ajax.Updater in Prototype API
If you really want to see what you are missing, read the jQuery or Prototype source code for their ajax routines. If there are bug numbers in the comments, look those up as well.