I've been trying to use AJAX and PHP to create a dynamically changed form where selecting an index on the drop down box automatically changes the type of input that is displayed on the form. I use a select box on the form that onchange() submits to the AJAX function. The function uses XML to call the PHP file. The the 2 types of inputs that I'm trying to switch between are a file upload and a drop down box that is populated by data that I have on a remote database. When I select the option for the file upload input, it displays fine, but the PHP database drop down box does not display when I select that option.
Can anybody tell me what I'm doing wrong?
Here is the code I have right now:
File Name: test.php
<html>
<body>
<head>
<script>
function getInputs(str) {
var xmlhttp;
if (str == "") {
document.getElementById("display").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("display").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "grabtest.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<form action="">
<select id='RecipeSelect' onchange='getInputs(this.value)'>
<option selected value=''>Select</option>
<option value='N'>New file</option>
<option value='E'>Existing file</option>
</select>
<br>
<div id="display"></div>
<br>
</form>
</body>
</html>
File Name: grabtest.php
<?php
$q=$_POST["q"];
//connect to database on server
$con=mysqli_connect("connection","loginname","password","DBname");
//if there was an error in connecting to the database, display the error
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if ($q=""){
echo "";
}
elseif ($q="N"){
echo "Select file to upload: <input type='file' name='newfile'>";
}
elseif ($q="E"){
//creates a dropdown box where you can select desired field
$list = mysqli_query($con, "select * from TableName");
echo 'Recipes: <select name = "name">';
while ($row = mysqli_fetch_array($list))
{
echo '<option value = "' . $row["ID"] . '">' . $row["Recipes"] . '</option>';
}
echo '</select><br>';
echo '<input type="submit" value="Submit">';
echo '</form>';
}
mysqli_close($con);
?>
You are passing q in the query string and using POST. You need to either use GET or send q, in the send method of the XHR.
Related
this should be simple but I have lost my way
simple form on HTML page - select Men, Women or Junior
then send that that value to a php page to perform SQL query and find all the Men, Women or Juniors using the variable "$trigen"
display the results on the HTML page using AJAX
if I set $trigen manually it works, but not when I choose the option in the form as set out in this code:--
my HTML:-
<!DOCTYPE html>
<html>
<div class="entry-content">
<form action="/getcustomer.php" method="POST">
<label for="trigen">Choose a gender:</label>
<select id="trigen" name="trigen">
<option value="Men">Men</option>
<option value="Women">Women</option>
<option value="Junior">Junior</option>
</select>
<button class="btn btn-primary text-center btn-block btn-flat" style="h2; margin: 20px; color:black; " name="trilookup" type="submit" onclick="showResults()"> Search</button>
</form>
</div>
<div id="results">Results go here if it works....</div>
<script>
function showResults(str) {
var xhttp;
if (str == "") {
document.getElementById("results").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("results").innerHTML = this.responseText;
}
};
xhttp.open("GET", "getcustomer.php?q="+str, true);
xhttp.send();
}
</script>
then my php code in "getcustomer.php"
<?php
//connect to the database
$conn=mysqli_connect('localhost','wetsuder_user1','user123','wetsuder_finder');
if($conn){
}
else{
echo "Sorry there is a connection error".mysqli_connect_error();
}
$trigen=$_POST['trigen'];
//this is the search
$sql = "SELECT id, Gender, Wetsuit FROM wp_wetsuitdata WHERE Gender = '$trigen'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["Gender"]." ".$row["Wetsuit"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Your button is causing a form submission. Just add preventDefault() as the first line of your showResults function and it will prevent the form from submitting naturally. You're handling the form submission via ajax. Also you don't need to have an action or method on your <form tag for the same reason. Another way of preventing the form from submitting is like this: <form onsubmit="return false"
Also, change your function to find the value you want to send, since you're not actually passing that value through the function call str
function showResults() {
preventDefault(); // prevents form submission
// get the value
let str = document.getElementById('trigen').value;
// check to make sure it's there...
if (!str) return alert("Please select an option...");
var xhttp;
......
You're sending the data via GET (when you use the ?q=val on your URL, the data is being sent through GET. So, you can receive it in your PHP with this:
$trigen=$_GET['q'];
I am trying to setup a table on my site that is populated based on the users selection of from a drop down menu. The dropdown menu should make up the variables that will perform the SELECT statement.
To do this I have a HTML drop down and a AJAX function. This the function ...
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("loadhere").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("loadhere").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajaxtest.php?q="+str,true);
xmlhttp.send();
}
</script>
And this is the HTML
<form action="">
<select name="users" onchange="showUser(this.value)">
<option value="">Please choose</option>
<option value="1200">Courses</option>
<option value="">TEST</option>
<option value="">TEST</option>
<option value="">TEST</option>
</select>
</form>
<br>
<div id="loadhere"><b>Details will be listed here after selection.</b></div>
This then calls a php script
$q=$_GET["q"];
$sql="SELECT * FROM clntcoursetbl WHERE mbrid = '".$q."'";
$result = mysql_query($sql);
echo "<table id='box-table-b'>
<tr>
<th>Course</th>
<th>Start Date</th>
<th>Finish Date</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['course'] . "</td>";
echo "<td>" . $row['startdate'] . "</td>";
echo "<td>" . $row['finishdate'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
Currently I have a value of 1200 against the select option of 'course' , this is the client ID of the user and was just for testing to make sure everything works. Which it does.
Now , I would like to change it so that the value in the select is put into the SELECT statement to choose the table to search.
Something along the lines of "SELECT * FROM selected value WHERE mbrid = '".$q."'";
Is this possible ?
If so, how can I can I then also make the mbrid dynamic ? Can I pass a session variable into the function perhaps ??
As always , thanks for you help !
You can have an ajax call in the showUser() function which can go like this.
var url = "url of the file you want to get data from";
var e = document.getElementById("#<Your Select Items ID>");
var data = 'q='+e.options[e.selectedIndex].value;
$.ajax({
type: "post",
url: url,
data: data,
success: function(msg) {
}
});
Then you can use $_POST['q'] to get the value in your destination page.
Also try appending all your echo data to a variable and do an echo when you loop execution is complete.
I have a sample script in php and validation are done using javascript. I am generating a inputbox using ajax script on click of a button. When I click submit it checks whether all the boxes are filled or not.
I am validating the boxes using for loop. When the boxes are empty it correctly alerts and I am returning false for the same case. But the problem is when all the boxes are filled it doesn't not return any thing and the function stops working even when I m returning true for this condition.
My javascript code with function is shown below
function addInput(){
var xmlhttp;
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)
{
var result = xmlhttp.responseText;
var newElem = document.createElement ("div");
newElem.innerHTML = result;
newElem.id = "input";
var container = document.getElementById ("main");
container.appendChild (newElem);
}
}
xmlhttp.open("GET","insert.php",true);
xmlhttp.send();
}
var count = '<?php echo $_SESSION['z']; ?>'
function check(){
function validate()
{
for(var i=1; i<=count+10; i++)
{
if(document.getElementById("text"+i+"").value == "")
{
alert("Please Enter Start Date For Sales Promotion");
document.getElementById("text"+i+"").focus();
return 'false';
}
}
return 'abc';
}
var flag = validate();
if(flag != 'false')
{
alert("correct");
}
}
MY html code is shown below
<form method="post" action="save.php">
<div id="main">
<div id="input1">
Enter Name </br></br>
<input type="text" id="text1" />
<?php $_SESSION['z'] = 2; ?>
</div>
</div>
</br>
<input type="button" value="add another" onclick="addInput()" />
<input type="button" value="Submit" onclick="check()" />
</form>
<div id="display"></div>
my ajax code is shown below
<?php
session_start();
$q = $_SESSION['z'];
?>
Enter Name </br></br>
<input type="text" id="text<?php echo $q; ?>" />
<?php $q = $q + 1;
$_SESSION['z'] = $q;
?>
the problem is when all the fields are filled it doesn't return anything.
This may occur a lot, and according to the browser used, the click event and submit event will be call at the same time, it's not safe (for exemple, in IE if your submit button call another submit function, the form will be submitted twice...)
You should wire your check function to the onBeforeSubmit event of your form.
It is likely that you get an error when you try to retrieve an item which does not exist on the page.
if(document.getElementById("text"+i+"").value == "")
{
alert("Please Enter Start Date For Sales Promotion");
document.getElementById("text"+i+"").focus();
return 'false';
}
Here may be there are no items with ids like "text8", "text9", etc. In that case there will be null reference error when you try to get value of non exisisting element.
Try changing it like this:
var ele = document.getElementById("text"+i);
if(ele && ele.value == "")
{
alert("Please Enter Start Date For Sales Promotion");
document.getElementById("text"+i+"").focus();
return 'false';
}
This validates if ele is null or not before accessing the value of it.
I have a dynamic drop down box which calls another PHP page. I've got it to work just how I want it.
Below is the part of the form:
<tr>
<td>
<p> Select a delivery date </p>
</td>
<td>
<select name='listdate' onchange='showDelivery(this.value)'>
<option value=''>select delivery type:</option>
<option value='forwardorder'>Forward Order</option>
<option value='byreturn'>By Return</option>
</select>
<div id='txtHint'>
<b>Change to drop down box to display delivery date</b>
</div>
</td>
</tr>
The Ajax
function showDelivery(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","getDelivery.php?q="+str,true);
xmlhttp.send();
}
The php script
$q=$_GET["q"];
// And create a cid object
require_once $CID_INCLUDE_PATH . "/cid.php";
$cid = new CHCID();
if ($q == 'forwardorder')
{
echo"<td><select 'name'='deliveryDate'/> ";
$listCapacityDates = $cid->ListCapacity();
foreach($listCapacityDates as $x) {
echo "<option value='".$x."'>".$x."</option> </select>";
}
}
if ($q == 'byreturn')
{
echo"<div id='div1'>Enter By Return Date<input type='text''name='deliveryDate' />
</div>";
}
I know the problem, because the results from the Ajax drop downs are shown through the PHP pages when the form submits none of those values are submitted. But I'm not sure how I can even submit them? Any ideas?
echo"<td><select 'name'='deliveryDate'/> ";
should be :
echo "<td><select name='deliveryDate'/> ";
and
echo"<div id='div1'>Enter By Return Date<input type='text''name='deliveryDate' />
should be :
echo"<div id='div1'>Enter By Return Date<input type='text' name='deliveryDate' />
and:
if ($q == 'forwardorder')
{
echo"<td><select 'name'='deliveryDate'/> ";
$listCapacityDates = $cid->ListCapacity();
foreach($listCapacityDates as $x) {
echo "<option value='".$x."'>".$x."</option>";
}
echo "</select></td>";
}
</select> should be outside foreach
You seem to understand why it's not working, just not how to correct it, right?
When you return the data from your PHP page, it needs to be processed via the javascript.
Instead of returning,
echo "<option value='".$x."'>".$x."</option> </select>";
It should be possibly json.
{ val : key, val : key }
Then Javascript can insert it into the HTML DOM, then your form will recongnize the values when you submit the form.
As for the Javascript code, there are a few ways, jQuery has some plugins for handle it.
Otherwise I can dig around for some code, if someone doesn't beat me too it :)
Edit:
Off hand, I think this code should work.
It's untested, but hopefully will give more of an idea how to use it.
replace
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
with
var response = xmlhttp.responseText;
var select = document.getElementByName('listdate');
var option;
for(var i=0; i<response.length; i++)
{
option = document.createElement("OPTION");
option.text = response.key[i];
option.value = response.val[i];
select.options.add(option);
}
I got a simple AJAX demo code from internet which fills one select listbox dynamically with values from database. It contains a html file with AJAX code embedded in it and a PHP file.
The problem is this code works fine in IE, Chrome, FireFox4 but its not works in FireFox3. Please any one explain this and tell me the solution. The code is as follows for reference
The database schema for city table is as follows
id tinyint(4) primary key not null
city varchar(50)
countryid tinyint(4)
HTML File
<html>
<head>
<script type="text/javascript">
function getCity(strURL)
{
alert("inside getCity function");
//var req = getXMLHTTP(); // function to get xmlhttp object
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
//xmlhttp=new XMLHttpRequest();
req=new XMLHttpRequest();
}
else
{// code for IE6, IE5
//xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
req=new ActiveXObject("Microsoft.XMLHTTP");
}
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) { //data is retrieved from server
if (req.status == 200) { // which reprents ok status
document.getElementById('citydiv').innerHTML=req.responseText;
}
else
{
alert("There was a problem while using XMLHTTP:\n");
}
}
}
//alert(srtURL);
var sURL="findcity.php?country="+strURL;
req.open("GET", sURL, true); //open url using get method
req.send();
}
}
</script>
</head>
<body>
<form method="post" action="" name="form1">
Country : <select name="country" onChange="getCity(this.value)">
<option value="">Select Country</option>
<option value="1">india</option>
<option value="2">usa</option>
</select>
<br />City : <div id="citydiv">
<select name="select">
<option>Select City</option>
</select>
</div>
</form>
</body>
</html>
PHP file
<?
echo $_GET['country'];
echo "<br>";
$country=intval($_GET['country']);
echo $country;
echo "<br>";
$link = mysql_connect('localhost', 'root', 'mark'); //change the configuration if required
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('querytest'); //change this if required
$query="select city from city where countryid=$country";
echo "<br>";
echo $query;
echo "<br>";
$result=mysql_query($query);?>
<select name="city">
<option>Select City</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value><?=$row['city']?></option>
<? } ?>
</select>
Please guide me friends to make this code working in FireFox 3
Change
req.send();
to
req.send(null);