Posting form data to mysql database with ajax and php - javascript

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+'&parameter='+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>

Related

Prevent echo line from AJAX response

I want to prevent an echo from an AJAX response. I have 2 buttons and I need to enable and disable them using JS by AJAX responses. The JS code to enable/disable the HTML elements has been already written inside the PHP if condition of the AJAX URL Page. From AJAX I can display the results on <span id="dupmsg"></span>.
The result will be "Already Exists" and "Not Exist". I only want to display the message and enable/disable the buttons based on the condition. Here it's not working:
Index Page in php:
<h2>Enabling and Disabling text field using JavaScript</h2>
<form id="registration-form">
Enter your name: <input type="text" id="name">
</form>
<button onclick="disable()">Disable the text field</button>
<button onclick="enable()">Enable the text field</button>
<p>Ajax Response is: <span id="dupmsg"></span></p>
<script>
function check_dup()
{
var barcode=$("#memb_barcode").val();
$.ajax({
type: 'POST',
url: "ajax_attendance.php",
data: {
barcode: barcode
},
success: function(msg)
{
//alert(msg); // your message will come here.
$('#dupmsg')
.css('color', 'red')
.html(msg)
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
})
}
</script>
Ajax URL Page:
<?php
$reg_no = mysqli_real_escape_string($con, $_POST['reg_no']);
$barcode = mysqli_real_escape_string($con, $_POST['barcode']);
$sql = "SELECT id from tblstudent where reg_no = '$reg_no' && barcode like '$barcode' ";
$query = mysqli_query($con, $sql);
$ecount = mysqli_num_rows($query);
if($ecount!=0)
{
printf("Already Exists");
echo'
<script>
function disable() {
document.getElementById("name").disabled = true;
}
</script> ';
}
else
{
printf("Not Exists");
echo'
<script>
function enable() {
document.getElementById("name").disabled = false;
}
</script> ';
}
?>
The problem is that the JS written inside the PHP echo is reflecting back to span id="dupmsg" with AJAX response. I don't want to bring it in AJAX response. Please help.
<h2>Enabling and Disabling text field using JavaScript</h2>
<form id="registration-form">
Enter your name: <input type="text" id="name">
</form>
<button id="disable" onclick="disable()">Disable the text field</button>
<button id="enable" onclick="enable()">Enable the text field</button>
<p>Ajax Response is: <span id="dupmsg"></span></p>
<script>
function check_dup()
{
var barcode=$("#memb_barcode").val();
$.ajax({
type: 'POST',
url: "ajax_attendance.php",
data: {
barcode: barcode
},
success: function(msg)
{
if(msg=='true'){
document.getElementById("name").disabled = true;
$("#disable").attr("disabled", true); // write the id of the button u want to hide
$('#dupmsg')
.css('color', 'red')
.html("Already Exists")
}
else if(msg=='false')
{
document.getElementById("name").disabled = false;
$("#enable").attr("disabled", false); // write the id of the button u want to hide
$('#dupmsg')
.css('color', 'red')
.html("Not Exists")
}
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
})
}
function enable() {
document.getElementById("name").disabled = false;
}
function disable() {
document.getElementById("name").disabled = true;
}
</script>
ajax_attendance.php
<?php
$reg_no = mysqli_real_escape_string($con, $_POST['reg_no']);
$barcode = mysqli_real_escape_string($con, $_POST['barcode']);
$sql = "SELECT id from tblstudent where reg_no = '$reg_no' && barcode like '$barcode' ";
$query = mysqli_query($con, $sql);
$ecount = mysqli_num_rows($query);
if($ecount!=0)
{
return true;
}
else
{
return false;
}
?>

How to prevent from submitting upload multiple times on server side when using ajax and php

i am using this code for uploading multiple files .here, upload and select button become disabled when uploading is in progress but this works only on client side user can easily modify the code and remove its disable property so how can i do this on server side so the user will not be able to submit the form many times by clicking upload button after disabling it.
Thanku for any help!
index.php
<!DOCTYPE html>
<html>
<head>
<title>Multiple File Upload using Ajax</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
</head>
<body>
<div>
<form action="action.php" method="post" enctype="multipart/form- data" id="multiple-upload-form">
<input type="button" id="select-file-btn" value="Select Files" onclick="document.getElementById('files').click(); return false;" />
<input type="submit" id="file-upload-btn" name="file_upload_btn" value="Upload">
<input type="file" id="files" name="files[]" multiple="" style="visibility: hidden;">
<br><br>
<div class="file-bar">
<span class="file-bar-fill" id="file-bar-fill-id"><span class="file-bar-fill-text" id="file-bar-fill-text-id"></span></span>
</div>
<script type="text/javascript">
var app = app || {};
(function(o){
"use strict";
var ajax, getFormData, setProgress;
ajax = function(data){
var xmlhttp = new XMLHttpRequest(), uploaded;
xmlhttp.addEventListener('readystatechange', function(){
if(this.readyState==4){
if(this.status==200){
uploaded = JSON.parse(this.response);
if(typeof o.options.finished==='function'){
o.options.finished(uploaded);
}
} else {
if(typeof o.options.error === 'function'){
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener("progress", function(event){
var percent;
if(event.lengthComputable===true){
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
if(o.options.progressBar!==undefined){
o.options.progressBar.style.width=0;
}
if(o.options.progressText!==undefined){
o.options.progressText.innerText=0;
}
xmlhttp.open("post", o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source){
var data = new FormData(), i;
if(source.length<=0)
{
return false;
}
else
{
for(i=0;i<source.length; i++){
data.append('files[]', source[i]);
}
return data;
}
};
setProgress = function(value){
if(o.options.progressBar!==undefined){
o.options.progressBar.style.width = value? value+"%":0;
}
if(o.options.progressText!==undefined){
o.options.progressText.innerText=value?value+"%":0;
}
};
o.uploader = function(options){
o.options = options;
if(o.options.files !== undefined){
var imageFormDataValue = getFormData(o.options.files.files);
if(imageFormDataValue===false)
{
alert("No Files Selected");
document.getElementById("file-upload-btn").disabled = false;
document.getElementById("select-file-btn").disabled = false;
}
else
{
ajax(imageFormDataValue);
}
}
};
}(app));
document.getElementById("file-upload-btn").addEventListener("click", function(e){
e.preventDefault();
document.getElementById("file-upload-btn").setAttribute("disabled", "true");
document.getElementById("select-file-btn").setAttribute("disabled", "true");
var f = document.getElementById('files'),
pb = document.getElementById('file-bar-fill-id'),
pt = document.getElementById('file-bar-fill-text-id');
app.uploader({
files: f,
progressBar: pb,
progressText: pt,
processor: "action.php",
finished: function(data){
document.getElementById("file-upload-btn").disabled = false;
document.getElementById("select-file-btn").disabled = false;
if(data.status===true){
alert(data.data);
}
},
error: function(){
alert("Error occured. Try Again after page reload.");
}
});
});
</script>
</form>
</div>
</body>
</html>
action.php
<?php
set_time_limit(0);
if(count($_FILES["files"])>0)
{
$success = 0;
$failed = 0;
foreach ($_FILES["files"]["error"] as $key => $value)
{
if(empty($value))
{
if(move_uploaded_file($_FILES["files"]["tmp_name"][$key], __DIR__."/uploads/".uniqid()."_".$_FILES["files"]["name"][$key]))
{
$success++;
}
else
{
$failed++;
}
}
else
{
$failed++;
}
}
$data = "";
if($success>0)
$data .= $success." files uploaded. ";
if($failed>0)
$data .= $failed." files failed to upload";
$response = array("status" => true, "data" => $data );
echo json_encode($response);
}
?>
As I've said in comment - no real cure to stop redundant uploads at server side as long as user has full access to html. The only thing that you can do - is to monitor total uploaded MB/day and to blacklist user ip/account who does such illegal activity. For example:
session_start();
$_SESSION['total_uploaded'] += (int)(filesize(($_FILES['fileToUpload']['tmp_name']))/(1024*1024));
if ($_SESSION['total_uploaded'] > 1024) {
echo "<p style='background-color: palevioletred; max-width:280px;'>
You uploaded too much data : {$_SESSION['total_uploaded']} MB<br>
So your IP/account will be blacklisted !</p>";
}
$html = <<< STR
<table border="1">
<tr>
<td>
<form id="uploadForm" action="" method="post" enctype= "multipart/form-data">
<br>
 <input type="file" name="fileToUpload" value=""><br><br>
 <input type="submit" name="submit_file" value="Upload">
</form>
</td>
</tr>
</table>
STR;
echo $html;
After some threshold of bombing server with uploads user will see:

creating and passing a checkbox array to javascript function

I have an html form displaying a series of checkboxes. The checkboxes (an array called "checkbox" is ) are created using a loop in php. I want to use this array for some background processing.
Trying to use AJAX as below, but I am not able to get it working.
Please help!
Here is test.php: containing html form:
<!DOCTYPE html>
<script language="javascript">
function activate(checkbox){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById("ajaxState").innerHTML =xhttp.readyState;
document.getElementById("ajaxStatus").innerHTML =xhttp.status;
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("ajaxResponse").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "process.php", true);
xhttp.setRequestHeader( "Content-Type", "application/json" );
xhttp.send(JSON.stringify(checkbox));
}
</script>
<html>
<body>
<form>
<?php
for ($i=0; $i<10; $i++){
echo "$i: ";
echo "<input type='checkbox' name='checkbox[".$i."]'></input><br>";
}
?>
<button type="button" name="button" onclick="activate(checkbox)" >Test</button>
</form>
<p>ajaxState: <span id="ajaxState"></span></p>
<p>ajaxStatus: <span id="ajaxStatus"></span></p>
<p>ajaxResponse: <span id="ajaxResponse"></span></p>
</body>
</html>
Output: Don't get any response.
process.php: decode json data and display the array
<?php
$data = file_get_contents( "php://input" );
$checkbox = json_decode( $data, true );
echo "Hello!<br>";
var_dump($checkbox);
?>
NOTE: If, in the button element, I use this.checkbox, var_dump returns NULL.
<button type="button" name="button" onclick="activate(this.checkbox)" >Test</button>
Response:
ajaxState: 4
ajaxStatus: 200
ajaxResponse: Hello!
NULL
Check the below code...
<!DOCTYPE html>
<script language="javascript">
function activate(){
/*getting all inputs*/
var inputs = document.getElementsByTagName("input");
var cbs = []; //will contain all checkboxes
var checked = []; //will contain all checked checkboxes
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
cbs.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
//then making a request
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
document.getElementById("ajaxState").innerHTML =xhttp.readyState;
document.getElementById("ajaxStatus").innerHTML =xhttp.status;
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("ajaxResponse").innerHTML = xhttp.responseText;
}
};
console.log(xhttp);
xhttp.open("POST", "process.php", true);
xhttp.setRequestHeader( "Content-Type", "application/json" );
xhttp.send(JSON.stringify(checked));//sending checked instead of checkbox
}
</script>
<html>
<body>
<form>
<?php
for ($i=0; $i<10; $i++){
echo "$i: ";
echo "<input type='checkbox' name='checkbox[".$i."]'></input><br>";
}
?>
<button type="button" name="button" onclick="activate()" >Test</button>
</form>
<p>ajaxState: <span id="ajaxState"></span></p>
<p>ajaxStatus: <span id="ajaxStatus"></span></p>
<p>ajaxResponse: <span id="ajaxResponse"></span></p>
</body>
</html>
used this to get all checkboxes
Better use Query see jQuery - AJAX
Here realization "Click on button and show id current button in ajax, for use in second needed tasks". If I right anderstand you.
{{--include jQuery CDN Library--}}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<button type="button" name="1" id="test" >Test</button>
<button type="button" name="2" id="test" >Test</button>
<button type="button" name="3" id="test" >Test</button>
...
<style>
$("button#test").change(function(){
var id = $(this).attr('name');
$.ajax({
method: 'POST',
url: 'process.php',
data: {id: id}
})
.done(function(msg){
console.log('button: ' + msg);
});
});
</style>
And php file
<?php
$data = $_POST['id']
$checkbox = json_encode($data);
echo "Hello!<br>";
echo $data; // show id checkbox
?>
It is simpler realization codes, from same javascript codes

Div response in ajax php

I have the following code in HTML AJAX. What I want is to get the echo results from the php script on the same page that the ajax called not generating blank pages. Please check my code below:
<form id="form1" name="form1" method="post" action="/" enctype="multipart/form-data">
<select id="machine" name="machine" class="field" onChange='addaction(this.value)'>
<option value="" selected="selected">Choose..</option>
<option value="machine1.php">Machine 1</option>
<option value="machine2.php">Machine 2</option>
</select>
</fieldset>
<fieldset>
<legend><strong>Select a file to upload</strong></legend>
<input type="file" id="files" name="files[]" size="40" multiple="multiple" />
<br />
<p></p>
<input type="submit" value="Upload File" id="upload" />
<br />
<br />
</form>
<div id="information"></div>
</fieldset>
<fieldset>
<legend><strong>Uploaded Files</strong></legend>
<div id="uploaded"></div>
</fieldset>
<script type="text/javascript">
function addaction(actionvalue){
$("#form1").attr("action",actionvalue);
};
Any help would be much appreciated.
The php script part:
set_time_limit(0);
if(isset($_FILES['files']))
{
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name)
{
$file_name = $key.$_FILES['files']['name'][$key];
$file_size = $_FILES['files']['size'][$key];
$file_tmp = $_FILES['files']['tmp_name'][$key];
$file_type = $_FILES['files']['type'][$key];
if($file_size > 10000000) //10mb
{
echo "<script>alert('File exceeds file size')</script>";
}
if($file_type == "text/plain")
{
$i = 0;
$file = fopen($file_tmp,"r");
while(($data = fgetcsv($file, 1000, "\t"))!=FALSE)
{
if($i > 0)
{
$data[0] = "";
$data[1] = "";
$data[3] = "";
$data[4] = "";
$data[5] = "";
unset($data[0],$data[1],$data[3],$data[4],$data[5]);
$line[] = $data;
}
$i++;
}
fclose($file);
$j = 0;
foreach($line as $value)
{
$newline = explode(" ",$value[6]);
$date = trim($newline[0]);
$time = trim($newline[2]);
$newtime = date("H:i",strtotime($time));
try{
$query = $con->prepare("INSERT IGNORE INTO temp_logs(EmpID, ValidDate, ValidTime)VALUES(:id,:ddate,:time)");
$query->bindParam(':id',$value[2]);
$query->bindParam(':ddate',$date);
$query->bindParam(':time',$time);
$query->execute();
}
catch(PDOException $e){
echo $e->getMessage();
exit;
}
$j++;
echo $j . " row(s) processed.";
echo str_repeat(' ',1024 * 64);
flush();
sleep(0);
}
}
echo "Process completed";
}
}
I tried this code but it seems it doesn't work:
$('body').on('click','#upload',function(e){
e.preventDefault();
var page = $('#machine option:selected').val();
var formData = new FormData($(this).parents('form')[0]);
$.ajax({
url: page,
type: 'POST',
xhr: function(){
var myXhr = S.ajaxSettings.xhr();
return myXhr;
},
success: function (data){
alert("Data Uploaded: "+data);
},
data: formData,
cache: false,
contentType: false,
processData: false,
});
return false;
});
I understood that you want to post to an other script without reloading the page and show the results on the page?
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
<form id="form1" name="form1" method="post" action="/" enctype="multipart/form-data">
<select id="machine" name="machine" class="field" onChange='outputResults()'>
<option value="" selected="selected">Choose..</option>
<option value="1">Machine 1</option>
<option value="2">Machine 2</option>
</select>
<div id="responsecontent">
</div>
... rest of form here ...
<script type="text/javascript">
function outputResults() {
var machineid = $('#machine').val();
//optional for some sort of effect:
$("#responsecontent").empty();
$("#responsecontent").append('<div style="width: 100%; text-align: center;"><img src="img/loading.gif" /></div>');
//posting the data to your php script and output the results in the div named 'responsecontent' above:
setTimeout(function(){
$.ajax({
url: "YOUR_PHP_RESPONSE_SCRIPT_HERE.php",
type: "POST",
data: {machineid:machineid},
success: function(data) {
// Do stuff when the AJAX call returns:
$("#responsecontent").empty();
$("#responsecontent").append(data);
}
});
}, 1000);
}
</script>
I found my solution by searching stackoverflow and have this code:
$(document).ready(function(){
$("#form1").submit(function(e){
var formObj = $(this);
var page = $("#machine option:selected").val();
if(window.FormData !== undefined)
{
var formData = new FormData(this);
$.ajax({
url: page,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function(data){
$("#uploaded").empty();
$("#uploaded").append(data);
}
});
e.preventDefault();
}
});
});

How to display AJAX output in a <div> generated from jQuery plugin?

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..

Categories

Resources