Results 1 to 9 of 9

Thread: Help using Ajax for checking if directory exists

  1. #1
    Join Date
    Apr 2008
    Posts
    58
    Thanks
    22
    Thanked 0 Times in 0 Posts

    Smile Help using Ajax for checking if directory exists

    Hello ,

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

    I have a following html code :
    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

  2. #2
    Join Date
    Apr 2008
    Posts
    58
    Thanks
    22
    Thanked 0 Times in 0 Posts

    Default

    Ok here is the code i'm running for now which is not working.

    index.html
    Code:
    <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
    Code:
    <?php
    	$filename=$_GET['dirnametocheck'];
    	
    	if (!file_exists($filename)) {
    		echo 'green';
    	} else {
    		echo 'red';
    	}
    <?

  3. #3
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,134
    Thanks
    44
    Thanked 3,231 Times in 3,192 Posts
    Blog Entries
    12

    Default

    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:

    Code:
    if(xmlHttp.responseText=='green')
    Should (just in case there's one or more line breaks or other whitespace in the responseText) probably be:

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

    Code:
    <?php
    	$filename=$_GET['dirnametocheck'];
    	
    	if (!file_exists($filename)) {
    		echo 'green';
    	} else {
    		echo 'red';
    	}
    <?
    Needs to be:

    Code:
    <?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:

    Code:
    <?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:

    Code:
    <?php
    	$filename=$_GET['dirnametocheck'];
    	
    	if (file_get_contents('http://www.dynamicdrive.com/' . $filename) !== false) {
    		echo 'green';
    	} else {
    		echo 'red';
    	}
    ?>
    or, for example:

    Code:
    <?php
    	$filename=$_GET['dirnametocheck'];
    	
    	if (file_get_contents('http://www.dynamicdrive.com/forums/' . $filename) !== false) {
    		echo 'green';
    	} else {
    		echo 'red';
    	}
    ?>
    Last edited by jscheuer1; 02-15-2013 at 03:20 AM. Reason: merge posts
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  4. The Following User Says Thank You to jscheuer1 For This Useful Post:

    sfchun (02-15-2013)

  5. #4
    Join Date
    Apr 2008
    Posts
    58
    Thanks
    22
    Thanked 0 Times in 0 Posts

    Default

    Code:
    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 :
    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 ... :/
    Last edited by sfchun; 02-15-2013 at 10:56 AM.

  6. #5
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,134
    Thanks
    44
    Thanked 3,231 Times in 3,192 Posts
    Blog Entries
    12

    Default

    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:

    Code:
    <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.
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  7. The Following User Says Thank You to jscheuer1 For This Useful Post:

    sfchun (02-15-2013)

  8. #6
    Join Date
    Apr 2008
    Posts
    58
    Thanks
    22
    Thanked 0 Times in 0 Posts

    Default

    Thanks for your advice

  9. #7
    Join Date
    Apr 2008
    Posts
    58
    Thanks
    22
    Thanked 0 Times in 0 Posts

    Default

    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
    Code:
    <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
    Code:
    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
    Code:
    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
    Code:
    while (el.value == '') {
       // do nothing
    }
    but either it hangs or do not work ...

    Is there a way to fix this ?

  10. #8
    Join Date
    Mar 2005
    Location
    SE PA USA
    Posts
    29,134
    Thanks
    44
    Thanked 3,231 Times in 3,192 Posts
    Blog Entries
    12

    Default

    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:

    Code:
    	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:

    Code:
    	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:

    Code:
    	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
    		}
    	}
    - John
    ________________________

    Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate

  11. The Following User Says Thank You to jscheuer1 For This Useful Post:

    sfchun (02-20-2013)

  12. #9
    Join Date
    Apr 2008
    Posts
    58
    Thanks
    22
    Thanked 0 Times in 0 Posts

    Default

    Thanks you , I finally decided to continue the code inside
    Code:
    xmlHttp.onreadystatechange=function()
    function as you advised.

Similar Threads

  1. Replies: 4
    Last Post: 06-04-2010, 04:24 AM
  2. Resolved [mkdir] exists or not
    By sysout in forum PHP
    Replies: 11
    Last Post: 02-16-2009, 01:47 AM
  3. Caps Lock - Not Sure If One Exists
    By banka in forum Looking for such a script or service
    Replies: 1
    Last Post: 03-07-2008, 03:52 AM
  4. Ajax javascript test if image file exists
    By Strangeplant in forum JavaScript
    Replies: 1
    Last Post: 12-12-2007, 05:28 PM
  5. Ajax Test for File Exists?
    By Strangeplant in forum JavaScript
    Replies: 3
    Last Post: 11-13-2007, 05:00 PM

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •