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.
Related
I am pretty new to creating web applications, so I am very unfamiliar with working over a web server. Just to let everyone know, I am implementing html, javascript, strawberry perl, AJAX, and running over an APACHE 2 web server. I finally have my web app working, I have an html file that calls a perl script that is in my htdocs directory. Here is a mock up of my .html file for reference, this one simply alerts the user of the output printed by the perl script:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
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()
{
var str;
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Get output from perl script and print it
str = xmlhttp.responseText;
alert(str);
}
}
xmlhttp.open("GET","http://localhost/try.pl" , false); //perl script
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Example</h2></div>
<button type="button" onclick="loadXMLDoc()">Display</button>
</body>
</html>
So this file test.html calls a perl script [try.pl] within the same directory. Also, the perl script just prints a number so this alerts the user of the number. This is just an example of my implementation. My actual perl script and java script [inside the ready state block] is much more complicated. Now I have to add functionality to my web app, so to my questions:
I am looking to run a second and separate perl script when a different event happens. For example, when a button is clicked this perl script is being ran. I am going to have another different event, say a double click on an icon or something, that will need to call this second perl script. Will I simply have the new event call a different function [the first is called Loadxmldoc()] that is almost identical to the one I have here except it will have different code in the ready state block and call a different perl script at the end of it? I am a little confused as to how to implement this.
Also, If I have a list of file names within my javascript code, I need to process EACH of the files using a perl script. Currently I am only processing one so calling the perl script as I have here is fine. I have looked all over the internet to try to find how I would do this but it seems every explanation just covers how to call "a" CGI script. So within my code, say where I am "alerting" the user, I am going to have an array that stores the file names. I need to iterate over this array and for each filename [array element] I need to call the same perl script to process that file. How should I go about implementing this? Currently, my html file is only calling the perl script once and I do not know how I could call it for EACH file since my GET command is outside of my ready state block...
Any help or direction would be appreciated. I am expected to deliver soon and have been spending way too much time sifting through repetitive examples that haven't helped me...:/
As far as generalizing your AJAX request, you can create a function (or rather, a set of functions) that would process different types of responses, as follows:
var requests = [];
requests['script1'] = "http://localhost/try.pl";
requests['script2'] = "http://localhost/try2.pl";
var response_processing = [];
response_processing['script1'] = function (xmlhttp) {
var str = xmlhttp.responseText;
alert(str);
};
// Here, you can add more functions to do response processing for other AJAX calls,
under different map keys.
Now, in your AJAX code, you call an appropriate request AND appropriate response processor, based on your script name (passed to loadXMLDoc() call as follows): loadXMLDoc("script1");
function loadXMLDoc(script_name) {
// Your generic AJAX code as you already implemented
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
response_processing[script_name](xmlhttp);
// Careful so script_name doesn't get closured in onreadystatechange()
}
}
xmlhttp.open("GET", requests[script_name], false); //perl script
xmlhttp.send();
}
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).
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 am calling a ajax method to update a div. It contains links and functions which require java script files. But these methods and functions are not getting called properly as java script files are not getting included through ajax call. For example, i am trying to call a light box function, but it gets redirected to different page and not in light box.
Thanks in advance, Anubhaw Prakash
The Ajax framework in prototype will properly execute the text content of <script> tags, but will not import new script files via <script src="somefile.js"/>. The only solution I came up with is to import all javascript files I need in the head of the page. That way the functions in the imported file are available to the inline javascript code executed in the Ajax response.
I had a similar problem, where I did want to postload some javascript. What I did is separating loading the html-fragment and loading the script into two calls. For loading the script I call the following function (I have JQuery handling the ajax part):
function loadModule(name, callback) {
$.ajax({type: "POST"
, url: "/js/" + name
, dataType: "script"
, success: callback
});
}
I see you're using Ruby on Rails — does that mean you're using Prototype on the client? If so, Prototype's Ajax.Updater will ignore script tags that reference external files (it will evaluate script tags that have their contents inline). So to add those external files to your page, you'll have to hook into the process via the onSuccess callback, look in the responseText for script tags with src attributes, and handle those yourself. Once you've identified the relevant script tags and extracted their src attributes, you can include them by dynamically adding the scripts as described in this article from the unofficial Prototype & script.aculo.us wiki.
<script> tags written to innerHTML are not executed at write-time. You can do element.getElementsByTagName('script') to try to get hold of them and execute their scripts manually, but it's very ugly and not reliable.
There are tedious browser differences to do with what happens to a <script> element written to innerHTML which is then (directly or via an ancestor) re-inserted into the document. You want to avoid this sort of thing: just don't write <script>s to innerHTML at all.
Then you also don't have to worry about executing scripts twice, which is something you never want to do with library scripts. You don't want to end up with two copies of a function/class that look the same but don't compare equal, and which hold hooks onto the page that don't play well with each other. Dynamically-inserted library scripts are a recipe for confusing failure.
Much better to include your scripts statically, and bind them to page elements manually after writing new elements to the page. If you really need to you can have your AJAX calls grab a JSON object containing both the new HTML to add and a stringful of script to execute.
May want to try running some prepatory javascript in the :before option to setup a variable with the correct files?
hey i found a way to add it....:)
NOTE- this is a synchronous process so you dont have to worry about that the script is loaded or not.... the script will always load the instance u call the function and you can start using the loaded script instantaneously..
lets use these 2 functions
1) first one is the ajax function to retrieve the values
where async should be true to send the request synchronously
// AJAX FUNCTION
function loadXMLDoc(reqt,url,reqp,cfunc,async)
{
var xmlhttp;
try// code for IE7+, Firefox, Chrome, Opera, Safari
{
xmlhttp=new XMLHttpRequest();
}
catch(err)// code for IE6, IE5
{
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
try{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch(E){}
}
}
if(!xmlhttp)
{
alert("error");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
cfunc(xmlhttp.responseText);
}
}
if(reqt=='GET')
{
url+=(reqp!=""?"?":"")+reqp;
xmlhttp.open("GET",url,(async?false:true));
xmlhttp.send();
}
else if(reqt=='POST')
{
xmlhttp.open("POST",url,(async?false:true));
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(reqp);
}
else
{
return false;
}
}
/*use this function
loadXMLDoc(reqt,url,reqp,function(response){
});
*/
2)then we use ajax to load the js file as string and then append it to the new script tag's innerHTML and then append it to the head section and one more thing to ensure file is already loaded i used the id of script tag as the path to the file which makes it really easy task to check for the duplicate...:)
//add new script dynamically
function add_script(src)
{
if(!document.getElementById(src))
{
loadXMLDoc("GET",src,"",function(jsresp){
var head = document.getElementsByTagName("head")[0];
var script=document.createElement("script");
script.type='text/javascript';
script.id=src;
script.text=jsresp;
head.appendChild(script);
},true);
}
}
thanks for all help i used to get and will get from this site and its users for the development purposes...
regards VIPIN JAIN
include static scripts on pages that need to use them (IE contain a lightbox, then include the lightbox script)
Problem solved. Do not load scripts using AJAX
Make necessary function calls to the static scripts using AJAX callbacks