willrockformilk Posted March 17, 2009 Share Posted March 17, 2009 hello everyone. so i am working on a phonebook for where i work. i made one with php/mysql and it works like a charm. Then one of my coworkers suggested that instead of it going to a new page after people submit their search's, to print the results out on the same page. now im kind of new to this but i have searched far and deep and discovered AJAX was the route to go. i got everything working. its great. i love it. but im having problems formatting my results. and it seems like i can only do this in javascript. and i dont know how to really. here is what i want: When the user searches for firstname "amy". There are 4 amy's in the database. i want it to print our the data for all 4 of the amy's into a table. but when a user searches for "henry". there are 2. and i want it to print out both henry's data into a table. i know this is going to take a for loop. but i dont know much about javascript and when i tried to put a loop where it needed to go it wouldnt let me. and every tutorial ive read usually has a set number of data entries that the load their code to print out. or use a select tag in html. phonebook.php this is the user interface. i just put the javascript in here to simplify things <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en-gb"> <head> <script type="text/javascript"> var ajaxObject = false; // this is our object which gives us access // to Ajax functionality function doAjaxQuery(url) { ajaxObject = false; if (window.XMLHttpRequest) { // if we're on Gecko (Firefox etc.), KHTML/WebKit (Safari/Konqueror) and IE7 ajaxObject = new XMLHttpRequest(); // create our new Ajax object if (ajaxObject.overrideMimeType) { // older Mozilla-based browsers need some extra help ajaxObject.overrideMimeType('text/xml'); } } else if (window.ActiveXObject) { // and now for IE6 try {// IE6 has two methods of calling the object, typical! ajaxObject = new ActiveXObject("Msxml2.XMLHTTP"); // create the ActiveX control } catch (e) { // catch the error if creation fails try { // try something else ajaxObject = new ActiveXObject("Microsoft.XMLHTTP"); // create the ActiveX control (using older XML library) } catch (e) {} // catch the error if creation fails } } if (!ajaxObject) { // if the object doesn't work // for some reason it hasn't worked, so show an error alert('Sorry, your browser seems to not support this functionality.'); return false; // exit out of this function } ajaxObject.onreadystatechange = ajaxResponse; // when the ready state changes, run this function // DO NOT ADD THE () AT THE END, NO PARAMETERS ALLOWED! ajaxObject.open('GET', url, true); // open the query to the server ajaxObject.send(null); // close the query // and now we wait until the readystate changes, at which point // ajaxResponse(); is executed return true; } // end function doAjaxQuery function ajaxResponse() { // this function will handle the processing // N.B. - in making your own functions like this, please note // that you cannot have ANY PARAMETERS for this type of function!! if (ajaxObject.readyState == 4) { // if ready state is 4 (the page is finished loading) if (ajaxObject.status == 200) { // if the status code is 200 (everything's OK) // here is where we will do the processing var xmlData = ajaxObject.responseXML.documentElement; var firstName = xmlData.getElementsByTagName("firstname").firstChild.data; var lastName = xmlData.getElementsByTagName("lastname").firstChild.data; var divContent = '<strong>First Name:</strong> ' + firstName + '<br /><strong>Last Name:</strong>' + lastName; document.getElementById('descriptionarea').innerHTML = divContent; } // end if else { // if the status code is anything else (bad news) alert('There was an error. HTTP error code ' + ajaxObject.status.toString() + '.'); return; // exit } } // end if // if the ready state isn't 4, we don't do anything, just // wait until it is... } // end function ajaxResponse </script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>First ever Ajax application with PHP</title> </head> <body style="color: rgb(255, 255, 255); background-color: rgb(99, 118, 153); direction: ltr;" alink="#ffffff" link="#ffffff" vlink="#ffffff"> <div style="text-align: center;"> <form name="ajaxform" method="get" action="javascript:;" onsubmit="doAjaxQuery('phonebookajax.php?fname=' + document.getElementById('fname').value);"> Name: <input type="text" name="fname" id="fname" value="" /><br /><br /> <input type="submit" value=" OK " /> </form> <br /> <br /> <br /> <br /> <div id="descriptionarea"></div> </body> </html> phonebookajax.php this is where the does the mysql query and then prints out the results into xml <?php header('Content-type: text/xml'); echo '<'.'?'.'xml version="1.0" ?'.'>'."\n"; // Error Display ini_set('display_errors', 1); ini_set('log_errors', 1); ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); error_reporting(E_ALL & ~E_NOTICE); //Connect to Server and Select Database $con = mysql_connect("localhost","root","*******"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("phonedirectory", $con); // Start script $queryfirstname = "SELECT * FROM employee WHERE EmpFName = '" . $_GET['fname'] . "'"; $firstname = mysql_query($queryfirstname) or die(mysql_error()); $rows = mysql_num_rows($firstname); if ($rows > 0) { ?> <results> <?php while($row = mysql_fetch_array($firstname)) { $resultfname = $row['EmpFName']; $resultlname = $row['EmpLName'];?> <result> <firstname><?php echo $resultfname; ?></firstname> <lastname><?php echo $resultlname; ?></lastname> </result> <?php } ?> </results> <?php } else { echo 0; } ?> any suggestions? tips? for something that would make this better? Quote Link to comment Share on other sites More sharing options...
Psycho Posted March 17, 2009 Share Posted March 17, 2009 You're making this too complicated. When you do the AJAX call simply query for the results then build the formatted output within the PHP code and deliver the formatted results back to the JavaScript to display on the page. The results of an AJAX call do not have to be XML data. function ajaxResponse() { // this function will handle the processing // N.B. - in making your own functions like this, please note // that you cannot have ANY PARAMETERS for this type of function!! if (ajaxObject.readyState == 4) // if ready state is 4 (the page is finished loading) { if (ajaxObject.status == 200) // if the status code is 200 (everything's OK) { // here is where we will do the processing var divContent = ajaxObject.responseXML.documentElement; document.getElementById('descriptionarea').innerHTML = divContent; } else // if the status code is anything else (bad news) { alert('There was an error. HTTP error code ' + ajaxObject.status.toString() + '.'); return; // exit } } // end if // if the ready state isn't 4, we don't do anything, just // wait until it is... } // end function ajaxResponse <?php // Error Display ini_set('display_errors', 1); ini_set('log_errors', 1); ini_set('error_log', dirname(__FILE__) . '/error_log.txt'); error_reporting(E_ALL & ~E_NOTICE); //Connect to Server and Select Database $con = mysql_connect("localhost","root","*******"); if (!$con) { die('Could not connect: ' . mysql_error()); } mysql_select_db("phonedirectory", $con) or die ('Could not select db: ' . mysql_error());; // Start script $firstName = mysql_real_escape_string($_GET['fname']); $queryfirstname = "SELECT * FROM employee WHERE EmpFName LIKE '%{$firstName}%'"; $firstname = mysql_query($queryfirstname) or die(mysql_error()); $rows = mysql_num_rows($firstname); if (mysql_num_rows($firstname)==0) { echo "<table>"; echo "<tr><th>Last Name</th><th>First Name</th></tr>"; while($row = mysql_fetch_array($firstname)) { echo "<tr><td>{$row['EmpLName']}</td><td>{$row['EmpFName']}</td></tr>"; } echo "</table>"; } else { echo "No results found."; } ?> NOTE: Modified the query to 1) escape the user value to prevent SQL injection/data corruption and 2) use a LIKE clause so the user can find partial matches Quote Link to comment Share on other sites More sharing options...
willrockformilk Posted March 17, 2009 Author Share Posted March 17, 2009 so the just go back to the interface page as text data? when i tried your code it simply printed out [object] where the results were suppose to be. you are right though. i tend to have a habit of over-complicating thinks on a very regular basis. Quote Link to comment Share on other sites More sharing options...
willrockformilk Posted March 17, 2009 Author Share Posted March 17, 2009 ok couple problems after some testing. first off the security changes you made would not run properly. dunno if it was syntax so i changed em back. once i get it working then ill go back to making it secure. second if (mysql_num_rows($firstname)==0) was changed to if (mysql_num_rows($firstname)!=0) the first way yielded no results found with a valid entry. to test it i put /phonebookajax.php?fname=amy to see what the results were. i got them into a nice pretty table from the php code like you suggested. when i would go and do a search in /phonebook.php it simple prints out "null" in the results field. any ideas why? Quote Link to comment Share on other sites More sharing options...
Psycho Posted March 17, 2009 Share Posted March 17, 2009 I typically do not test the code I post and instead consider it a "guide" to the poster (ergo the text in my sig). I appreciate the fact that you found/resolved the minor errors - typically people just post back "your code didn't work". Anyway, I'm not an AJAX expert, but I think the problem is that the original code was designed to expect XML data. After looking at a tutorial it looks like there are different ways to receive the response data. Try changing this var divContent = ajaxObject.responseXML.documentElement; To this var divContent = ajaxObject.responseText; Quote Link to comment Share on other sites More sharing options...
willrockformilk Posted March 17, 2009 Author Share Posted March 17, 2009 yeah i figured that out on my lunch break. var divContent = ajaxObject.responseXML.documentElement; was the error. it was looking for xml coming back and we were giving it html. thank you for your help! ps i was just letting you know what i changed and how that might effect your code you posted. i dont expect you to write it for me. Quote Link to comment Share on other sites More sharing options...
Psycho Posted March 17, 2009 Share Posted March 17, 2009 Please mark the topic as solved. And, I was not implying that you did expect me to write the code for you. I was just commenting on the fact that you, unlike many posters, took responsibility for reviewing the code that was providied and providing constructive feedback on what didn't work right. For that I thank you. Far too often I see replies from people simply stating that the code doesn't work without providing an error message, let alone actually doing the simplest of debugging. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.