Complete Dynamic drop down in PHP MySQL & AJAX with mysql Insert query works perfectly.
Code to insert date to MySQL table
<?php
require('../conn/include.php');
require('quick.php');
$query="SELECT * FROM category";
$result=mysql_query($query);
$project=$_POST['project'];
$alttext=$_POST['alttext'];
$relation=$_POST['state'];;
if(isset($_FILES['image'])) {
$errors=array();
$allowed_ext=array('jpg','png','jpeg','JPG');
$filename=$_FILES['image']['name'];
$name=stripslashes($filename);
$type=strtolower(end(explode('.',$filename)));
$size=$_FILES['image']['size'];
$file_tmp=$_FILES['image']['tmp_name'];
if(in_array($type,$allowed_ext) ===false) {
$errors[]= "<span class=\"notification n-error\">Extenstion Not Allowed</span>";
}
if($size > 1048576) {
$errors[]= "<span class=\"notification n-error\">File must be less then 2mb</span>";
}if(file_exists('../../images/a/gallery/'.$filename)) {
$errors[]= "<span class=\"notification n-error\">File $filname Already Exists in directory</span>";
}if(empty($errors)) {
if(move_uploaded_file($file_tmp, '../../images/a/gallery/'.$filename)) {
$insert="Insert into `my`.gallery(name,alttext,project,relation)VALUE('$name','$alttext','$project','$relation')";
//echo $insert;
$que=mysql_query($insert);
echo "<span class=\"notification n-success\">File $filname Uploaded Sucessfully</span>";
header('Refresh:3; url:gallery.php');
}
}else {
foreach($errors as $error) {
echo $error,'<br/>';
}
}
}
?>
AJAX Code
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=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 getState(cate_id) {
var strURL="findsect.php?country="+cate_id;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("Problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Code for Second Drop Down or findsec.php
<?php
$country=$_GET['country'];
$con = mysql_connect('localhost', 'root', '');
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('my');
$query="SELECT * FROM gallery_section WHERE related='$country'";
$result=mysql_query($query);
?>
<select name="state" onchange="getCity(<?php echo $country?>,this.value)">
<option>Select State</option>
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['title']?>"><?php echo $row['title']?></option>
<?php } ?>
</select>
Thanks to Nick Wilde who helped me.
I'm presuming you mean when the value of the option for the second drop down is multiple words. If that is the case the problem is you are missing quotes; use this instead:
<?php while ($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['title']?>"><?php echo $row['title']?></option>
<?php } ?>
</select>
as the last three lines of your findsec.php
Related
Being new to PHP and ajax XmlHttpRequest calls altogether, I am struggling to figure out what is wrong with my code. Gone through the documentation but it seems I'm struggling to put the db row names into an array. I ideally want to asynchronously display an innerHTML below the input to indicate whether the item is in db or not. Right now it is showing 'undefined' as seen below until I type the last item in the db. it's only responding to the last item in the db meaning there's probably an issue with my loop. Any help is welcome.
index.php
<?php
include 'db.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<link href="css/main.css" rel="stylesheet">
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script src="js/todo.js" type="text/javascript"></script>
<script>
</script>
</head>
<body onload="process()">
<div class="list">
<h1 class="header">My To Do</h1>
<form>
<ul class="items">
<?php
$sql = "SELECT * FROM items ORDER BY items.id ASC";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<li><input type='checkbox' /><label>";
echo $row['name'];
echo "</label></li><br>";
}
} else {
echo "There are no to-dos!";
}
echo "<br/><br/>";
echo "<li><input type='checkbox' /><label>Mark all as completed</label></li>";
?>
</ul><br />
</form>
</div>
<div class="list">
<form class="item-add" method="post">
<input type="text" id="name" name="name" placeholder="Enter new item" class="input" autocomplete="off" required>
<input name="myBtn" type="submit" value="Add Item">
<div id="status"></div>
</form>
</div>
</body>
item.php
<?php
include 'db.php';
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$sql = "SELECT * FROM items ORDER BY items.id ASC";
$result = mysqli_query($conn, $sql);
$itemArray = array();
$rowNum = mysqli_num_rows($result);
//is this the correct way to add db items to an array?
if($rowNum > 0){
while ($row = mysqli_fetch_assoc($result)){
for ($x = 0; $x <= $rowNum; $x++) {
$itemArray[$x] = $row['name'];
}
}
} else {
echo "There are no to-dos!";
}
$entry = $_GET['name'];
if(in_array($entry, $itemArray))
echo 'Item ' .$entry. ' already exists! Please enter a new item...';
elseif ($name == '')
echo "Please enter an item...";
else {
//code for insertion
echo "Successfully Inserted";
}
echo '</response>';
?>
item.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject() {
var xmlHttp;
if(window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch(e) {
xmlHttp = false;
}
}
if(!xmlHttp) {
alert("cant create that object hoss");
} else {
return xmlHttp;
}
}
function process() {
if (xmlHttp.readyState==0 || xmlHttp.readyState==4) {
name = encodeURIComponent(document.getElementById('name').value);
xmlHttp.open("GET", "item.php?name="+name, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
} else {
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4) {
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
console.log(xmlResponse.documentElement);
message = xmlDocumentElement.firstChild.data;
document.getElementById('status').innerHTML =
'<span style="color:blue">' + message + '</span>';
setTimeout('process()', 1000);
} else {
alert('Something went wrong!');
}
}
}
$name is not defined in your PHP file , Shouldnt it be $entry that you are checking in the elseif condition below
$entry = $_GET['name'];
if(in_array($entry, $itemArray))
echo 'Item ' .$entry. ' already exists! Please enter a new item...';
elseif ($entry == '')
echo "Please enter an item...";
else {
//code for insertion
echo "Successfully Inserted";
}
also the correct way to assign a DB column to an array should be like below .
if($rowNum > 0){
while ($row = mysqli_fetch_assoc($result)){
$itemArray[] = $row['name'];
}
} else {
echo "There are no to-dos!";
}
I display a table on the website after a select option (I use ajax) and get the datas from the database. What I want to do is to insert a checkbox in my table and when it is checked delete the row in the database. I don't want to use a submit button but only the checkbox to delete it.
I'm not really good with ajax and JavaScript. This is the code:
The select :
<p>
<label for="client">Veuillez choisir le fournisseur :</label><br />
<select name="client" id="client" onchange="showUser(this.value)">
<?php
// echo '<option value=""/></option>';
while ($donnees = $reponse->fetch())
{
echo '<option value='.$donnees['refCustomer'].'>'.$donnees['legalCompanyName'].' </option>';
//$value = $donnees['refCustomer'];
}
$reponse->closeCursor();
?>
</select>
</p>
The script :
<script>
function showUser(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","getTableBuffer.php?q="+str,true);
xmlhttp.send();
}
}
</script>
getTableBuffer.php :
<?php
$q = intval($_GET['q']);
try
{
$bdd = new PDO());
}
catch (Exception $e)
{
die('Erreur : ' . $e->getMessage());
}
$reponse = $bdd->query('select * from vendor_'.$q.'_offers_ncli_amendments_buffer');
echo '<table class="imagetable">';
echo '<tr>';
echo '<th>code</th>';
echo '<th>dateAdded</th>';
echo '<th>effectiveDate</th>';
echo '<th>price</th>';
echo '<th>type</th>';
echo '<th>destination</th>';
echo '</tr>';
while ($donnees = $reponse->fetch())
{
echo '<tr>';
echo '<td><input type="checkbox" name="code" id="code" value="'.$donnees['code'].'"/>'.$donnees['code'].'</td>';
echo '<td>'.$donnees['dateAdded'].'</td>';
echo '<td>'.$donnees['effectiveDate'].'</td>';
echo '<td>'.$donnees['price'].'</td>';
echo '<td>'.$donnees['type'].'</td>';
echo '<td>'.$donnees['destination'].'</td>';
echo "</tr>";
}
echo "</table>";
echo "</br>";
echo "</br>";
$reponse->closeCursor();
?>
Add event onclick to your checkbox :
echo '<td><input onclick="remove(this);" type="checkbox" name="code" id="code" ....';
create function remove() in you javascript, that send the $donnees['code'] to a remove.php to delete it from DB :
function remove(e)
{
if (e.target.checked)
{
....
xmlhttp.open("GET","remove.php?code="+e.target.value,true);
xmlhttp.send();
}
}
Create remove.php that get the code and delete from DB :
<?php
if(isset($_GET['code'])){
//Query to remove from DB where code = $_GET['code']
}
?>
Hope this will help.
I'm developing a website which allow the user to do query on a public database and I would like to allow the user to see the query he has done during the current session and delete one of them he wants to.
here is the code creating $_SESSION['history']:
$_SESSION['history'][] = array(
'Database' => $_SESSION['db'],
'Choice' => $_SESSION['radio'],
'Query' => $_SESSION['query'],
'Résult' => ($asResults),
'Date' => date("d-m-Y"),
'Hour' => date("H:i:s")
);
here is the code displaying the array of the $_SESSION['history']:
<?php
function displayHistory($arQueryArray)
{
if (isset($_SESSION['history']))
{
echo '<table id="history" class="display">';
$iQueryNumber = 0;
echo '<thead><tr>';
echo '<th>n°</th>';
foreach (array_keys($_SESSION['history'][0]) as $field)
{
if ($field != 'Résult' and $field != 'Choice')
{
echo '<th>', $field, '</th>';
}
}
echo '<th></th><th></th>';
echo '</tr></thead>';
echo '<tbody>';
foreach ($_SESSION['history'] as $query)
{
echo '<tr>';
echo '<td>', ($iQueryNumber + 1), '</td>';
foreach ($query as $field => $value)
{
if ($field != 'Résult' and $field != 'Choice' and $field != 'Requête')
{
echo '<td>', $value, '</td>';
}
else if ($field == 'Query')
{
echo '<td>' . $arQueryArray[$query['Choice']] . " " . $query['Query'] . '</td>';
}
}
?>
<td>
<input type="button" class="del_btn" value="X" title="Delete this query" onclick="delQueryInHistory(<?php echo $iQueryNumber; ?>, this);"/>
</td>
<?php
echo '</tr>';
$iQueryNumber += 1;
}
echo '</tbody></table>';
}
else
{
echo "<p>No query</p>";
}
}
?>
Here is the javascript:
var XHR = null;
function getXMLHTTP()
{
var xhr = null;
if(window.XMLHttpRequest)
{ // Firefox
xhr = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{ // Internet Explorer
try
{
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e1)
{
xhr = null;
}
}
}
else
{ // XMLHttpRequest not supported
alert("YOur browser doesn't support XMLHTTPRequest...");
}
return xhr;
}
//Query suppression function
function delQueryInHistory(queryId, self)
{
XHR = getXMLHTTP();
XHR.open("GET", "controleur/delQueryInHistory.php?queryId=" + queryId, true);
XHR.onreadystatechange = function()
{
if (XHR.readyState == 4)
{
self.parentNode.parentNode.parentNode.removeChild(self.parentNode.parentNode);
}
}
XHR.send();
}
Here is the php called
<?php
session_start();
if(empty($_GET['queryId']) or !is_numeric($_GET['queryId']) or !isset($_GET['queryId']))
{
exit;
}
else
{
unset($_SESSION['history'][intval($_GET['queryId'])]);
}
?>
The problem is that it simply doesn't run and i don't understand why since i have not any error raised! Even if i use a corrupted php file... I have already verified that the path to the php file is OK!
Sorry for my English, and thanks..
** Last UPDATE:** Sorry, I've forgotten to say what specially didn't run: The row is correctly removed but the $_SESSION['history'][queryId] is not removed! But the XmlHttp object has been created! Thanks.
I've found how to fix the issue, maybe it could help
<?php
session_start();
if(empty($_GET['queryId']) or !is_numeric($_GET['queryId']) or !isset($_GET['queryId']))
{
exit;
}
else
{
unset($_SESSION['history'][$_GET['queryId']]);
$_SESSION['history'] = array_values($_SESSION['history']);
}
?>
the unset() function doesn't normalize integer indexes and it broke my code during the display!
I would like to display one column of data, [pin], based on the [plan] and [order_id] values. plan=9 and order_id=0. Would like to load data without reloading page, using ajax.
Here is my HTML/Script:
<script>
function showPins(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","getPins.php?q="+str,true);
xmlhttp.send();
}
}
</script>
HTML:
<div align="center">
<h3>View PIN's</h3>
<form>
<select name="users" onchange="showPins(this.value)">
<option value="">Select Plan Type:</option>
<option value="1">Plan1</option>
<option value="2">Plan2</option>
<option value="3">Plan3</option>
</select>
</form>
<br/>
<div id="txtHint"></div>
</div>
This is my PHP file (getPins.php):
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('myHost','myUsername','myPw','my_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"my_db");
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
$result = mysqli_query($con,$sql);
echo "<table>
<tr>
<th>PIN's</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['pin'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
This is based off the tutorial shown here: http://www.w3schools.com/php/php_ajax_database.asp
Trying to make it work for showing the correct pins for plan type chosen.
your query would be wrong read manual where
$sql="SELECT * FROM attPins WHERE (order_id=0, plan=9 and id = '".$q."')";
It would be
WHERE (order_id=0 and plan=9 and id = '".$q."')
Or
WHERE (order_id=0 OR plan=9 and id = '".$q."')
according to your requirment
I am using following script to dynamically add to html.
<script type="text/javascript">
$(document).ready(function ()
{
$('<div/>',
{
'class' : 'extraPerson', html: GetHtml()
}).appendTo('#container');
$('#addRow').click(function ()
{
$('<div/>',
{
'class' : 'extraPerson', html: GetHtml()
}).hide().appendTo('#container').slideDown('slow');
});
})
function GetHtml()
{
var len = $('.extraPerson').length;
var $html = $('.extraPersonTemplate').clone();
$html.find('[name=family_member_name]')[0].name="family_member_name" + len;
$html.find('[name=gender]')[0].name="gender" + len;
$html.find('[name=age]')[0].name="age" + len;
$html.find('[name=fdegrees]')[0].name="fdegrees" + len;
$html.find('[name=fcourse]')[0].name="fcourse" + len;
$html.find('[name=blood_group]')[0].name="blood_group" + len;
$html.find('[name=cell_no]')[0].name="cell_no" + len;
return $html.html();
}
</script>
Now i'm calling AJAX method on onChange event of <select> having id="fdegrees". i am receiving the proper AJAX response but not able to add to the HTML. The code for it is as follows.
<div class="extraPersonTemplate">
<div class="controls controls-row">
<select name="fdegrees" id="fdegrees" onChange="getDegree1('familyfinddegree.php?fdegrees='+this.value)">
<option value="">Select Degree</option>
<option value="1">Bachlor</option>
<option value="2">Master</option>
</select>
<div style="float:left" id="courses1">
<select name="fcourse">
<option>Select Courses</option>
</select>
</div>
</div>
</div>
The Javascript for AJAX functionality.
<script>
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=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 getDegree1(strURL) {
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('courses1').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
// alert(strURL);
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
The PHP file gives AJAX response is as follows:
<?php
$degrees=$_REQUEST['fdegrees'];
$link = mysql_connect('localhost', 'root', ''); //changet the configuration in required
if (!$link)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('gujarati_mandal');
$query="select course from courses where degree_id=$degrees";
$result=mysql_query($query);
$i=0;
?>
<select name="fcourse<?php echo $i?>">
<option>Select Course</option>
<?php while($row=mysql_fetch_array($result)) { ?>
<option value="<?php echo $row['course']?>"><?php echo $row['course']?></option>
<?php } ?>
</select>
change this code
The PHP file gives AJAX response is as follows:
<?php
$str="";
$str. = "
<select name='fcourse".$i.">
<option>Select Course</option>";
while($row=mysql_fetch_array($result))
{
$str. = "
<option value=".$row['course'].">".$row['course']."</option>";
}
$str. = "
</select>";
echo $str;
?>
this echo result will give u ur desirred O/P and u can append to it DIV by using innerHTML..