Jump to content

[SOLVED] kinda complicated output results


willrockformilk

Recommended Posts

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?

 

 

 

 

Link to comment
Share on other sites

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

 

Link to comment
Share on other sites

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?

 

Link to comment
Share on other sites

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;

Link to comment
Share on other sites

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. :)

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.