XMLHttpRequest to grab database values (Wordpress) - php

I'm having issues getting my local Wordpress installation to properly grab data from a database. Im using xmlhttprequest to call a php file which has my database request and then sends it back. This all works on my local installation without Wordpress but once i moved it all over to a locla Wordpress im not getting any information back.
I was able to successfully add the Javascript XMLHttpRequest function to my php template and the function is called properly when I use the onchange event on dropdown select but doesnt seem to want to go over the other php request and start the db connection. Looking for any thoughts...thanks!
Drop down select on Index.php
<form method="get" action="./gardenguide.php">
<table>
<tr>
<td>Hardiness Zone</td>
<td>
<select name="zone" style="width:110px;" onchange="getVegetablesByZone(this.value)">
<option selected disabled>Select</option>
<option value="2a">Zone 2a</option>
<option value="2b">Zone 2b</option>
<option value="3a">Zone 3a</option>
<option value="3b">Zone 3b</option>
<option value="4a">Zone 4a</option>
<option value="4b">Zone 4b</option>
<option value="5a">Zone 5a</option>
<option value="5b">Zone 5b</option>
<option value="6a">Zone 6a</option>
<option value="6b">Zone 6b</option>
<option value="7a">Zone 7a</option>
<option value="7b">Zone 7b</option>
<option value="8a">Zone 8a</option>
<option value="8b">Zone 8b</option>
<option value="9a">Zone 9a</option>
<option value="9b">Zone 9b</option>
<option value="10a">Zone 10a</option>
<option value="10b">Zone 10b</option>
<option value="11a">Zone 11a</option>
<option value="11b">Zone 11b</option>
<option value="12a">Zone 12a</option>
<option value="12b">Zone 12b</option>
<option value="13a">Zone 13a</option>
<option value="13b">Zone 13b</option>
</select>
</td>
</tr>
</table>
<div id="results"><b></b></div>
</form>
JavaScript calling the XMLHTTP Request
function getVegetablesByZone(zone) {
if (zone == "") {
document.getElementById("results").innerHTML = "";
alert("works1");
return;
} else {
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("results").innerHTML = xmlhttp.responseText;
}
};
}
PHP called from Javascript
<?php
$q = $_GET['q'];
echo "LOL";
$con = mysqli_connect('localhost','user','pass');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"plants");
$sql="SELECT plant_name FROM plants WHERE plant_id IN (SELECT fk_plant_id from hardinesszone WHERE zone = '$q')";
$result = mysqli_query($con,$sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($con));
exit();
}
$display = "<table cellpadding=1 cellspacing=1 border=1>
<tr>";
$i=0;
while($row = mysqli_fetch_array($result)) {
if ($i < 3)
{
$display.= "<td><input type=\"checkbox\" name=\"v[]\" value=\"".$row['plant_name']."\"> " . $row['plant_name'] . "</td>";
}
else
{
$display.= "</tr><tr><td><input type=\"checkbox\" name=\"v[]\" value=\"".$row['plant_name']."\"> " . $row['plant_name'] . "</td>";
$i=0;
}
$i=$i+1;
}
$display .= "</tr></table>";
$display .= "<input type=\"submit\" class=\"btn btn-submit btn-lg\" id=\"submit\" value=\"Submit!\">";
echo $display;
mysqli_close($con);
?>

Related

getting a text value populated by a select option

i am in dire need here. i have gone to every person i know that knows php/mysql/ajax, but no one can help.
i am trying to get an input field populated with data from my dbase that is chosen from two different selects. here is the situation:
building a golf scoring page on my website. the user will choose a course (select #1), then the tee they played (select #2), which then the disabled text inputs will populate with the rating and slope. the rating and slope are very important b/c they help figure out the handicap for the user. i am able to get everything to populate fine, but i can't figure out the correct WHERE clause in my query on the get_rating.php page. can somebody help me with that query?
here is my code:
dbase setup:
this is pulling from 2 tables, one is the courses table (course_id, c_id, name) and the other is the course_tees table (tee_id, course_name, c_id, t_id, color, rating, slope). the c_id's on both tables are the same.
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" class='new_score'>
<div class='form-group'>
<select class="form-control" name="course_name" onchange="get_tees(this.value)">
<option value="">select a tee</option>
<?php get_courses() ?>
</select>
</div>
<div class='form-group'>
<select class='form-control' name='tee_played' onchange="get_rating(this.value)" id='txtHint'>
<option value="">select a tee</option>
</select>
</div>
<div class="form-group" id="getRating">
</div>
the first select uses the get_tees.php code (listed below) and the second one uses the get_rating.php code (listed 2 below) which is the one i'm having trouble with.
get_tees.php
$con = mysqli_connect("***","***","***","***") or die("connection was not established");
$q = intval($_GET['q']);
mysqli_select_db($con,"course_tess");
$sql="SELECT * FROM course_tees WHERE c_id = '".$q."'";
$result = mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result)) {
$tee_id = $row['tee_id'];
$c_id = $row['c_id'];
$t_id = $row['t_id'];
$tee_color = $row['color'];
$cor_rating = $row['rating'];
$cor_slope = $row['slope']; ?>
<option value='<?php echo $tee_id ?>'><?php echo $tee_color ?></option>
get_rating.php
$con = mysqli_connect("***","***","***","***") or die("connection was not established");
$q = intval($_GET['q']);
mysqli_select_db($con,"course_tees");
$sql="SELECT * FROM course_tees";
$result = mysqli_query($con,$sql);
while($row=mysqli_fetch_array($result)) {
$c_id = $row['c_id'];
$t_id = $row['t_id'];
$cor_rating = $row['rating'];
$cor_slope = $row['slope']; ?>
<input type='text' name='cor_rating' class='form-control' value='<?php echo $row['rating']; ?>' disabled>
<input type='text' name='cor_slope' class='form-control' value='<?php echo $row['slope']; ?>' disabled>
and here's my ajax for both selects:
function get_tees(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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","get_tees.php?q="+str,true);
xmlhttp.send();
}
}
function get_rating(str) {
if (str == "") {
document.getElementById("getRating").innerHTML = "";
return;
} else {
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("getRating").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","get_rating.php?q="+str,true);
xmlhttp.send();
}
}
am i not passing something correctly in my ajax? what am i doing wrong?!?! PLEASE help!!
#chris85 this is essentially the bandaid that i have put over the issue for right now ... instead of trying to populate the text fields automatically, i am listing them in the selects and manually putting in the rating/slope ... this is my code:
php:
mysqli_select_db($con,"course_tess");
$sql="SELECT * FROM course_tees WHERE c_id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<option value=''>select a tee</option>";
while($row=mysqli_fetch_array($result)) {
$tee_id = $row['tee_id'];
$c_id = $row['c_id'];
$t_id = $row['t_id'];
$tee_color = $row['color'];
$cor_rating = $row['rating'];
$cor_slope = $row['slope']; ?>
<option value='<?php echo $tee_color ?>'><?php echo $tee_color ?> - <?php echo $cor_rating ?> : <?php echo $cor_slope ?></option>
and the form:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" class='new_score'>
<div class='form-group'>
<select class="form-control" name="course_name" onchange="get_tees(this.value)">
<option value="">select a tee</option>
<?php get_courses() ?>
</select>
</div>
<div class='form-group'>
<select class='form-control' name='tee_played' onchange="get_rating(this.value)" id='txtHint'>
</select>
</div>
<div class="form-group">
<input type="text" class="form-control" name="cor_rating" placeholder="enter rating from above">
<input type="text" class="form-control" name="cor_slope" placeholder="enter slope from above">
</div>
so, like you can see, it's just a bandaid. if you want to see it working, go to the http://www.havikmarketing.com and sign in with these credentials:
EM: test#test.com
PW: testing123
then go up to the settings (gears) and choose 'new round'. go through and enter a score ... you'll see how it pulls everything through. now mind you, i just have it set up as pretty much a skeleton right now ... so no judging on the design :)
thanks again

Dynamically Adding Elements to table using ajax

When we are selecting a element from a dropdownlist it will display the value of that element but after that when we choose the next element from that dropdownlist it must display the value below the previous element.
I have done it till displaying the element but when next element is clicked the first one is not displaying.
Please help me to sort this out. I have created my code using HTML, AJAX and PHP.
<?php
$q = intval($_GET['q']);
$con = mysql_connect("localhost", "root", "", "registration");
if (!$con)
{
echo "Connection Failed..";
echo mysql_error($con);
}
$sql = "select * from dynamic where Id='".$q."'";
$result = mysql_query($con, $sql);
echo "<table border=3 bordercolor='pink' width=100 height=100>
<tr>
<th>Id</th>
<th>Name</th>
<th>Fathername</th>
<th>Age</th>
<th>Gender</th>
<th>Address</th>
</tr>";
while ($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".$row["Id"]."</td>";
echo "<td>".$row["Name"]."</td>";
echo "<td>".$row["Fathername"]."</td>";
echo "<td>".$row["Age"]."</td>";
echo "<td>".$row["Gender"]."</td>";
echo "<td>".$row["Address"]."</td>";
echo "</td>";
}
echo "</tables>";
mysql_close($con);
?>
<html>
<head>
<script>
function test(str) {
if (str == "") {
document.getElementById("tst").innerHTML="";
}
else {
if(window.XMLHttpRequest) {
xml = new XMLHttpRequest();
} else {
xml = new ActiveXObject("Microsoft.XMLHttp");
}
xml.onreadystatechange = function() {
if (xml.readyState == 4 && xml.status == 200) {
document.getElementById("tst").innerHTML = xml.responseText;
}
}
xml.open("GET", "mysqlajax.php?q=" + str, true);
xml.send();
}
}
</script>
<body>
<form>
<select name="User" onchange="test(this.value)">
<option value="">-Select user-</option>
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="4">S</option>
<option value="5">G</option>
<option value="6">S</option>
</select>
</form><br>
<b><div id="tst"></b></div>
</body>
</html>
Instead of overwriting innerHTML, try to append to it.
Try something like this:
HTML:
<html>
<head>
<script>
function test(str)
{
if(str=="")
{
document.getElementById("tst").innerHTML="";
}
else
{
if(window.XMLHttpRequest)
{
xml=new XMLHttpRequest();
}
else
{
xml=new ActiveXObject("Microsoft.XMLHttp");
}
xml.onreadystatechange=function()
{
if(xml.readyState == 4 && xml.status== 200)
{
var innerHTML = document.getElementById("tst").innerHTML;
innerHTML += xml.responseText;
document.getElementById("tst").innerHTML=innerHTML;
}
}
xml.open("GET","mysqlajax.php?q="+str,true);
xml.send();
}
}
</script>
<body>
<form>
<select name="User" onchange="test(this.value)">
<option value="">-Select user-</option>
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
<option value="4">S</option>
<option value="5">G</option>
<option value="6">S</option>
</select>
</form><br>
<b>
<div id="tst"></div>
</body>
</html>
PHP:
<?php
$q=intval($_GET['q']);
//$con=mysql_connect("localhost","root","","registration");
//if(!$con)
//{
//echo "Connection Failed..";
//echo mysql_error($con);
//}
//$sql="select * from dynamic where Id='".$q."'";
//$result=mysql_query($con,$sql);
echo "<table border=3 bordercolor='pink' width=100 height=100>
<tr>
<th>Id</th>
<th>Name</th>
<th>Fathername</th>
<th>Age</th>
<th>Gender</th>
<th>Address</th>
</tr>";
//while($row=mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>".rand()."</td>";
echo "<td>".rand()."</td>";
echo "<td>".rand()."</td>";
echo "<td>".rand()."</td>";
echo "<td>".rand()."</td>";
echo "<td>".rand()."</td>";
echo "</td>";
echo "</tr>";
}
echo "</table>";
//mysql_close($con);
?>
Response will be:

how do i fill text box field with ajax

I have a combobox and i want to fill the State and Zip_code Field..its working but it fills each field State "NY11715" and Zip_code "NY11715"...i'm looking to fill State "NY" and Zip_code 11715...please help me resolve this
<select name="LookupCity" id="LookupCity" onchange="showZip(this.value)">
<option value="" <?php if (!(strcmp("", $_GET['City']))) {echo "selected=\"selected\"";} ?>>Select from menu</option>
<?php do { ?>
<option value="<?php echo $row_fmCity['City']?>"<?php if (!(strcmp($row_fmCity['City'], $_GET['City']))) {echo "selected=\"selected\"";} ?>><?php echo $row_fmCity['City']?></option>
<?php
} while ($row_fmCity = mysql_fetch_assoc($fmCity));
$rows = mysql_num_rows($fmCity);
if($rows > 0) {
mysql_data_seek($fmCity, 0);
$row_fmCity = mysql_fetch_assoc($fmCity); } ?> </select>
select</td>
</tr><tr valign="baseline">
<td nowrap="nowrap" align="right">State:</td>
<td><input type="text" name="State" id="State" placeholder="NY" value="<?php echo $_GET['State']; ?>" size="5"/>
<input type="text" name="Zip_Code" id="Zip_Code"placeholder="zip code" value="<?php echo $_GET['Zip']; ?>" size="10" /></td>
Ajax code
function showZip(str)
{
if (str=="")
{
document.getElementById("State").innerHTML="";
document.getElementById("Zip_Code").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("State").value=xmlhttp.responseText;
document.getElementById("Zip_Code").value=xmlhttp.responseText;
}
}
xmlhttp.open("GET","Getzip.php?q="+str,true);
xmlhttp.send();
}
PHP Code
<?php
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', 'root');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("Leadbook", $con);
$sql="SELECT * FROM Zip WHERE City = '".$q."'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$State = $row['State'];
$Zip_Code = $row['Zip Code'];
}
echo $State;
echo $Zip_Code;
mysql_close($con);
?>
1. change your php code, so that both city and zip code are comma seperated.
change this code:
echo $State;
echo $Zip_Code;
to this:
echo $State;
echo ",";
echo $Zip_Code;
2. than update your javascript, so that the return text is splitted into 2 parts and gets to its respected fields.
change this code:
document.getElementById("State").value=xmlhttp.responseText;
document.getElementById("Zip_Code").value=xmlhttp.responseText;
to this:
var string = xmlhttp.responseText;
var array = string.split(',');
document.getElementById("State").value=array[0];
document.getElementById("Zip_Code").value=array[1];
this should do what you requested.

form does not posting the data of filtered field?

i am fetching categories and their sub-categories from the database.
and filtering the sub-categories after selecting the category bu using dropdown.
after selecting when i submit the form, the value of the sub-category is 0, form does not posting the selected value.
<?php
if(isset($_POST) && $_POST['submit'] == "Add")
{
extract($_POST);
$scat_id = $regions['scat_id'];
echo $sqlpa = "INSERT INTO products(mcat_id, scat_id)VALUES('$mcat_id', '$scat_id')";
$resultpa = mysql_query($sqlpa);
}
?>
<script type="text/javascript">
function getregions(mcat_id) {
if (mcat_id=="") {
document.getElementById("region").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("region").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getregions.php?mcat_id="+mcat_id,true);
xmlhttp.send();
}
</script>
<form action="" method="post" name="p_add" id="p_add">
<table>
<tr>
<td>Select Category</td>
<td><select name="mcat_id" id="mcat_id" onchange="getregions(this.value);">
<option value="">Select</option>
<?php
if(!empty($resultm)) {
foreach($resultm as $rm) {
?>
<option value="<?php echo $rm['mcat_id']; ?>"><?php echo $rm['mcat_name'];?> (<?php echo $rm['mcat_id']; ?>)</option>
<?php
}
}
?>
</select>
</td>
</tr>
<tr>
<td>Select Sub-Category</td>
<td>
<div id="region">
<select name="scat_id" id="scat_id">
<option value="">Please Select</option>
</select>
</div>
</td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Add" /></td>
</tr>
</table>
</form>
-->this page is getregions.php where filtering is done:
<?php
include "../conn.php";
$mcat_id=$_GET['mcat_id'];
$sql = "SELECT * FROM sub_category WHERE mcat_id = '".$mcat_id."'";
$res = mysql_query($sql);
while($row = mysql_fetch_array($res)) {
$rec[] = $row ;
}
?>
<select name="scat_id" id="scat_id">
<option value="">Please Select</option>
<?php
foreach($rec as $regions) {
?>
<option value="<?php echo $regions['scat_id'];?>"><?php echo $regions['scat_name'];?></option>
<?php
}
?>
</select>
just before the insert query, i need to write
$scat_id = $_post['scat_id'];
this will get the posted value.

dropdown with php and ajax

For some time I am battling to solve this problem but I am not coming to any conclusion so thought to seek some help here.
The problem is that I am getting a blank dropdown instead I should get list of cities populated from the database. Database connection is fine but I am not getting anything in my dropdown.
This is what I am doing:
<?php
require 'includes/connect.php'; - database connection
$country=$_REQUEST['country']; - get from form (index.php)
$q = "SELECT city FROM city where countryid=".$country;
$result = $mysqli->query($q) or die(mysqli_error($mysqli));
if ($result) {
?>
<select name="city">
<option>Select City</option>
$id = 0;
<?php while ($row = $result->fetch_object()) {
$src = $row->city;
$id = $id + 1;
?>
<option value= <?php $id ?> > <?php $src ?></option>
<?php } ?>
</select>
<?php } ?>
ajax script is this:
<script>
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{mlhttp=new XMLHttpRequest();}
catch(e) {
try{ xmlhttp= new ActiveXObject("Microsoft.XMLHTTP"); }
catch(e){ try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCity(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
This is my form code:
<form method="post" action="" name="form1">
<table width="60%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="150">Country</td>
<td width="150"><select name="country" onChange="getCity('findcity.php?country='+this.value)">
<option value="">Select Country</option>
<option value="1">New Zealand</option>
<option value="2">Canada</option>
</select></td>
</tr>
<tr style="">
<td>City</td>
<td ><div id="citydiv"><select name="city">
<option>Select City</option>
</select></div></td>
</tr>
</table>
</form>
I think the problem is where you are outputting the <option> tags.
Try using this block of code between your <select> tags.
<option>Select City</option>
<?php
$id = 0;
while ($row = $result->fetch_object()) {
$src = $row->city;
$id = $id + 1;
?>
<option value="<?php echo htmlspecialchars($id,ENT_QUOTES) ?>"><?php echo htmlspecialchars($src) ?></option>
<?php } ?>
Edit: To clarify, you didn't have any echo statements before the $id and $src variables. I added htmlspecialchars() as a habit to produce properly escaped html.
A few things to try:
If you request findcity.php manually in your browser with a city you know exist in the database, will i return the correct HTML?
Try with FireBug or another javascript debugger, to set a breakpoint in the onreadystatechange function and see if the returned values are as expected. Set the breakpoint at the first line of the function.
<input name="acname" type="text" id="acname" value="" maxlength="9">
Account Name </p>
<select name="src">
<option value="number"> :::: Select ::::</option>
<option value="did">DID</option>
<option value="tfn">TFN</option>
</select>
<span id="errmsg"></span> DID/TFN </p>
<select name="did" onchange='OnChange(this.form1.did);' >
<option value=""> :::: Select ::::</option>
<? $qry1 = mysql_query("SELECT * FROM ".NUMBERS." where Flag='1'") or die(mysql_error()) ;
while($res1 = mysql_fetch_array($qry1)) { ?>
<option value="<?=$res1['Numbers'] ?>"><?=$res1["Numbers"]?></option>
<? } ?>
</select>
SOURCE

Categories