Link to home
Start Free TrialLog in
Avatar of Colin Brazier
Colin BrazierFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Help with ajax autocomplete script

I would like to get an ajax call working for an autocomplete text field, it fetches players' names.  In the same query that gets the names I can retrieve the phone number of each player.  

What I want to do, is that when the user picks the player from the list, I want to flag up if the chosen player has no number stored. I don't want to show the number on the screen at all.

What I have done so far can be tested at http://www.col-b.uk/fines_text.php

I have little knowledge of javascript, so I have included first_name, surname and tel_mobile fields as one string of data to be returned from the selection.  

1. I need to show/hide the 'No number stored' message at the right times.
2. I never want to show the number on the screen.
3. In this test data, the only person with no number is Steve Johnson.

Data
DROP TABLE IF EXISTS players;

CREATE TABLE players (
  id                int AUTO_INCREMENT NOT NULL,
  first_name        varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  surname           varchar(25) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  tel_mobile        varchar(20) CHARACTER SET utf8 COLLATE utf8_general_ci,
  /* Keys */
  PRIMARY KEY (id)
) ENGINE = MyISAM;

INSERT INTO players (first_name, surname, tel_mobile) VALUES ('Alan','Johnson','00123 121212');
INSERT INTO players (first_name, surname, tel_mobile) VALUES ('Albert','Johnson','00123 121212');
INSERT INTO players (first_name, surname, tel_mobile) VALUES ('Alan','Jones','00123 121212');
INSERT INTO players (first_name, surname, tel_mobile) VALUES ('Simon','St John','00123 121212');
INSERT INTO players (first_name, surname, tel_mobile) VALUES ('Steve','Johnson','');
INSERT INTO players (first_name, surname, tel_mobile) VALUES ('Roger','Winlake','00123 121212');
INSERT INTO players (first_name, surname, tel_mobile) VALUES ('Sheila','Johnston','00123 121212');

Open in new window


Front end
<div id="page_container">
    <div>
        <h2>Send a Fines Notification via SMS</h2>
        
        <form action="fines_text_update.php" method="post">
            <p>Message</p>
            <div>
                <textarea name="txtMessage" cols="100" rows="6" maxlength="600" placeholder="<?=$text_message?>" required><?=$text_message?></textarea>
            </div>
            <p>To:</p>
            <div id = "player_name">Player Name: <input id="txtName" name="txtName" type="text" size="40" maxlength="40"/> <input type="hidden" id="hdnTel_mobile" name="hdnTel_mobile" value=""/>  </div>
            <div id = "player_list">
                <!-- infilled by ajax call -->            
            </div> 
        	<br />	
        	<div id="error_message" name="error_message" style="width: 80%; margin: auto; font-weight: bold; color: red;"><?=$error_message?></div>
        
        	<div id="buttons_line" style="margin: 0.8em auto 0;">
            	<input type="submit" name="submit" value="Submit" class="button" > 
                <input type="reset"  name="reset"  value="Reset"  class="button" > 
                <input type="button" name="cancel" value="Cancel" class="button" onclick="window.location.href='menu2.php'"/> 
        	</div>
        </form>
    </div>
</div>
</body>
</html>
<script>  
 $(document).ready(function(){   
      $('#txtName').keyup(function(){  
           var player_name_part = $(this).val();  
           if(player_name_part != '')  
           {  
                $.ajax({  
                     url:"player_search.php",  
                     method:"POST",  
                     data:{query:player_name_part},  
                     success:function(data)  
                     {  
                          $('#player_list').fadeIn();  
                          $('#player_list').html(data);  
                     }  
                });  
           }  
      });  
	  
      $(document).on('click', 'li', function(){  
           $('#txtName').val($(this).text()); 
		   $('#hdnTel_mobile').val($(this).text()); 
		   var myData=$(this).text();
		   if(!hasNumber(myData))
		   {
		   		$('#error_message').html("This player has no stored number.");
		   }
		   else
		   {
		   		$('#error_message').html("");
		   }
		   
           $('#player_list').fadeOut();   
		   
		   /* see if the chosen player has a number stored. */	
			
      });  
	  
	 function hasNumber(myString) {
		return /\d/.test(myString);
	 }
 });  
 </script>  

Open in new window


Search code
if(isset($_POST["query"]))  
{  
    $output = '';  
	if (!$player_list = getPlayerSearchList($dbi, trim($_POST["query"])))
	{
		$msg = "Error with the player search query. Click the button to return.";
		end_prog($msg);
	}
	
	$output = '<ul class="list-unstyled">';  
	if ($player_list == 'Empty set')
	{  
	   $output .= '<li>Player not found</li>';  
	}  
	else
	{
	   	foreach ($player_list AS $row)
		{ 
			$output .= '<li>'.$row["first_name"].' '.$row["surname"].' <span style="display:none;">'.$row["tel_mobile"].'</span></li>';
	   	}  
	} 
	$output .= '</ul>';  
	
	/*if (trim($row["tel_mobile"]) == '')
	{
		
	}*/
	echo $output;  
}

Open in new window


What happened to the question preview feature?
ASKER CERTIFIED SOLUTION
Avatar of leakim971
leakim971
Flag of Guadeloupe image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Colin Brazier

ASKER

Thanks, but if there is a number, I see it in the text field (as part of my clumsily returned data), and how do I get rid of the message if I pick someone without a number and want to start again?
Thanks, but if there is a number, I see it in the text field (as part of my clumsily returned data)

if/else

use the else...

and how do I get rid of the message if I pick someone without a number and want to start again?

please open a new thread
Not sure you understand but never mind, I'll have another go at sorting myself.  Thanks for your help.
you welcome