Log in

View Full Version : Help using Ajax for checking if directory exists



sfchun
02-14-2013, 05:33 PM
Hello ,

I'm requesting some help to figure out, how to handle the following problem, without using jquery :)

I have a following html code :

<textarea style="background-color:red" name="dirNametoCheck" id="dirNametoCheckID" onkeyup="checkThisDirectory('dirNametoCheckID');" > blabla </textarea>

and I can't figure out how I can change its background-color depending on if directory exists or not.

Note : Directory is located on a remote server, I could manage to check if it exists using PHP , but I can't implement it with the html/javascript code...

So what I need would be the javascript part of Ajax method or maybe a way to change the background-color of an element using PHP , don't know what is the best practice :/


Thanks for your help

sfchun
02-15-2013, 01:19 AM
Ok here is the code i'm running for now which is not working.

index.html


<script type="text/javascript">
function ajaxCheckDirIfExists(url,val) {
var xmlHttp;
try
{
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
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)
{
var el=document.getElementById('dirNametoCheckID');
if(xmlHttp.responseText=='green')
{
el.style.backgroundColor='green';
} else {
el.style.backgroundColor='red';
}
}
}
xmlHttp.open("get",url+"?dirnametocheck="+val,true);
xmlHttp.send(null);
}
</script>
<textarea style="rows="1" cols="32" maxlength="32" id="dirNametoCheckID" name ="dirNametoCheck" onkeyup="ajaxCheckDirIfExists('checkDirectoryExists.php',this.value);"></textarea>



checkDirectoryExists.php


<?php
$filename=$_GET['dirnametocheck'];

if (!file_exists($filename)) {
echo 'green';
} else {
echo 'red';
}
<?

jscheuer1
02-15-2013, 03:19 AM
There could also be other problems. But with AJAX it doesn't matter where the directory is. It does matter where checkDirectoryExists.php is. That PHP file must be on the same server as the AJAX code. Is it?

Other potential problems:



if(xmlHttp.responseText=='green')

Should (just in case there's one or more line breaks or other whitespace in the responseText) probably be:


if(xmlHttp.responseText.indexOf('green') > -1)

And:


<?php
$filename=$_GET['dirnametocheck'];

if (!file_exists($filename)) {
echo 'green';
} else {
echo 'red';
}
<?

Needs to be:


<?php
$filename=$_GET['dirnametocheck'];

if (file_exists($filename)) { // unless red means good, logic here would dictate that ! not be used
echo 'green';
} else {
echo 'red';
}
?>

Don't miss the corrected closing ?> tag.



For checking if a file/directory exists on a remote server, assuming fopen wrappers are enabled:


<?php
$filename=$_GET['dirnametocheck'];

if (file_get_contents($filename) !== false) {
echo 'green';
} else {
echo 'red';
}
?>

If you like you can include the base path (or any path) on the remote server:


<?php
$filename=$_GET['dirnametocheck'];

if (file_get_contents('http://www.dynamicdrive.com/' . $filename) !== false) {
echo 'green';
} else {
echo 'red';
}
?>

or, for example:


<?php
$filename=$_GET['dirnametocheck'];

if (file_get_contents('http://www.dynamicdrive.com/forums/' . $filename) !== false) {
echo 'green';
} else {
echo 'red';
}
?>

sfchun
02-15-2013, 10:31 AM
if(xmlHttp.responseText.indexOf('green') > -1) This worked ! thanks a lot for your help, and sory for the wonr PHP tag ...
And yes , i need green color when directory does not exists to indicated user that the name is available for creation :)

About how to check if directory exists , I run an 'issue' due to windows remote share (with AD authentication).
I had to use following code :
system("net use ".$letter.": \"".$filename."\" ".$password." /user:".$user." /persistent:no>nul 2>&1");
if (file_exists($letter.":\\") !== false) {
echo 'red';
} else {
echo 'green';
}
system("net use ".$letter.": /del>nul 2>&1");
don't know if there is better way of doing it...
For me it seems that mounting/unmount eachtime a key is pressed for checking sound a bit heavy ... :/

jscheuer1
02-15-2013, 12:39 PM
Instead of onkeyup, you can use onchange, which is better in two ways. It can detect changes that occur without keystrokes (pasting via mouse). And requires that the element (in this case the textarea) lose focus before any change is registered. The advantage is a lot less round trips to check intermediate spellings/misspellings. But you need a mechanism that forces/invites the user to blur the textarea. That's all simple enough:


<textarea style="rows="1" cols="32" maxlength="32" id="dirNametoCheckID" name ="dirNametoCheck" onchange="ajaxCheckDirIfExists('checkDirectoryExists.php',this.value);"></textarea>
<input type="button" value="Check">

The button needs no event. Simply by clicking on it or tabbing to it, the user triggers the onchange event of the textarea - that is if anything has changed. Which is perfect because, if nothing has changed, no need to check the remote server again.

sfchun
02-15-2013, 01:17 PM
Thanks for your advice :)

sfchun
02-18-2013, 03:56 PM
Hi again,

I try to apply the advice for less load.
So the checking is initiated when form is submited rather that at each input.
html part

<form name="form1" id="form1" action="writeRequestIni.php" method="post" onsubmit="deepCheckForm(); return false;">
[...]
<tr><td align="left"></td><td><input type="submit" name="submit" id="submitID" value="Submit" disabled="disabled" /></td>
</form>
<br /><div name="displayResult" id="displayResultID" style="background-color:white;color:black"></div>

java script part

function deepCheckForm() {
var el = document.getElementById('sourceID');

ajaxCheckDirIfExists('checkDirectoryExists.php',el.value, el.id);
// WAIT <-- ???
alert('color : '+el.style.backgroundColor+'\nname : '+el.value); //DEBUG
//
xmlhttpPost('writeRequestIni.php', 'form1', 'displayResultID', '<img src=\'img/circleloading.gif\'>');
}

My problem here, is that when I perform the validity check about the existing directory
ajaxCheckDirIfExists('checkDirectoryExists.php',el.value, el.id);
The code continue and display the next alert before receiving the check result :/
I tried different tricks to temporize as using a
while (el.value == '') {
// do nothing
} but either it hangs or do not work ...

Is there a way to fix this ?

jscheuer1
02-19-2013, 06:10 AM
AJAX stands for Asynchronous Javascript And XML. The key concept here is asynchronous. That means that while the external content is being fetched, the browser is free to go on along its merry way processing the rest of the code if any on the page. This is usually a good thing. It allows the browser to continue parsing HTML code if - say the AJAX call comes before the page is fully loaded. And/or parse more javascript. The only problem with this is that if you have a otherwise synchronous script that needs the information from the request to be processed before it continues.

Fortunately there are ways of dealing with that. Perhaps the simplest is to continue your code from the onreadystatechange function. In your code that's here:



xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
var el=document.getElementById('dirNametoCheckID');
if(xmlHttp.responseText.indexOf('green') > -1)
{
el.style.backgroundColor='green';
} else {
el.style.backgroundColor='red';
}
}
}

You already have a branch there depending upon what color name is returned. You can continue on your code right there:


xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
var el=document.getElementById('dirNametoCheckID');
if(xmlHttp.responseText.indexOf('green') > -1)
{
el.style.backgroundColor='green';
//continue on your code with something more here, perhaps call another function
} else {
el.style.backgroundColor='red';
//continue on your code with some other thing more here, perhaps call a different other function
}
}
}

Or you can setup a poll (a 20 to 300 millisecond loop that repeats via a setInterval or a series of setTimeouts that will look for something that will only be there once the response has been received, like a global variable or an accessible variable or property that gets set to true when the response is received and is set/reset to false each time a new request is made, breaking out of the loop only once that is true. Or you can switch from an asynchronous request to a synchronous one. That's not recommended because, if there's a problem with the request, the page will just hang there. Your onreadystatechange function should also have a branch for failure though. If the requested data is received the status is 200, all others represent some problem. So something like:


xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4 && xmlHttp.status==200)
{
var el=document.getElementById('dirNametoCheckID');
if(xmlHttp.responseText.indexOf('green') > -1)
{
el.style.backgroundColor='green';
//continue on your code with something more here, perhaps call another function
} else {
el.style.backgroundColor='red';
//continue on your code with some other thing more here, perhaps call another function
}
} else if (xmlHttp.readyState==4)
{
//do something here in the event that no response is available
}
}

sfchun
02-20-2013, 09:37 AM
Thanks you , I finally decided to continue the code inside
xmlHttp.onreadystatechange=function() function as you advised.