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..
Related
I have two drops downs on my page.
I have a drop directly taken from DB.
I have a drop totally depends on the selection from dropdown 1 and taken from db.
I have both of these drop-downs inside a modal. I am not sure how to insert the javascript variable to dropdown 2.
Here is my code:
Dropdown 1:
<select class="selectpicker form-control mt-2" id="schoolname" name="schoolname" data-width="" title="School" onChange=reload(this.form)>
<?php
$prod_query = "SELECT * FROM my_school_class";
$prodresult = mysqli_query($DBconnect, $prod_query);
while($r = mysqli_fetch_array($prodresult))
{
if (!empty($schoolName) && $schoolName == $r['schoolName'])
{
$selected = 'selected="selected"';
}
else
{
$selected = '';
}
echo "<option ".$selected." value=".$r['schoolName'].">".$r['schoolName']."</option>";
} ?>
</select>
Dropdown 2:
<select class="selectpicker form-control mt-2" id="classname" name="classname" data-width="" title="class">
<?php
$prod_query = "SELECT * FROM my_class WHERE school="JAVASCRIPT VARIABLE SHOULD COME HERE";
$prodresult = mysqli_query($DBconnect, $prod_query);
while($r = mysqli_fetch_array($prodresult))
{
echo "<option ".$selected." value=".$r['className'].">".$r['className']."</option>";
} ?>
</select>
Javascript writing correctly to console:
<script language=JavaScript>
function reload(form)
{
var val=form.schoolname.options[form.schoolname.options.selectedIndex].value;
console.log (val);
}
The above variable prints the selection correctly on the console in chrome.
And I have all these inside a modal. Let me know how to fix this?
Thanks!
use this using JQUERY
index.html
$(document).on('change','#schoolname',function(){
var schoolname = $('#schoolname').val();
$('#classname').empty();
$('#classname').append('<option value="" disabled selected>Choose your option</option>');
$.ajax({
url: 'GetClassname.php',
type: 'POST',
data: {schoolname : schoolname },
success: function(data) {
$('#classname').append(data);
}
});
});
GetClassname.php
<?php
include('../config.php');
$schoolname = $_POST['schoolname'];
$prod_query = "SELECT * FROM my_class WHERE school='$schoolName'";
$prodresult = mysqli_query($DBconnect, $prod_query);
while($r = mysqli_fetch_array($prodresult)) {
echo "<option ".$selected." value=".$r['className'].">".$r['className']."</option>";
}
?>
Call ajax like this (pure vanilla js)
function reload(form)
{
const id = form.schoolname.options[form.schoolname.options.selectedIndex].value
var xhr = new XMLHttpRequest();
xhr.open('POST', '/fetch_second.php/');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
xhr.onload = function() {
if (xhr.status === 200) {
const data = xhr.responseText
let elem = document.querySelector( 'css-selector (#container id)')
elem.appendChild(responseText)
}
else if (xhr.status !== 200) {
console.log('Request failed. Returned status of ' + xhr.status);
}
}
xhr.send(encodeURI('id=' + id))
}
and change
this css-selector (#container id) to your container id or className from your modal
And in your fetch_second.php
$schoolName = $_POST['id'];
$prod_query = "SELECT * FROM my_class WHERE school='$schoolName'";
$prodresult = mysqli_query($DBconnect, $prod_query);
while($r = mysqli_fetch_array($prodresult)) {
echo "<option value=".$r['className'].">".$r['className']."</option>";
}
I have the following js script that triggers onChange of the select box below.
It then retrieves data from a table and returns some input fields populated with the data (using PHP code below). Then saves the data.
This part works fine.
However, if I run the script again, and it populates the selected option from DB and shows as a selected option, but it does not display the populated input fields returned from the PHP code/DB query since I am not triggering the onChange again.
I tried to add 'window.onload = showAgentOne;' under the JS for the onChange function, assuming it would see the value in (str) from the select box, but I am probably missing something as it does not work.
New to JS - I hope this makes sense.
JS:
function showAgentOne(str) {
if (str == "") {
document.getElementById("agent1").innerHTML = "";
return;
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("agent1").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "user_agent1.php?q=" + str, true);
xmlhttp.send();
}
window.onload = showAgentOne; // trigger function on pageload - not working
HTML:
<select name="narid" onchange="showAgentOne(this.value)" class="form-control">
<option selected="selected" disabled value="">select agent</option>
<?php
$sql = "select last_name, first_name, active, nrds_id from ft_form_2 ORDER BY last_name";
$sql_result = mysqli_query($mysqli,$sql);
while ($row = mysqli_fetch_array($sql_result)) }?>
<option value="<?php echo $row[" nrds_id "]; ?>" <?php if($narid_agent1==$ row[ "nrds_id"]) { echo ' selected '; } ?> >
<?php echo strtoupper($row["last_name"]) . ' > ' . $row["first_name"] . ' ' . $row["last_name"] . ' ['.$active.']'; ?>
</option>
<? } ?>
</select>
<div id="agent1"></div>
PHP (user_agent1.php) ------------------------- $q=$_GET["q"]; $sql="SELECT pay_to_name,nrds_id FROM ft_form_2 WHERE nrds_id = $q"; $result = mysqli_query($mysqli,$sql); while($row = mysqli_fetch_array($result)) { ?>
<input type="text" name="narid_agent1" value="<?php echo $row['nrds_id']; ?>">
<input type="text" name="pay2_agent1" value="<?php echo $row['pay_to_name']; ?>">
<?php } ?>
'window.onload = showAgentOne;' is a good try but it is expecting a str param, otherwise it returns and do nothing. That's why nothing happens.
You will have to try something like
window.onload = function (event) {
let str = 'ADD_YOUR_VALUE_HERE';
showAgentOne(str);
}
But I can't help you with what str should be.
My index.php:
<html>
<head>
</head>
<body>
<form name="form1" action="submit.php" method='POST'>
<select id="dropdown1" name="country" onchange="window.getStates()">
<option> Select Country</option>
<option value="1">Pakistan</option>
<option value="2">India</option>
<option value="3">USA</option>
<option value="4">UK</option>
</select>
<input type="text" id="area" style="display: none;" size="16" placeholder=" Enter value"></input>
<input type="submit" id="submit" style="display: none" name="submit" value="submit" onclick="submit()">
</form>
<script type="text/javascript">
function show() {
{ document.getElementById('area').style.display = 'inline-block';
document.getElementById('submit').style.display = 'inline-block';}
}
function getStates()
{
var xmlhttp;
try{
xmlhttp = new XMLHttpRequest;
}catch(e)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp)
{
var form = document['form1'];
var country = form['country'].value;
xmlhttp.open("GET","http://localhost/getStates.php?country="+country,true);
xmlhttp.onreadystatechange = function()
{
if(this.readyState == 4)
{
var s = document.createElement("select");
s.onchange=show;
s.id="dropdown2";
s.name="state";
s.innerHTML = this.responseText;
if(form['state'])
{
form.replaceChild(s, form['state']);
}
else
form.insertBefore(s,form['submit']);
}
}
xmlhttp.send(null);
}
}
function submit() {
var table = document.getElementById("dropdown1").value;
var parameter = document.getElementById("dropdown2").value;
var value = document.getElementById("area").value;
$.ajaxSetup({
url: "http://localhost/database.php",
type: "POST",
});
$.ajax({
data: 'table='+table+'¶meter='+parameter+'&value='+value+,
success: function (msg) {
alert (msg);},
error: function (XMLHttpRequest, textStatus, errorThrown)
{
alert('Error submitting request.');
}
});
}
</script>
</body>
</html>
my getStates.php code:
<?php
$states=array(
"1" => array("NWFP","Sindh","Bala","Punjab","Select"),
"2" => array("gujrat","goa","U.P.","Select"),
"3" => array("bgjs","hhtrs","Bhtrshts","Utah","Select"),
"4" => array("England","Scotland","Bahwgla","Punthwthjab","Select")
);
if(isset($_GET['country']))
{
$c = $_GET['country'];
if(isset($states[$c]))
{
for($i = count($states[$c]) -1; $i>=0; $i--)
{
echo "<option value='".$states[$c][$i]."'>".$states[$c][$i]."</option>";
}
}
}
?>
database.php code:
<?php
header('Content-type: text/html; charset=ISO-8859-1');
try
{
if(isset($_POST['table']) && isset($_POST['parameter']) && isset($_POST['value'])){
$table = ($_POST['table']);
$parameter = ($_POST['parameter']);
$value = ($_POST['value']);
$db = mysql_connect(localhost, root, "");
$select = mysql_select_db(records, $db);
$query="INSERT INTO $_POST['table'] (Parameter,Value)
VALUES ('".$_POST['parameter']."','".$_POST['value']."');";
}
mysql_query($query,$connection);}
catch(Exception $e)
{
echo 'Erreur : '.$e->getMessage().'<br />';
echo 'N° : '.$e->getCode();
}
?>
Also, the submit button has a onclick() and an action tag. When the submit button is clicked, i want the submit() function to be executed, so what should i do for that? When i press submit, the parameter and value values are not being inputted into my database called records with 4 tables named 1,2,3 and 4. Thanks!
I think there is some probllem with this line:
$query="INSERT INTO $_POST['table'] (Parameter,Value)
VALUES ('".$_POST['parameter']."','".$_POST['value']."');";
You have commented out submit() and Maybe that's the problem...
The form submission overtakes the onclick call.
You should check this out:
http://www.codediesel.com/javascript/prevent-form-submissions-with-javascript-disabled/
<script>
$(function(){
$("form").submit(function(e) {
e.preventDefault();
});
});
</script>
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
<html>
<head>
<script>
function showUser()
{
//var s=document.getElementById('uni'); //this also not working
//var str=s.options[s.selectedIndex].value;
var str=document.form.formList.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>
</head>
<body>
<form name="form">
<select name="formList" id="uni" >
<option value="">Select a person:</option>
<option value="1">University 1</option>
<option value="2">University 2</option>
<option value="3">University 3</option>
<option value="4">University 4</option>
</select>
<input type="submit" value="Search" onsubmit="showUser()" >
</form>
<br>
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
Want to get value from Select Tag by Submit button.....
By using javascript and then send to AJAX to forward that data to userget.php file to fetch data from SQL DATABASE and
then show to on web.
please i'm stuck here anybody tell me what i'm doing wrong... ???
I want to to store value from drop down list by submit button...
/////////////////Server side code///////////////////////////
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','','degree');
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="SELECT * FROM uni WHERE id = '".$q."'";
$result = mysqli_query($con,$sql);
echo "<table border='1'>
<tr>
<th>Id</th>
<th>Univeristy</th>
<th>Degree</th>
<th>Location</th>
<th>Rank</th>
<th>Fees</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['Id'] . "</td>";
echo "<td>" . $row['Univeristy'] . "</td>";
echo "<td>" . $row['Degree'] . "</td>";
echo "<td>" . $row['Location'] . "</td>";
echo "<td>" . $row['Rank'] . "</td>";
echo "<td>" . $row['Fees'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
If you use JQuery, you may do something like:
$(document).ready(function(){
$('#searchButton').click(function(){
if ($('#uni').val()) {
$.post(
'getuser.php',
{
q: $('#uni').val()
},
function(personInfo){
if (personInfo) {
$('#txtHint').text(personInfo)
}
}
);
} else {
alert('Please select an option first.');
}
});
});
Just change the input type in your form from submit to button and add the id as "searchButton".
In your server side script, use POST instead of GET:
$q = intval($_POST['q']);
First of all more reliable method of getting xmlhttp
function getXmlHttp(){
var xmlhttp;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
Second is that correct form to do what you want is that:
<form name="form" onsubmit="showUser(); return false;">
<select name="formList" id="uni" >
<option value="">Select a person:</option>
<option value="1">University 1</option>
<option value="2">University 2</option>
<option value="3">University 3</option>
<option value="4">University 4</option>
</select>
<input type="submit" value="Search" />
</form>
And showUser function like that:
function showUser()
{
//var s=document.getElementById('uni'); //this also not working
//var str=s.options[s.selectedIndex].value;
var str=document.form.formList.value;
if (str=="")
{
document.getElementById("txtHint").innerHTML = "";
return;
}
var xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4)
{
if(xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
} else {
// add error handler here
}
}
};
xmlhttp.open("GET","/getuser.php?q="+str,true);
xmlhttp.send();
}
No need to bother with submit at all. This will do the trick :)
<input type="button" onclick="showUser();" value="Search" />