I have a form with a variable number of text boxes that contain an id. When the user exits the page, files on the server are deleted by a python script (delete.py). The filename of the files to delete contains the id so the id has to be passed to the python script. If my form has a single id, everything works perfectly and the file on the server is deleted. If my form has multiple id fields, no files get deleted. If I use firebug to step through the code, the files gets deleted regardless of the number of id fields. I don't understand what is going on. Any help would be greatly appreciated. My onbeforeunload method is below.
function deleteFiles()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
allElements = document.getElementsByName("id");
for (x=0; x < allElements.length; x++)
{
xmlhttp.open("GET","/cgi-bin/delete.py?id=" + allElements[x].value,true);
xmlhttp.send();
}
window.onbeforeunload = deleteFiles;
Sounds like the request's are being sent too fast. Try adding
xmlhttp.async = false;
function deleteFiles()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
allElements = document.getElementsByName("id");
xmlhttp.async = false;
for (x=0; x < allElements.length; x++)
{
xmlhttp.open("GET","/cgi-bin/delete.py?id=" + allElements[x].value,true);
xmlhttp.send();
}
window.onbeforeunload = deleteFiles;
Let me know your findings
Related
My webpage features a table where each row has a "+" button so that a mini table appears. The mini table houses data from a super slow database so I am having the data come in through ajax requests. My problem is rooted in a certain situation. Suppose you pressed a plus button causing an AJAX request and while waiting you press another plus button. The second ajax request causes the first request to never come back. In other words the newest request overwrites all previous pending requests. Any idea why this might be happening? I feel like this might just be what happens when you don't use jQuery to handle AJAX but I am not sure and I couldn't find anything that said that was the case. I am appending my code below. Any help is appreciated!
function fetchSINamesForVariantAJAX(latestBuild, variantToExpand){
if (latestBuild == "") {
//document.getElementById(subTableId).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) {
spinner.stop();
var variantRow = variantToExpand + "Row";
if (document.getElementById(variantRow).rows.length == 1){
var json = JSON.parse(xmlhttp.responseText);
var SINames = json['SIs'];
var locations = json['locations'];
var SIBuilds = json['SIBuilds'];
for (var i = 0; i < SINames.length ; i++){
var row = document.getElementById(variantRow).insertRow(-1);
var cell = row.insertCell(-1);
var SILinkURL = "exampleWebsite.com/name.php?names=" + SINames[i];
cell.innerHTML = "" + SINames[i] + "";
cell = row.insertCell(-1);
var fullLocation = locations[i] + "\\" + SIBuilds[i];
cell.innerHTML = "" + fullLocation + "";
cell = row.insertCell(-1);
cell.innerHTML = "";
}
}
}
}
//create the GET message to be sent using AJAX window
var stateToSend = "SITableGeneratorFromVariant.php?";
stateToSend += "latestBuild=" + latestBuild;
xmlhttp.open("GET", stateToSend, true);
xmlhttp.send();
}
}
I think the reason is that you overwrite your xmlhttp variable with a new one each time a new AJAX call gets done try declaring it inside the function:
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
var xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
I have a JSON Object getting a list of images I have on the page. The images are generated at random using a database. I want to keep adding to the images using AJAX whn the user for example clicks "show more". The images src are found so that no duplicates are pulled from the database on the AJAX call.
I want to know how to parse this array to the pHp file to perform an SQL statement to get more images to append to the images list. In the php file how would I select the elements from there. So SELECT * FROM images WHERE image_src NOT IN (JSON array) ORDER BY rand() LIMIT 12
CODE
var imageArray = {};
imageArray.itemList = [];
function imagesLoaded(){
var gal_img_thumbs = document.getElementsByClassName("gal-thumb-image");
for (var i = 0; i < gal_img_thumbs.length ; i++){
var img = gal_img_thumbs[i].firstChild.getAttribute("src");
var new_obj = {'src':img};
imageArray.itemList.push( JSON.stringify(new_obj));
//imageArray.itemList.[i]['src']=img;
}
}
function loadImages(){
console.log("load images");
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","getimages.php?imgArray="+imageArray.itemList,true);
xmlhttp.send();
}
Here is some background: I have a text file that is broken down into context blocks. Each block has a header of a pattern "[header]". So far, I have been able to create a php script that will search for these headers and generate a list of only the headers.
What I have not yet been able to figure out is how to supply these results to a web page that will take this list and generate a drop-down/select box with the list as options. Here is the php script:
<?php
$theList = array();
$theInFile = 'extensions.conf';
$theLine = '';
$theReturnString = '';
$inFile=fopen($theInFile, 'r') or exit('Unable to open file.');
while(!feof($inFile))
{ $theLine = fgets($inFile);
$theLine = (string)$theLine;
// Is it a context header?
// Check for the presence of a '[', then the position of '['
// This method is used due to STRPOS returning ZERO if not found,
// which is the position we are looking for.
$x = strstr($theLine, '[');
if ($x != '')
{ $y = strpos($theLine, '[');
if ($y == 0)
{ // Only the context name itself is wanted.
// If there is anything after the ']', strip it.
$end = strlen($theLine);
$tBracket = strpos($theLine, ']') + 1;
if($end != $tBracket)
$theLine = substr($theLine, 0, $tBracket);
$theReturnString = $theReturnString.$theLine.'~';
}
}
}
fclose($inFile);
echo $theReturnString;
?>
The following HTML page is as far as I have gotten. It will at least get the return string separated into a list of headers, but I am at a loss as to how to get that list into a select / drop-down box:
<!DOCTYPE html>
<html>
<form id="StartingPage" action="GetList.php" method="post">
</form>
<head>
<script type="text/javascript">
function loadXMLDoc()
{ var xmlhttp;
var received;
// Browser setup;
// IF - code for IE7+, Firefox, Chrome, Opera, Safari
// ELSE - code for IE6, IE5
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
// Retreive the list
xmlhttp.onreadystatechange=function()
{ var newString = new Array();
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{ received = document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
received = received.split('~');
for ( i = 0; i < received.length; i++ )
document.writeln(received[i] + '<br>');
document.writeln('Done.<br>');
}
}
xmlhttp.open("GET","GetList.php",true);
xmlhttp.send();
}
</script>
And and all advice and critiques are appreciated.
First, I think it would be better if you parse your file with regular expressions for performance reasons.
Then, prefer JSON for the response, it will be easier for you to read it with Javascript. JSON is also a good choice because it allows you to easily change your script (adding items) without requiring to change the way to parse the responses from Ajax requests.
Following regex will search for contents between "[" and "]".
<?php
$content = file_get_contents('extensions.conf');
preg_match_all('~\[(.+)\]~Usmx', $content, $headers, PREG_PATTERN_ORDER);
echo json_encode($headers[1]);
Now, for the client side, we parse response with JSON.parse() method and put it into select box by creating option elements with document.createElement.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<form id="StartingPage" action="GetList.php" method="post">
<select name="mySelectName" id="mySelectId"></select>
</form>
<script>
function loadXMLDoc()
{
// Browser setup;
// IF - code for IE7+, Firefox, Chrome, Opera, Safari
// ELSE - code for IE6, IE5
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
// Retreive the list
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var mySelect = document.getElementById('mySelectId');
var headers = JSON.parse(xmlhttp.responseText);
for (var i = 0; i < headers.length; i++) {
var option = document.createElement('option');
option.setAttribute('value', i);
option.innerHTML = headers[i];
mySelect.appendChild(option);
}
}
}
xmlhttp.open("GET", "GetList.php", true);
xmlhttp.send();
}
loadXMLDoc();
</script>
</body>
</html>
Hope it helps !
If I understood the question right, you need to display select with options from that array .. this should work :
<!DOCTYPE html>
<html>
<form id="StartingPage" action="GetList.php" method="post">
</form>
<head>
<script type="text/javascript">
function loadXMLDoc()
{ var xmlhttp;
var received;
// Browser setup;
// IF - code for IE7+, Firefox, Chrome, Opera, Safari
// ELSE - code for IE6, IE5
if (window.XMLHttpRequest)
xmlhttp=new XMLHttpRequest();
else
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
// Retreive the list
xmlhttp.onreadystatechange=function()
{ var newString = new Array();
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{ received = document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
received = received.split('~');
var select = document.createElement("select");
select.setAttribute("name", "mySelect");
select.setAttribute("id", "mySelect");
var option;
for ( i = 0; i < received.length; i++ )
{
/* create options elements */
option = document.createElement("option");
/* You can change i with received[i] if you need your options with values equal to displayed text */
option.setAttribute("value", i);
option.innerHTML = received[i];
select.appendChild(option);
}
// Append the select to the end of the body tag
document.body.appendChild(select);
// Or You can use something like this also
// document.getElementById("myDiv").appendChild(select);
}
}
xmlhttp.open("GET","GetList.php",true);
xmlhttp.send();
}
</script>
I'm fairly new to the world of web development and am trying to read a txt file in internet explorer 8 and compare it to source code of a website to see if they are equal. This is so I can work out if the web page is functioning correctly.
I managed to get the source code with an xmlhttprequest and have tried the same to get the text file (which is in the same domain as my web page) and I am getting an access denied error.
After some research I can see that cross-domain xmlhttprequests won't work but that's not what I'm trying to do so I'm not sure how to proceed.
Having run the same code in Firefox(current version). It will read the file but not the web page!
I don't mind which of the two browsers I end up using but at the moment each does half of what I want it to.
my code is:
function source1(){
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", "http://website",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
document.getElementById('textzone').value = xmlhttp.responseText
var inputString = xmlhttp.responseText;
alert(inputString);
comparison(inputString)
}
}
xmlhttp.send(null)
}
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "comparisondoc.txt", false);
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==4) {
var compareString = xmlhttp1.responseText;
alert(compareString)
if(inputString==compareString){
alert("Strings are equal");
}
}
}
xmlhttp.send(null)
}
All I need to know is why either the file won't open in ie8, or why the website source code shows up blank (in the alert) in firefox. Any help would be appreciated.
It could be a browser support issue.
Try the following code to initialize your XMLHttpRequest :
function createRequest() {
try {
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
Check your comparison function. You should you xmlhttp1 instead of xmlhttp at 2 places
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "comparisondoc.txt", false);
xmlhttp1.onreadystatechange=function() {
if (xmlhttp1.readyState==4) {
<!--alert(xmlhttp1.responseText)-->
var compareString = xmlhttp1.responseText;
alert(compareString)
if(inputString==compareString){
alert("Strings are equal");
}
}
}
xmlhttp1.send(null)
}
Try to add the if(xmlhttp.status == 200) { } stuff. Remember both of these are looping through status' "AND" readystates.
Technically you could be erroring somewhere (I'd rather not speculate on) halting progress to next request or whatever without the status check.
Also you "should" try other request techniques. ie.. xmlhttp.onreadystatechange = function(){itsReady(inputString)}; // we keep this line short and simple calling to another func that contains your status and readystate checks, response stuff, and more func.
On a pretty normal run the Loop looks like:
hi rdySte:1///status 0////////
hi rdySte:2///status 200////////
hi rdySte:3///status 200////////
hi rdySte:4///status 200////////
I ran into a lot of weird issues trying the long onreadystatechange = function (){ ... All stuff..} I successfully run a crazy set of request functionalities using the short onreadystatechange technique.
I noticed at the last minute->
is there a reason why the async flags are different between your funcs? I'd set them all to true unless you have a great reason.
This will work: (to test: 2 pages t1.php contains a num or whatever and t2.txt that has a num in sam dir as the funcs are called in)
function source1(){
var avar = 1;
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET", "t1.php",true); // shortened f-names for ease of test
xmlhttp.onreadystatechange = function(){jsg_snd(avar)};
xmlhttp.send(null)
}
function jsg_snd(avar){
if (xmlhttp.readyState==4) {
if (xmlhttp.status == 200) {
var inputString = xmlhttp.responseText;
document.getElementById('text_zone').innerHTML = inputString;
document.getElementById('text_zone1').value = inputString;
// alert(inputString);//
comparison(inputString)
}
}
}
function comparison(inputString){
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET", "t2.txt", true);
xmlhttp1.onreadystatechange= function(){jsg_snd1(inputString);};
xmlhttp1.send(null)
}
function jsg_snd1(inputString){
if (xmlhttp1.readyState==4) {
if (xmlhttp1.status == 200) {
var compareString = xmlhttp1.responseText;
//alert(compareString)
if(inputString==compareString){
//alert("Strings are equal");
document.getElementById('text_zone').innerHTML += "; Ok "+inputString+"=="+compareString+"";
}
}
}
}
Now the html in your body should look like:
<tt id = 'text_go' onMouseUp="source1();" >Go!</tt>
<tt id = 'text_zone' onMouseUp="text_zone.innerHTML = '';" >Click to clear!</tt>
<input type ='text' id = 'text_zone1' onMouseUp="text_zone1.value = '';" value = 'Click to clear!' >
The extra stuf is for ___s & giggles.
The objective is to display a list of URLs in an HTML page. The list is retrieved from another file (currently in XML-format).
Validator: What is the proper xHTML mark-up for a list generated by JavaScript and still validate properly?
I assume the reason is that JavaScript-code inside [ul]'s is not accepted. Is this correct? Is there another solution?
The code below does produce the list anticipated, but it creates a warning (pls see below, 2.).
<ul>list A
<li>item A1</li>
<li>item A2</li>
<ul>List B
<li>item B1</li>
<script type="text/javascript">/* <![CDATA[ */
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.open("GET","/test-code/panorama-list2.xml",false);
// xmlhttp.open("GET","/test-code/panorama-list2.xml",true); //this does not work. xmlDoc is null.
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{ document.write('<li class="menu2">'+'<a href="');
document.write(x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue);
document.write('">');
document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
document.write('</li>'); }
//]]></script> //This is line: 136
</ul>
The JavaScript used in the code above is called using the synchronous method and thus creating the Warning:
"An unbalanced tree was written using document.write() causing data from the network to be reparsed. For more information https://developer.mozilla.org/en/Optimizing_Your_Pages_for_Speculative_Parsing
/ Source File: /test-code/index2.htm / Line: 136"
The solution is to use the asynchronous method similar to the code below placed into the section.
The solution is NOT to simply setting 'true' in the function xmlhttp.open (..., ..., true);.
<script type="text/javascript">//<![CDATA[
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
xmlDoc = xmlhttp.responseXML;
var txt = "";
var txt1 = "";
var x = xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{
txt = x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue + "<br />";
txt1 = x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue + "<br />";
}
{
document.getElementById("myDiv").innerHTML=txt;
document.getElementById("myDiv1").innerHTML=txt1;
}
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
//]]></script>
That does take care of the Warning.
I assume a solution would be to combine these 2 examples of code.
That's what I am trying:
The Variables 'txt' and 'txt1' retrieve the last entry of the XML-file.
How do I get all entires as well? The amount of entries varies.
Here is the big question:
How can I create a proper list using the asynchronous method and obtain a result like in the initial code example where the list is generated by stepping through the XML-file?
After all, is there is another, better or simpler solution? The file with data for the list shall not be part of the xHTML mark-up.
At last an actual page using the initial code example. The list is revealed by hovering over the button at top-right: http://www.halo-photographs.com/2011-Cascata-da-Bernina/index.htm (yes, this is my own page)
Thanks for your attention.
you code is an soup..
you need refactor that
now with jquery
in the load the you page
you should put somthing how that
$(document).ready(function(){
BeforePrepareList();
});
function BeforePrepareList()
{
var xmlRequest = XmlHttpRequestResolver();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
var xmlDoc = xmlhttp.responseXML;
// you need parse string response a array or use xslt, the next
// is simple for each
ListSetting(xmlDoc);
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
function XmlHttpRequestResolver()
{
if (window.XMLHttpRequest)
return xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
else
return xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
function ListSetting(rawdata)
{
ListPopulate($("_PUT_YOUR_LIST_ID_HERE").get(0), rawdata);
}
function ListPopulate(el, items) {
el.options.length = 0;
if (items.length > 0)
el.options[0] = new Option('All', '');
// THAT IS AN SIMPLE EXAMPLE, CHANGE FOR CREATE tag <a />
$.each(items, function (index,item) {
el.options[el.options.length] = new Option(item.[PROPERTY_A], item.[PROPERTY_B]);
});
}
and .....
more information here
invoke xml and transform http://www.ibm.com/developerworks/xml/library/x-ffox3/index.html
examples de http request http://www.jibbering.com/2002/4/httprequest.html