www.webdeveloper.com
Page 1 of 3 123 LastLast
Results 1 to 15 of 36

Thread: [RESOLVED] Alert box - parsing values

Hybrid View

  1. #1
    Join Date
    Jun 2012
    Posts
    48

    resolved [RESOLVED] Alert box - parsing values

    Hello forum readers,

    I have a problem when I click on a custimizable alert box.
    This alert box shows "Yes" and "No" as options.
    When you click "No" the box closes.
    When you click "Yes" the box closes and it has to do a submit form values and delete line in flat file. Without the alert box everything works just fine
    What am I doing wrong?
    delete.php
    Code:
    <html>
    <head>
    <script type="text/javascript" src="Alert.js"></script> 
    </head>
    <body>
    
    <!-- code to read flat file here - case ""; -->
    
    
    <form method="post" action="'.$self.'?do=delete_data&id='.$id.'&name='.$name.'" enctype="multipart/form-data" onclick="alert(\'Are you sure?\');return false;" >
    	<input type="hidden" name="do" value="delete_data">
    	<input type="hidden" name="name" id="name" value="'.$name.'" />
    	<input type="hidden" name="id" id="id" value="'.$id.'" />
    	<input type="submit" name="submit" value="Delete" />
    </form>
    
    <!-- code to delete file - case "delete_data";
    
    </body>
    </html>
    Alert.js code
    Code:
    var ALERT_TITLE = "Conformation";
    var ALERT_BUTTON_TEXT = "YES";
    var ALERT_BUTTON_TEXT_CANCEL = "NO";
    if(document.getElementById) {
    	window.alert = function(textalert) {
    		createCustomAlert(textalert);
    	}
    }
    
    function createCustomAlert(textalert) {
    	d = document;
    
    	if(d.getElementById("modalContainer")) return;
    
    	mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
    	mObj.id = "modalContainer";
    	mObj.style.height = d.documentElement.scrollHeight + "px";
    	
    	alertObj = mObj.appendChild(d.createElement("div"));
    	alertObj.id = "alertBox";
    	if(d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
    	alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth)/2 + "px";
    	alertObj.style.visiblity="visible";
    
    	h1 = alertObj.appendChild(d.createElement("h1"));
    	h1.appendChild(d.createTextNode(ALERT_TITLE));
    
    	p = alertObj.appendChild(d.createElement("p"));
    	p.appendChild(d.createTextNode(textalert));
    	p.innerHTML = textalert;
    
    	btn = alertObj.appendChild(d.createElement("a"));
    	btn.id = "closeBtn";
    	btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
    	btn.href = "#";
    	btn.focus();
    	btn.onclick = function() { removeCustomAlert();return false; }
    
    	alertObj.style.display = "block";
    
    	btn_cancel = alertObj.appendChild(d.createElement("a"));
    	btn_cancel.id = "closeBtn";
    	btn_cancel.appendChild(d.createTextNode(ALERT_BUTTON_TEXT_CANCEL));
    	btn_cancel.href = "#";
    	btn_cancel.focus();
    	btn_cancel.onclick = function() { cancelCustomAlert();return false; }
    
    	alertObj.style.display = "block";
    	
    }
    
    function removeCustomAlert() {
    	document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
    
    	var id = document.getElementById("id").value;
    	var name = document.getElementById("name").value;
    	window.location='delete.php?do=delete_data&id='+id+'&name='+name;
    
    }
    
    function cancelCustomAlert() {
    	document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
    }
    Problem is in --> function removeCustomAlert() <--
    I hope somebody can help me.

    Thanks in advance

    Regards
    Last edited by coderunner; 06-20-2012 at 02:37 PM. Reason: more code

  2. #2
    Join Date
    Aug 2006
    Posts
    301
    you'd need to show more code, this seems to be ok. but why not just have the button be an image that links directly to the php file with the query string already hardcoded like this:

    <a href=''delete.php?do=delete_data&id=id&name=name'><img src='yes.jpg'></a>

    even if the query needs to be dynamic, you can just use javascript to dynamically change the url or php to load the page with the query already in place.

  3. #3
    Join Date
    Jun 2012
    Posts
    48
    Hello bsmbahamas,

    I changed the code in my first post.
    Does this give you a better idea of my code ?

    Can you help me please to solve my problem ?

    Regards

  4. #4
    Join Date
    Aug 2006
    Posts
    301
    that's much better, but with regard to the removeCustomAlert() function,
    where are the html elements with the ids of 'id' and 'name' that you are trying to get the value of? i assume that this info is coming from form fields since you are using .value instead of .innerHTML in this case, but the code you provided does not have any elements with an id of 'id' or 'name'. when you mouse over the yes/no buttons you'll see that no query string is coming up either

    function removeCustomAlert() {
    document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));

    var id = document.getElementById("id").value;
    var name = document.getElementById("name").value;
    window.location='delete.php?do=delete_data&id='+id+'&name='+name;

    }

  5. #5
    Join Date
    Aug 2006
    Posts
    301
    do you really want to dynamically create a custom alert via dom manipulation versus just hard coding the whole custom alert in the html of the page and using javascript and css to toggle it's visibility or display property, and moving it into place on the screen? you can still dynamically change the url of the buttons with javascript when the alert box is called

  6. #6
    Join Date
    Jun 2012
    Posts
    48
    Hello bsmbahamas,

    I have feeling that my case "delete_data"; doesn't read the values in the url because I can see the values in the url
    delete.php?do=delete_data&id=0012&name=Johson

    But how can I make my case "delete_data"; get the values out of the url
    So far I have this but how to get the id in my delete script ?
    case "delete_data"
    Code:
    	case "delete_data";
    	
    	
    // Get values of id and name out of url	
    if(strpos($_SERVER['REQUEST_URI'], '?') !== false)
    {
    	list($file, $query) = explode('?', $_SERVER['REQUEST_URI']);
    	$pairs = explode('&', $query);
    	foreach($pairs as $p)
    	{
    		$value = $val = '';
    		list($value, $val) = explode('=', $p);
    		if($value=='id')
    		{
    			$id = $val;
    		}
    		if($value=='name')
    		{
    			$name = $val;
    		}
    	}
    }
    
    //Delete the line with id
                   $id = $_POST['id'];
    		$name = $_POST['name'];
    		$file = file($data_file); 
    		$data = ''; 
    		for ($i=0; $i<count($file); $i++) 
    		{ 
    			if (!strstr($file[$i],$id)) 
    			{ 
    				$data .= $file[$i]; 
    			} 
    		} 
    		$fp = fopen($data_file,"w");
    		
    		if ($fp) 
    		{ 
    			fwrite($fp,$data); 
    			fclose($fp); 
    		}
    Can you help me ?

    Regards
    Last edited by coderunner; 06-20-2012 at 05:06 PM.

  7. #7
    Join Date
    Aug 2006
    Posts
    301
    try echoing out the info so you can see what's coming through:

    echo "<p><pre>"; print_r($_GET); echo "</pre></p>";
    echo "<p><pre>"; print_r($_POST); echo "</pre></p>";
    echo "<p><pre>"; print_r($_REQUEST); echo "</pre></p>";

    if they are not submitting a form then it would come though via GET otherwise it would come through POST, (REQUEST shows both) you could probably just use $id = $_GET['id'] and $name = $_GET['name'] to retrieve the values from the url after the link is clicked.

    this code would check that the values are set and not empty/false in the url.

    if(
    isset( $_GET['id'] ) && !empty( $_GET['id'] ) &&
    isset( $_GET['name'] ) && !empty( $_GET['name'] )
    ){
    $id = $_GET['id'] ;
    $name = $_GET['name']
    } else {
    die("<p>MSG: both id and name are not set!</p>");
    }

    gotta run, i'll check your progress later or tomorrow

  8. #8
    Join Date
    Jun 2012
    Posts
    48
    Hello bsmbahamas,

    Thank you for helping me.
    I already echo-ed the values and it worked.
    I think I got a little closer to a solution but the problem is that the javascript in the alert script sends the wrong value in the url ... always the first one so I tried to give the id an unique value with adding id="'.$id.'" in the form
    PHP Code:
    <input type="hidden" name="id" id="'.$id.'" value="'.$id.'" /> 
    but then Firebug says that the id is undefined in the alert script line 54 and 55

    How can I fix this?

    I send you the complete code

    The text database looks like this
    Code:
    hhdgfbcjeffch | name 1 | street 1 | city 1 | country 1
    hhdfllhigjfch | name 2 | street 2 | city 2 | country 2
    hhdgfbcjeffkg | name 3 | street 3 | city 3 | country 3
    hhdgfbcjnsogj | name 4 | street 4 | city 4 | country 4
    hhdgdjiiadmgf | name 5 | street 5 | city 5 | country 5
    hhdgfbchsufkf | name 6 | street 6 | city 6 | country 6
    hhddhfydsbfju | name 7 | street 7 | city 7 | country 7
    hhdgfmcbhdyaq | name 8 | street 8 | city 8 | country 8
    hhdgfbjfhfbds | name 9 | street 9 | city 9 | country 9
    hhdopdjjrhsbj | name 10 | street 10 | city 10 | country 10
    The delete.php I have now is
    PHP Code:
    <html>

    <head>

        <script type="text/javascript" src="Alert.js"></script>
        <link rel="stylesheet" type="text/css" href="alert.css" />

    </head>

    <body bgcolor="000080">

    <?php

    $do 
    = isset($_REQUEST['do']) ? trim($_REQUEST['do']) : "";
    $self $_SERVER['PHP_SELF'];
    $data_file 'address_book.txt';


    switch (
    $do
        {

        case 
    "";
    ///////////////////////////////////////////////////////////////
    //                      READ TEXT FILE                       //
    ///////////////////////////////////////////////////////////////

    $file_handle fopen($data_file"rb");
        while (!
    feof($file_handle) ) 
        {

            
    $line_of_text fgets($file_handle);
            
    $row explode(' | '$line_of_text);
            
                
    $id $row[0];
                
    $name $row[1];
                
    $street $row[2];
                
    $city $row[3];
                
    $country $row[4];
                                                                                            

                echo 
    '<div width="400px" align="center">
                        <form method="post" action="'
    .$self.'?do=delete_data&id='.$id.'&name='.$name.'" onclick="alert(\'Are you sure?\');return false;" >
                            <input type="hidden" name="do" value="delete_data">
                            <input type="text" name="name" id="name" value="'
    .$name.'" />
                            <input type="hidden" name="id" id="id" value="'
    .$id.'" />
                            <input type="submit" name="submit" value="Delete" />
                        </form>
                     </div>'
    ;
        }
                                        
        break;

    ///////////////////////////////////////////////////////////////
    //                DELETE LINE IN TEXT FILE                   //
    ///////////////////////////////////////////////////////////////

        
    case "delete_data";
        
        if (isset(
    $_GET['id']))
        {
            
    $id $_GET['id'];
        }
        if (isset(
    $_GET['name'])) 
        {
            
    $name $_GET['name'];
        }
        


            
    $file file($data_file); 
            
    $data ''
            for (
    $i=0$i<count($file); $i++) 
            { 
                if (!
    strstr($file[$i],$id)) 
                { 
                    
    $data .= $file[$i]; 
                } 
            } 
            
    $fp fopen($data_file,"w");
            
            if (
    $fp
            { 
                
    fwrite($fp,$data); 
                
    fclose($fp); 
            } 


            
            
    redir("$self","<span style=\"font-family: Century Gothic, Arial, Helvetica;color:#FFFFFF;font-size:14px;\">$name deleted!</span><br /><br />");
            break;
        }

    function 
    redir($target,$msg
    {
        global 
    $background;


    ///////////////////////////////////////////////////////////////
    //              REDIRECT SHOWS UPDATE MSG                    //
    ///////////////////////////////////////////////////////////////
    ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="refresh" content="2; url=<?=$target?>">
    </head>
    <body>
        <div align="center">
            <span style="font-family: Century Gothic, Arial, Helvetica;color:#FFFFFF;font-size:14px">
                <?=$msg?>Data being updated ...
            </span>
        </div>
    </body>
    </html>
    <?php
        
    exit;
    }
    ?>
    The alert.js is in one of my earlier posts.

    I hope you (or somebody else of course) can tell me or give a working code.

    Thanks in advance

    Regards

  9. #9
    Join Date
    Aug 2006
    Posts
    301
    the php code for the form is not correct...

    this code:

    <input type="hidden" name="id" id="'.$id.'" value="'.$id.'" />

    should be:

    <input type="hidden" name="id" id="<?php echo $id; ?>" value="<?php echo $id; ?>" />

    or alternatively:

    <?php
    echo '<input type="hidden" name="id" id="$id" value="$id" />';
    ?>

    otherwise you won't have any value being passed as the php must use echo at some point.

    also you don't need to include 'id' and 'name' in the query string of your forms action attribute,
    since you already have them in the hidden fields, they may over write each other.

    i'd also seperate the scripts so you'd have one page that shows the the text file contents(records.php)
    and a second script that handles the deleting (delete.php) and then redirects back to records.php
    Last edited by bsmbahamas; 06-21-2012 at 11:11 AM.

  10. #10
    Join Date
    Jun 2012
    Posts
    48
    Hello bsmbahamas,

    I changed what you said but Firebug still says that the id is undefined or nul in the alert.js file lines 54.

    With the code, I posted here, it works BUT the code in the alert.js file
    function removeCustomAlert() {
    document.getElementsByTagName("body")[0].removeChild(document.getElementById("modalContainer"));
    var id = document.getElementById("id").value;
    var name = document.getElementById("name").value;

    window.location='delete.php?do=delete_data&id='+id+'&name='+name;
    }
    doesn't take the right line to delete, it aways takes the first line in the text file (address_book.txt)

    E.g
    I want to delete "naam 7"
    The url the alert.js script generates is
    delete.php?do=delete_data&id=hhdgfbcjeffch&name=name 1 and line 1 (= name 1) is deleted in stead of line 7.

    I hope you understand what I mean.
    So something is wrong with generating the url but what ...

    Hope I can find/get a solution for my problem.

    Best regards
    Last edited by coderunner; 06-21-2012 at 12:08 PM.

  11. #11
    Join Date
    Jun 2012
    Posts
    48
    Oops ... I see you have posted some codes while I was replying to your earlier post.

    Going to check the codes you posted and reply after I tested it.

    Thanks again for helping me and finding a solution for this.

    Best regards

  12. #12
    Join Date
    Aug 2006
    Posts
    301
    Quote Originally Posted by coderunner View Post
    Hello bsmbahamas,

    I changed what you said but Firebug still says that the id is undefined or nul in the alert.js file lines 54.

    With the code, I posted here, it works BUT the code in the alert.js file
    doesn't take the right line to delete, it aways takes the first line in the text file (address_book.txt)

    E.g
    I want to delete "naam 7"
    The url the alert.js script generates is
    delete.php?do=delete_data&id=hhdgfbcjeffch&name=name 1 and line 1 (= name 1) is deleted in stead of line 7.

    I hope you understand what I mean.
    So something is wrong with generating the url but what ...

    Hope I can find/get a solution for my problem.

    Best regards
    i'd only pass the id via get, then have the delete.php script explicitly match the id before deleting the record, otherwise as you database changes you'll be deleting by row number which can change, instead of based on the id of the row which will stay the same whther rows are added or removed later.

    in any event if you are gonna stick with forms you should pass the data via the hidden form fields, and not as part of the query string in the action part of the form

  13. #13
    Join Date
    Jun 2012
    Posts
    48
    Hello bsmbahamas,

    I made the 2 files (records.php and delete.php) as you said in your post.
    Do I have to change something is the file alert.js ?

    Results of testing:
    I get the same error message as before
    errror message: document.getElementById("id") is null in alert.js file
    So it stops and does nothing. It stays on the records.php page and didn't delete any line in the database.

    Best regards
    Last edited by coderunner; 06-21-2012 at 12:38 PM.

  14. #14
    Join Date
    Aug 2006
    Posts
    301
    i have 2 other questions:

    1. why are you displaying the data in forms if you are only giving an option to delete the info? you could just show plain text and give a plain text delete link.

    2. why are you using a switch statement if the only option is to delete?

    i'd restructure the whole thing to simply read the flat file database and show the records onscreen as plain text with a delete link next to it in records.php, if they click delete they could still be shown the javascript custom popup and then be redircted to delete.php where the deleting happens then redirect them back to records.php

    if you are planningon alowing them to update and delete records from the same page then the current structure is logical, but you'll need to add a good bit more code to handle updating.

    something like this...

    records.php

    <html>

    <head>

    <script type="text/javascript" src="Alert.js"></script>
    <link rel="stylesheet" type="text/css" href="alert.css" />
    <style type="text/css">
    .success { border: 1px solid green; }
    .warning { border: 1px solid orange; }
    .error { border: 1px solid red; }
    </style>
    </head>

    <body bgcolor="000080">

    <?php

    /* READ TEXT FILE */

    $data_file = 'address_book.txt';
    $rows = file($data_file);

    if( $_GET['m'] == 1 ){
    echo '<p class="success">Record Deleted!</p>';
    }

    echo '<table width="400" cellpadding="5" cellspacing="0" align="center">';
    echo '<tr><td>Name</td><td>Street</td><td>City</td><td>Country</td><td>Options</td></tr>';

    for( $i = 0; $i < count($rows); $i++ ){

    $row = explode(' | ', trim($rows[$i]));

    $id = $row[0];
    $name = $row[1];
    $street = $row[2];
    $city = $row[3];
    $country = $row[4];

    echo "
    <tr>
    <td>$name</td>
    <td>$street</td>
    <td>$city</td>
    <td>$country</td>
    <td><a href="edit.php?id=$id">Edit</a> | <a onclick="alert('Are you sure?');return false;" href="delete.php?id=$id">Delete</a></td>
    </tr>
    ";

    }

    echo '</table>';

    </body>
    </html>

    -----------------------------

    delete.php
    <?php

    /* DELETE LINE IN TEXT FILE */

    if( isset($_GET['id']) ){
    $id = $_GET['id'];
    }

    $data_file = 'address_book.txt';
    $rows = file($data_file);
    $rows = array_map('trim',$rows); //trim all rows

    for( $i = 0; $i < count($rows); $i++ ){

    $row = explode(' | ', $rows[$i]);

    /* if submitted id matches the id in the current row delete it using unset */

    if( $id == $row[0] ){

    unset($rows[$i]);
    $fh = fopen($data_file,'w');
    fwrite($fh,implode("\n",$rows));
    fclose($fh);

    header("location: records.php?m=1");

    }

    }


    ?>
    Last edited by bsmbahamas; 06-21-2012 at 12:11 PM.

  15. #15
    Join Date
    Aug 2006
    Posts
    301
    the code above reads the text file and creates a table of all the records, the delete/edit links take them to another page and passes the id via GET. the delete.php page
    creates an array containing the rows from the db and loops over them comparing the id in the db to the id passed via GET from records.php if it finds a match it unsets/deletes that record from the array, then it implodes the array back into the db and redirects them back to records.php with a query string of m=1, records.php detects the m=1 and displays a success message.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles