Page 1 of 1

Adding Bookmarks the AJAX Way

Posted: Sat Nov 17, 2012 12:42 pm
by rick.emmet
Hi Everyone,
I took a PHP class that used PHP And MySQL Web Development by Welling and Thomson as our textbook and we were able to get through most of the book. We didn't have time to cover chapter 34 Building Web 2.0 Applications with AJAX though. I need to do some AJAX development and have proceeded to work with the examples in the book. The section, Adding Bookmarks the AJAX Way, has us changing a number of scripts that were used previously to make the interface more user friendly. I typed out the scripts and couldn't get them to run. I cut and pasted the code into my PHP pages and it still won't run, so I need a little help.

I found several typos which I corrected but the scripts will not run; the weird thing is that nothing happens when I click on the “Add bookmark” button. A new snippet of code has been added as a button attribute that invokes a javascript function which calls a PHP script to insert the bookmark into the database. These scripts have numerous error messages (exceptions), but not a single one is displayed on the page. I have a form which allows me to add a bookmark and there is a button to click on; and when I fill out the form and click on the button, the page does not change at all.

Since this is new to me, I'm having a hard time figuring out where the problem is. The PHP script requires both a bookmark and a valid user (both are input into the database). It looks as if the javascript function is only sending the bookmark, but since we really don't really leave the page, perhaps the PHP script can grab the valid user to process. I do want to learn this stuff (wish we had time to cover this in class!) and any advice would be most appreciated!

Here are the scripts:
THE AJAX.JS FILE

Code: Select all

function getXMLHTTPRequest() {
   var req =  false;
   try {
      /* for Firefox */
      req = new XMLHttpRequest();
   } catch (err) {
      try {
         /* for some versions of IE */
         req = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (err) {
         try {
            /* for some other versions of IE */
            req = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (err) {
            req = false;
         }
     }
   }
   
   return req;
}

function addNewBookmark() {
  var url = "add_bms.php";
  var params = "new_url=" + encodeURI(document.getElementById('new_url').value);
  myReq.open("POST", url, true);
  myReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  myReq.setRequestHeader("Content-length", params.length);
  myReq.setRequestHeader("Connection", "close");
  myReq.onreadystatechange = addBMResponse;
  myReq.send(params);
}

function addBMResponse() {
  if (myReq.readyState == 4) {
    if(myReq.status == 200) {
       result = myReq.responseText;
       document.getElementById('displayresult').innerHTML = result;
    } else {
      alert('There was a problem with the request.');
    }
  }
}
THE ADD BOOKMARKS FUNCTION FROM THE OUTPUT LIBRARY

Code: Select all

function display_add_bm_form() {
  // display the form for people to enter a new bookmark in
?>
<script type="text/javascript">
var myReq = getXMLHTTPRequest();
</script>
<form>
<table width="250" cellpadding="2" cellspacing="0" bgcolor="#cccccc">
<tr><td>New BM:</td>
<td><input type="text" id="new_url" name="new_url" value="http://"
     size="30" maxlength="255"/></td></tr>
<tr><td colspan="2" align="center">
    <input type="button" value="Add bookmark"
           onClick=" javascript:addNewBookmark();"/></td></tr>
</table>
</form>
<div id="displayresult"></div>
<?php
}
THE ADDBOOKMARKS PHP SCRIPT

Code: Select all

<?php
 require_once('bookmark_fns.php');
 session_start();

 //create short variable name
 $new_url = $_POST['new_url'];

 //check that form has been completed
 if (!filled_out($_POST)) {
   //has not
   echo "<p class=\"warn\">Form not completely filled out.</p>";
 } else {
    // has; check and fix URL format if necessary
    if (strstr($new_url, 'http://') === false) {
       $new_url = 'http://'.$new_url;
    }

    // continue on to check URL is valid
    if (!(@fopen($new_url, 'r'))) {
      echo "<p class=\"warn\">Not a valid URL.</p>";
    } else {
      //it is valid, so continue to add it
      add_bm($new_url);
    }
 }
 // regardless of the status of the current request
 // get the bookmarks this user has already saved
 if ($url_array = get_user_urls($_SESSION['valid_user'])) {
    display_user_urls($url_array);
 }
?>
THE ADD_BM FUNCTION FROM THE URL FUNCTION LIBRARY

Code: Select all

function add_bm($new_url) {
  // Add new bookmark to the database

  echo "Attempting to add ".htmlspecialchars($new_url)."<br />";
  $valid_user = $_SESSION['valid_user'];

  $conn = db_connect();

  // check not a repeat bookmark
  $result = $conn->query("select * from bookmark
                         where username='$valid_user'
                         and bm_URL='".$new_url."'");

  if ($result && ($result->num_rows>0)) {
    echo "<p class=\"warn\">Bookmark already exists.</p>";
  } else {
    //attempt to add
    if (!$conn->query("insert into bookmark values
       ('".$valid_user."', '".$new_url."')")) {
       echo "<p class=\"warn\">Bookmark could not be inserted.</p>";
    } else {
       echo "<p>Bookmark added.</p>";
    }
  }

  return true;
}
THE DB_CONNECT FUNCTION FROM THE DB FUNCTION LIBRARY

Code: Select all

function db_connect() {
   $result = new mysqli('localhost', 'bm_user', 'password', 'bookmarks');
   if (!$result) {
     throw new Exception('Could not connect to database server');
   } else {
     return $result;
   }
}
Looks all looks good to me, but I just started studying this so...
Thanks in advance for your help,
Rick

Re: Adding Bookmarks the AJAX Way

Posted: Sat Nov 17, 2012 6:37 pm
by califdon
I haven't looked at all your code, but here's something you can try, right away:
In AJAX.JS, change

Code: Select all

 myReq.onreadystatechange = addBMResponse;
to read

Code: Select all

 myReq.onreadystatechange = addBMResponse();
The onReadyStateChange method has to call a function, which means it must have parentheses following the function name.

Actually, I don't see all the required code in AJAX.JS. Where do you define the JS object myReq?

Re: Adding Bookmarks the AJAX Way

Posted: Sun Nov 18, 2012 4:48 pm
by rick.emmet
Hi califdon,
Thank you for the reply! Boy it's hard to learn a computer language (or several as AJAX is) when the textbook has numerous mistakes in their code. Since I posted the question about this problem, I've found several other very BIG mistakes in the code that came along with the book (I guess they were under the gun to get the book published).

I'm not sure how myReq should be defined. Would one expect to have code similar to:

Code: Select all

myReq = new Object();
I'm not familiar enough with javascript to know, and was relying on the textbook to teach me. Any help with this would be much appreciated. And thanks for the time you've spent on this too!
Cheers,
Rick

Re: Adding Bookmarks the AJAX Way

Posted: Sun Nov 18, 2012 9:21 pm
by califdon
That sounds like a really bad book! I'm afraid a lot of those are published by people who may be good programmers, but who don't know much about writing and proofing a useful book.

It's possible that this script assumes that there's another script in which myReq is defined, but yes, somewhere that has to happen. I'll try to find time to look at this tomorrow.

Re: Adding Bookmarks the AJAX Way

Posted: Mon Nov 19, 2012 1:48 pm
by rick.emmet
Hey califdon,
The book has been highly praised and everything we covered in class had good code (with the exception of a few typos). I think they had some time pressures with the publication date, but you would think they would have posted the corrected code on their site. I tried to find that, but couldn't. Thanks in advance for your help!
Cheers,
Rick