• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 937
  • Last Modified:

Ajax, returning multiple values from PHP script

Hello,

I have a form, which has many fields, but the main field is ID, once a person punches in an ID, I would like that ID to go through an AJAX function and return a few values, which will be filled out in the other fields in the forms, such as Name, lastname, Adress.  And some of the fields such as STATE, is a drop down menu.  How do I make the information that I grab from AJAX tell the drop down menu the default value, and still have the other states listed, so that it can be changed.
0
falimorad
Asked:
falimorad
  • 6
  • 6
  • 5
  • +1
2 Solutions
 
Andyc75Commented:
When you build the drop down in the ajax call, you can specify the selected value by using selected="selected"

<select>

</select>
0
 
Andyc75Commented:
Sorry should be

<select name="dropdown1">
    <option value="1">item 1</option>
    <option selected="selected" value="2">item 2</option>
     <option value="3">item 3</option>
</select>

Is this what you were trying to accomplish ?
0
 
AlexanderREnterprise Web DeveloperCommented:
JSON should do the job here.  I will also use jQuery to make job easier.
You have an input for id which should be like
<input type="text" name="id" />
and a button which user can click to look up the id
<input type="button" value="Search" id="search">

AJAX function to handle your requirements should be in the <head></head>:
<head>
<script type="text/javascript" src="jquery.js"></script>  
<script type="text/javascript">
$(document).ready(function(){
     $('#search').click(function(){
          $.post("search.php", { id: $('#id').val()},
                function(data){
                      // here you can fill out values for your form fields by id
                     $("name").val(data.name);
   });
      });
});
</script>
</head>

for the $("name").val(data.name); line to work PHP needs to return data in JSON format:
<?php
$id = $_POST['id'];
// perform your DB query based on that id which return array like
$data = array('name' => 'alex');
// and make a json out of it
echo json_encode($data);
0
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
AlexanderREnterprise Web DeveloperCommented:
*
sorry, <input type="text" name="id" /> should be <input type="text" id="id" /> or else the ID will never be picked up by ajax function
0
 
leakim971PluritechnicianCommented:
Hello falimorad :

Check this thread :

page.html :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
        function setMessage(messageid) {
                if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                xmlhttp.open("GET","getmessage.php?messageid="+messageid.value,false);
                xmlhttp.send(null);
                if(xmlhttp.readyState==4) {
                                        var json = eval('[' + xmlhttp.responseText + ']');
                                        document.forms[0].id.value = json[0].id;
                                        document.forms[0].surname.value = json[0].surname;
                                }
        }
</script>
</head>
<body>
<form>
    <input type="text" name="class_number" size="3" maxlength="3" /><br />
    <input type="button" value="Set id and surname" onclick="setMessage(document.forms[0].class_number);" />
    <br />
    id : <input type="text" name="id" readonly="readonly" /><br />
    surname : <input type="text" name="surname" readonly="readonly" />
</form>
</body>
</html>

Open in new window

0
 
leakim971PluritechnicianCommented:
Miss the thread in previous post : http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Q_25416749.html

And getmessage.php :



<?PHP 
        $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); 
        if(!$link) die('Could not connect: ' . mysql_error()); 
        if(!mysql_select_db('database_name'))die('Could not select database: ' . mysql_error()); 
 
        $result = mysql_query("SELECT id, CONCAT(fname,' ',lname) AS surname FROM emp WHERE num = " . $_GET["messageid"]);
 
        if(!$result) die('Could not query:' . mysql_error()); 
        echo json_encode(mysql_result($result)); 
        mysql_close($link); 
?>

Open in new window

0
 
falimoradAuthor Commented:
leakim971 and AlexanderR both of you have great solutions.  We are almost there, do you know how I would put one of the values on a drop down list, for instance the drop down list already has values, but once it finds the State value (e.g OH), it will make that as the selected value.  What is the javascript code for that, I am new to javascript, so bear with me...thanks.
0
 
leakim971PluritechnicianCommented:
You may use :


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
        function setMessage(messageid) {
                if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                xmlhttp.open("GET","getmessage.php?messageid="+messageid.value,false);
                xmlhttp.send(null);
                if(xmlhttp.readyState==4) {
                                        var json = eval('[' + xmlhttp.responseText + ']');
                                        document.forms[0].id.value = json[0].id;
                                        document.forms[0].surname.value = json[0].surname;
                                }
        }
</script>
</head>
<body>
<form>
    <select id="class_number" name="class_number" onchange="setMessage(this.value);">
        <option value="">Choose one</option>
        <option value="OH">Ohio</option>
        <option value="CA">California</option>
    </select>
    <br />
    id : <input type="text" name="id" readonly="readonly" /><br />
    surname : <input type="text" name="surname" readonly="readonly" />
</form>
</body>
</html>

Open in new window

0
 
AlexanderREnterprise Web DeveloperCommented:
jquery for selects drop down works identical for others. So you can easily use
$("state").val(data.state);

as long as the data.state from $data contains value found in the drop down:
<option value="OH"></option>
will work with php
$array('name'=>'alex', 'state'=>'OH');
0
 
falimoradAuthor Commented:
AlexanderR, I tried your method, but the problem is, that when I click the button, it doesn't do anything.  I checked everything.  The PHP script works perfectly, I tested that out separately to make sure, but the actual file that contains the jquery script, it doesn't do anything when I click the button. I haven't used jquery really.  Do I need an onclick function in the button definition.

leakim971: Your drop down method won't work, as it is passing over a STATE value as oppose as passing an ID value, and from the ID, it should retrive the state and place it in the STATE dropdown
0
 
leakim971PluritechnicianCommented:
Another example to fill a dropdown :

the page :
<html>
<head>
<script language="javascript">
        function fillStateDropDown(theid) {
                if(window.XMLHttpRequest) xmlhttp=new XMLHttpRequest(); else xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
                xmlhttp.open("GET","getstate.php?id="+theid,false);
                xmlhttp.send(null);
                if(xmlhttp.readyState==4) {
                        sStates = document.getElementById('stateDropDown');
                        var states = eval('(' + xhr.responseText+ ')');
                        for(var s in states) {
                                var o = document.createElement('option');
                                o.value = states[s].stateVal;
                                o.text = states[s].stateText;
                                sStates.add(o,null);
                        }
                }
    }
</script>
</head>
<body onload="getUsers">
<select id="theidvalue" name="theidvalue" onchange="if(this.selectedIndex>0) fillStateDropDown(this.value);" >
  <option value="">Choose one...</option>
  <option value="1">text for id 1</option>
  <option value="2">text for id 2</option>
  <option value="3">text for id 3</option>
</select>
<select id="stateDropDown" name="stateDropDown"></select>
</body>
</html>

Open in new window

0
 
leakim971PluritechnicianCommented:
getstate.php :

(replace localhost, mysql_user, mysql_password and database_name of course with your own values)
<?PHP 
        $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); 
        if(!$link) die('Could not connect: ' . mysql_error()); 
        if(!mysql_select_db('database_name'))die('Could not select database: ' . mysql_error()); 
 
        $result = mysql_query( "SELECT stateVal, stateText FROM statesTable WHERE id=" . $_GET['id'] );
 
        if(!$result) die('Could not query:' . mysql_error()); 
        echo json_encode(mysql_result($result)); 
        mysql_close($link); 
?>

Open in new window

0
 
AlexanderREnterprise Web DeveloperCommented:
Did you download jquery library?
Using this method, along with some refinement, you do not have to download jquery lib yourself and it takes care of some other things automatically too.   just make sure you link all the form input IDs with whatever is after # sign from lines 10.
<html> 
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>  
<script type="text/javascript">
$(document).ready(function(){ 
  $('#search').click(function(){ 
    $.getJSON("search.php", { id: $('#id').val()}, 
	function(data){
	  // here you can fill out values for your form fields by id
          $("#name").val(data.name);
	  $("#state").val(data.state);
	});
   });
      });  
</script>
</head>
<body>

<input type="text" id="id" />
<input type="text" id="name" />
<select id="state">
<option value="default">default</option>
<option value="OH">OH</option>
</select>
<input type="button" value="Search" id="search" />
</body>
</html>

Open in new window

0
 
AlexanderREnterprise Web DeveloperCommented:
and btw, if you go to search.php directly, it should return something in format
{"name":"alex","state":"OH"}
0
 
falimoradAuthor Commented:
Well when I test the script directly, I get the following

{"location":"GC","zone":"B","floor":"B","room":"B307"}

So it works well, the only problem is when I am at the main site, and I click the button so that the ajax function can work, it doesn't.
0
 
falimoradAuthor Commented:
I tested it out with the following code

<script type="text/javascript" src="jquery.js"></script>  
<script type="text/javascript">
$(document).ready(function(){
     $('#search').click(function(){
          $.post("search.php", { serialnumber: $('#serialnumber').val()},
                function(data){
                      // here you can fill out values for your form fields by id
                     $("room").val(data.room);
   });
      });
});
</script>


<td>Serial number:
      <input id="serialnumber" type="text" size="20" />
<<
<input type="button" id="search" value="Get Device Info" /></td>



<td>Room number:
      <input type="text" name="room" id="room" /></td>
0
 
AlexanderREnterprise Web DeveloperCommented:
oh, use my latest code from my 28454864 comment
0
 
falimoradAuthor Commented:
AlexandarR your solution worked perfect leakim971, your solution was partly, but all in all, thank you very much guys.  I appreciate it.
0
 
leakim971PluritechnicianCommented:
Thanks for the points!
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

  • 6
  • 6
  • 5
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now