Jump to content

Using Variables from Ajax


Zergman

Recommended Posts

Using the tutorial found here http://www.w3schools.com/PHP/php_ajax_database.asp

 

PHP file

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?> 

 

Form on main page

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>

 

Javascript

<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>

 

So what I need to do is store  $row['LastName'] in my form to submit to the database.  Right now, it shows it, but doesn't actually put it into the form

 

For example

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b><?php echo $row['LastName'] ;?></b></div>

 

Any ideas?

Link to comment
Share on other sites

Using the tutorial found here http://www.w3schools.com/PHP/php_ajax_database.asp

 

PHP file

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', 'peter', 'abc123');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?> 

 

Form on main page

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>

 

Javascript

<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>

 

So what I need to do is store  $row['LastName'] in my form to submit to the database.  Right now, it shows it, but doesn't actually put it into the form

 

For example

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b><?php echo $row['LastName'] ;?></b></div>

 

Any ideas?

 

 

Before you do anything, make sure your JS functions are located in the <HEAD> section of the parent file.

 

It sounds like you are wanting to be able to pull form data and pass it to a file called getuser.php using the GET method.  I personally prefer POST as it is more secure, but I think we can work with what you have.  You are passing a variable (str) but you'll have to get that variable the JS way, not the HTML way.  1st assign an ID to your select:

 

<select name="users" id="users" onchange="javascript:showUser();">

 

Now, Lets get the value of that from inside the AJAX function.

 

<script type="text/javascript">
function showUser(){
var str = document.getElementById("users").value;
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>

 

Try that out and see what happens.  As for targeting other types of HTML containers, I've never tried it, but it it my understanding that if it has an ID and can contain what you are sending it, then it should work.  Good luck!

 

Link to comment
Share on other sites

The javascript is in the header for sure.

 

I put in the changes you suggested but now the script won't fire.  I guess I left out 1 piece of information.  I changed from a <select> to a standard textbox in my app for this.

<input type="text" name="findagentid" id="findagentid" class="textboxstyle" size="15" maxlength="8" value="<?php echo $emp_id; ?>" onchange="showUser(this.value)" />

 

Wouldn't I need to put something on the getusers.php to send the info BACK to the parent page?

Link to comment
Share on other sites

Im with ya gamesmstr.

 

So understand the info from getusers.php is echoed and displayed in the <div> tag on the parent page, but how would i echo the same info inside a form element?

 

Would I put the form element code on the getusers.php page?

 

Sorry but ajax is really new to me :)

Link to comment
Share on other sites

either that or use JS to update the value of the form field and it can be done from inside the ajax call.  Just make sure you assign an ID to the field Example: <INPUT TYPE="TEXT" ID="myfield">

 

The JS command would be something like this:

 

document.getElementById("myfield").value=q;

 

Where q was the variable containing the value you wanted to update the field with.

 

 

And don't sweat it.  AJAX is confusing at first, but once you get the hang of it, it really makes a pretty website.

 

 

Link to comment
Share on other sites

Still working on this, but just can't get it to go.  Can't get the data returned by getuser.php to show up on parent page.

 

I tried attaching it to a form element value but the value remains empty.

 

Really having touched the javascript on parent page

<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>

 

Here's my form

<form>
<table align="center" cellpadding="2" cellspacing="0" border="0">
<tr>
	<td align="right"><label>Find Agent Info :</label></td>
	<td align="left"><input type="text" name="findagentid" id="findagentid" class="textboxstyle" size="15" maxlength="8" value="" onchange="showUser(this.value)" /></td>
</tr>
<tr align="left">
	<td align="right"><input type="text" name="agentID" id="agentID" class="textboxstyle" size="10" maxlength="8" value="" /></td>
	<td><div id="txtHint"></div></td>
</tr>
</form>

 

Trying to get the results from getuser.php to show in the agentID field.

 

getuser.php just echos value

echo $row_rsagentquery1['employee_id'];

 

Ajax is cool, but tough to learn lol

Link to comment
Share on other sites

Ah, so the only problem left is that it simply won't target that form field with the value.  One last thing you might try...

 

Change this:

 

document.getElementById("agentID").innerHTML=xmlhttp.responseText;

 

to this:

 

document.getElementById("agentID").value=xmlhttp.responseText;

 

Don't know why I didn't think of that before.  this is how I update form fields with price totals etc.. without actually submitting the form.

 

This is the JS

function totalprice(){
            var quant = document.getElementById("quantity").value;
            var price = document.getElementById("price").value;
            var tot = quant*price;
            document.getElementById("total").value=tot;
        }

 

And this is the form with trigger:

Quantity: <input type="text" size="10" id="quantity" name="quantity" value="0" onKeyUp="totalprice();">
Price Each: <input type="text" size="10" id="price" name="price" value="0" onKeyUp="totalprice();">
Total Price: <input type="box" size="10" id="total" name="total" READONLY value="0">

 

Good luck!

 

Link to comment
Share on other sites

document.getElementById("agentID").value=xmlhttp.responseText;

 

Worked like a charm!  Thanks gamesmstr!

 

Here's something else im wondering. 

How would I had more fields to this?  Say I need my getusers.php to not only fill in the agentID field, but say 2 or 3 more with info from the same query?

 

One thing i'm not sure of is do I need to echo the variable on the getusers.php page for it to show on the parent page?

Link to comment
Share on other sites

All getusers.php does is a mysql query and echo right now 1 value.

echo $row_rsagentquery1['employee_id'];

 

Want to use other values from that query to update other fields in the parent page.

 

No worries that you have to run, I'll keep picking and learning with this :)

Link to comment
Share on other sites

Put a JS function in the parent file in the HEAD section with your AJAX function.  Something like this:

function filform(formval1,formval2,formval3){
  document.getElementById("formfield1").value=formval1;
  document.getElementById("formfield2").value=formval2;
  document.getElementById("formfield3").value=formval3;
}

 

Then call that function from inside getuser.php

 

<script>javascript:fillform('<?php echo"$formval1,$formval2,$formval3";?>');</script>

 

Not really thinking clearly right now, but something like that SHOULD work.

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.