13.09.2016 Views

PHP and MySQL Web Development 4th Ed-tqw-_darksiderg

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Adding Ajax Elements to Earlier Projects<br />

879<br />

Listing 34.9<br />

Continued<br />

//check that form has been completed<br />

if (!filled_out($_POST)) {<br />

//has not<br />

echo "Form not completely filled out.";<br />

} else {<br />

// has; check <strong>and</strong> fix URL format if necessary<br />

if (strstr($new_url, 'http://') === false) {<br />

$new_url = 'http://'.$new_url;<br />

}<br />

// continue on to check URL is valid<br />

if (!(@fopen($new_url, 'r'))) {<br />

echo "Not a valid URL.";<br />

} else {<br />

//it is valid, so continue to add it<br />

add_bm($new_url);<br />

echo "Bookmark added.";<br />

}<br />

}<br />

// regardless of the status of the current request<br />

// get the bookmarks this user has already saved<br />

if ($url_array = get_user_urls($_SESSION['valid_user'])) {<br />

display_user_urls($url_array);<br />

}<br />

?><br />

This version of the script still follows a logical path through possible events, but displays<br />

an appropriate error message without duplicating any other page elements.<br />

The first check is whether the form itself has been filled out. If it has not, an error<br />

message is displayed between the addition form <strong>and</strong> the user’s current list of stored<br />

bookmarks.You can see this response in Figure 34.6.<br />

The second check is whether the URL is properly formed; if it is not, the string is<br />

transformed into a proper URL <strong>and</strong> moves on to the next step. In the next step, a socket<br />

is opened <strong>and</strong> the URL is tested for validity. If it fails, an error message is displayed<br />

between the addition form <strong>and</strong> the user’s current list of stored bookmarks. However, if<br />

the URL is valid, it is added to the user’s existing list of stored URLs. In Figure 34.7<br />

you can see the response when attempting to add an invalid URL.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!