Link to home
Start Free TrialLog in
Avatar of falimorad
falimoradFlag for Afghanistan

asked on

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.
Avatar of Andyc75
Andyc75
Flag of Canada image

When you build the drop down in the ajax call, you can specify the selected value by using selected="selected"

<select>

</select>
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 ?
Avatar of AlexanderR
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);
*
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
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

Miss the thread in previous post : https://www.experts-exchange.com/questions/25416749/Returning-two-values-with-javascript.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

Avatar of falimorad

ASKER

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.
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
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');
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
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

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

ASKER CERTIFIED SOLUTION
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
and btw, if you go to search.php directly, it should return something in format
{"name":"alex","state":"OH"}
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.
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>
oh, use my latest code from my 28454864 comment
AlexandarR your solution worked perfect leakim971, your solution was partly, but all in all, thank you very much guys.  I appreciate it.
Thanks for the points!