Jump to content

Ajax with PHP: click PHP result and autofill form with results


kjetterman

Recommended Posts

When I click on the letter of the alphabet on my form page, it will bring up the results of my query.  I got this part working.  The next part is to be able to click on any of the populated results and have it autofill my form with organization, first name, last name, email address and phone number.

 

I know that I need to use Ajax and jQuery to accomplish this. 

 

Here is my html

<!-- Letter Search -->
<div class="searchBox span12">

	<h3>Choose the First Letter of the Person's Last Name</h3>
	<ul>
        <li class="alphabets" id="A"><a href="?by=A">A</a></li>
        <li class="alphabets" id="B"><a href="?by=B">B</a></li>
        <li class="alphabets" id="C"><a href="?by=C">C</a></li>
        <li class="alphabets" id="D"><a href="?by=D">D</a></li>
        <li class="alphabets" id="E"><a href="?by=E">E</a></li>
        <li class="alphabets" id="F"><a href="?by=F">F</a></li>
        <li class="alphabets" id="G"><a href="?by=G">G</a></li>
        <li class="alphabets" id="H"><a href="?by=H">H</a></li>
        <li class="alphabets" id="I"><a href="?by=I">I</a></li>
        <li class="alphabets" id="J"><a href="?by=J">J</a></li>
        <li class="alphabets" id="K"><a href="?by=K">K</a></li>
        <li class="alphabets" id="L"><a href="?by=L">L</a></li>
        <li class="alphabets" id="M"><a href="?by=M">M</a></li>
        <li class="alphabets" id="N"><a href="?by=N">N</a></li>
        <li class="alphabets" id="O"><a href="?by=O">O</a></li>
        <li class="alphabets" id="P"><a href="?by=P">P</a></li>
        <li class="alphabets" id="Q"><a href="?by=Q">Q</a></li>
        <li class="alphabets" id="R"><a href="?by=R">R</a></li>
        <li class="alphabets" id="S"><a href="?by=S">S</a></li>
        <li class="alphabets" id="T"><a href="?by=T">T</a></li>
        <li class="alphabets" id="U"><a href="?by=U">U</a></li>
        <li class="alphabets" id="V"><a href="?by=V">V</a></li>
        <li class="alphabets" id="W"><a href="?by=W">W</a></li>
        <li class="alphabets" id="X"><a href="?by=X">X</a></li>
        <li class="alphabets" id="Y"><a href="?by=Y">Y</a></li>
        <li class="alphabets" id="Z"><a href="?by=Z">Z</a></li>
     </ul>
     	<? include('search.php'); ?>
    
</div>
     
<hr style="color:#ccc; margin-bottom:20px;" />

<!-- Main Form -->

<div id="mainForm">
	<form method="post" id="icsForm" class="searchBox span12">
    	     <div id="col1" class"span6">
    	           <h3>Contact Information</h3>
                        <label>Church / Organization:</label><input type="text" name="organization" id="organization" class="span6 upright" /><br />
		        <label>First Name:</label><input type="text" name="firstName" id="firstName" class="span6 upright" />
                        <label>Last Name:</label><input type="text" name="lastName" id="lastName" class="span6 left upright" />
                        <label>Email Address:</label><input type="text" name="email" id="email" class="span6 left upright" />
                        <label>Phone Number:</label><input type="text" name="phone" id="phone" class="span6 left upright" />
        </div>
</div>

Here is my php

if(preg_match("/^[A-Z | a-z]+/", $_POST['name'])){
$name=$_POST['name'];
}

if(isset($_GET['by'])){
$letter=$_GET['by'];

//query to sort by last name

$sql="SELECT contact_id, first_name, last_name, church_org, email_address, phone_number FROM ics_data WHERE last_name LIKE '$letter%' ORDER BY last_name ASC";

//run the query against the mysql query function
$result=mysql_query($sql); 

//count results
$numrows=mysql_num_rows($result);

echo "<p>" .$numrows . " results found for " . $letter . "</p>"; 

//Create while loop and loop through result set
while($row=mysql_fetch_array($result)){

        $first_name=$row['first_name'];
	$last_name=$row['last_name'];
	$church_org=$row['church_org'];
	$email_address=$row['email_address'];
	$phone_number=$row['phone_number'];
	$contact_id=$row['contact_id'];
	
//display the result of the array

echo "<div id=\"search-results\">";
echo "<ul class=\"letter-results\">\n"; 
echo "<li class=\"result-row\">" . "<a href=\"#\" class=\"testclass\">"  .$first_name . " " .$last_name . "". ",  " ."" .$church_org ."</a></li>\n";
echo "</ul>";
echo "</div>";
}
}


Here is my Javascript file (Ajax)

$(document).ready( function() {
	function formfill() {
		var organization = $('#organization').val();
		var firstname = $('#firstname').val();
		var lastname = $('#lastname').val();
		var email = $('#email').val();
		var phone = $('#phone').val();
		$.ajax ({
			method: "GET",
			url: "search.php",
			dataType: 'json',
			data: {
				organization:organization, firstname:firstname, lastname:lastname, email:email, phone:phone
			},
			type: "POST",
			success: function(data) {
				$organization
				$firstname
				$lastname
				$email
				$phone
			},
			
	 	failure: function() {
                alert('fail!');
            }
        });
	}
  

I know that I do not have a reference yet to JSON in my php file and that it is needed.  I'm not solid on the Ajax part.  That is the part that is tripping me up.  I know that I need to make the form autofill when clicking on a specific result returned from my query... but i'm not sure how to do that.

 

Thank you in advance for any help or advice you can give!! :)  I am relatively new to programming.  Hopefully I posted this in the right forum as a lot of these technologies overlap.

Edited by kjetterman
Link to comment
Share on other sites

  • 5 weeks later...

I'm not exactly sure how your code relates.  Your PHP seems to be searching for the person based on letter of last name and your JavaScript appears to be what you want to do with your form.  Nonetheless I will provide basic outlines of something you can do.  You should try organizing your search return first:

/*
Organized code for readability - Changed # to javascript:void(0) to get rid of the annoying page scroll
Added the onclick event - Inside must be a unique database identifier (I am just assuming contact_id is)
*/
echo '<div id="search-results">';
echo "<ul class='letter-results'>\n";
echo "<li class='result-row'><a href='javascript:void(0)' onclick='formFill(\"{$contact_id}\");' class='testclass'>{$first_name} {$last_name},  {$church_org}</a></li>\n";
echo '</ul>';
echo '</div>';

Then your JavaScript would be something like:

// Functions do not work well in document ready calls
// This function will(should) fire from the onclick event we just set in the PHP
function formFill(contact_id) {

  // You might want to clear the information in the form in case the user selects another person
  $("#organization").val("");
  $("#firstname").val("");
  $("#lastname").val("");
  $("#email").val("");
  $("#phone").val("");

  $.ajax({
    url: "fill_form.php",
    type: "POST",
    data: {
      "contact_id" : contact_id
    },
    dataType: "json",
    success: function(data) {

      // Request was valid but it triggered one of our set errors
      if(data.hasOwnProperty('error')) {
        // You can choose a better option for error returning
        alert(data.error);
        return false;
      }

      // Fill the form with the information
      $("#organization").val(data.organization);
      $("#firstname").val(data.firstname);
      $("#lastname").val(data.lastname);
      $("#email").val(data.email);
      $("#phone").val(data.phone);

    },
    error: function(data) {
      /*
        Add an error function if you want.
        Since it is in Json format, any returned text from the error will accessible in data.responseText
      */
  });
 
}
 
$(document).ready(function() {
 
  // Do whatever you are doing for searching via letter of last name
 
});

Now: Your new PHP file (in this case fill_form.php) will have to access the database to get the information based on the contact_id

/*
    Validate that contact_id is set
    Connect to the database
    If contact_id will always be a number, you can just use $contact_id = (int)$_POST['contact_id'];
    Note that removing the '' around {$contact_id} in the query if you use that method will leave you open to SQL Injection
    Otherwise use the below
*/
$contact_id = mysql_real_escape_string($_POST['contact_id']);
 
$sql = "SELECT `first_name`, `last_name`, `church_org`, `email_address`, `phone_number` FROM `ics_data` WHERE `contact_id` = '{$contact_id}'";

//run the query against the mysql query function
$result=mysql_query($sql); 
 
// Valid results
if(mysql_num_rows($result) != 0) {
 
    // Because your $.ajax call has a dataType of json, you will need to json_encode everything
    $log = array();
 
    $log['organization'] = $result['church_org'];
    $log['firstname'] = $result['first_name'];
    $log['lastname'] = $result['last_name'];
    $log['email'] = $result['email_address'];
    $log['phone'] = $result['phone_number'];
 
   json_encode($log);
 
} else
    die(json_encode(array("error" => "No results")));

None of this was tested.

 

 

Consider updating your PHP query functions to mysqli instead of mysql.

You need to protect against SQL Injection and XSS in your original code as well

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.