My AJAX seems like not working. It should load patient details into a dropwdown.
this is my ajax code:
function PopulatePatient()
{
$("#PatientDropDown").empty();
$("#PatientDropDown").append("<option>Loading.....</option>");
$.ajax({
type:"POST",
url:"../listener/populatePatientName.php",
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
$("#PatientDropDown").empty();
$("#PatientDropDown").append("<option value=''>-Select Patient-</option>");
$.each(data,function(i,item)
{
$("#PatientDropDown").append('<option value="'+ data[i].patientUserId +'">'+ data[i].patientFirstName +'</option>');
});
},
complete: function()
{
}
});
}
This is my PHP Code (populatePatientName.php):
<?php
include '../core/init.php';
$sql = mysql_query("SELECT patientUserId,patientFirstName FROM patientdetails");
if(mysql_num_rows($sql))
{
$data=array();
while($row=mysql_fetch_array($sql))
{
$data[]=array
(
'patientUserId' => $row['patientUserId']
'patientFirstName' => $row['patientFirstName']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
This is my HTML Code:
<select class="form-control" id="PatientDropDown">
</select>
This code works in my friend PC. My database and query are running well. Table contained data.
My code stop at this point : $("#PatientDropDown").append("Loading.....");
It does not enter ajax. Any solution?
I found the solution, I forgot the comma,
<?php
include '../core/init.php';
$sql = mysql_query("SELECT patientUserId,patientFirstName FROM patientdetails");
if(mysql_num_rows($sql))
{
$data=array();
while($row=mysql_fetch_array($sql))
{
$data[]=array
(
'patientUserId' => $row['patientUserId'],
'patientFirstName' => $row['patientFirstName']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
$data[]=array
(
'patientUserId' => $row['patientUserId'],
'patientFirstName' => $row['patientFirstName']
);
try this line before $.each()
function in ajax success
data= JSON.parse(data);
Use "GET" instead of "POST" into your ajax type.
Your script is absolutely fine, but you do not have any event which will trigger PopulatePatient()
function. Run the function to get data. Use console.log(data)
to check whether your php is sending data or not.
Try to go to populatePatientName.php using web browser, it should return JSON data
Two questions:
- It is included jquery in head tag like this?
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
- To populate try using a button like:
<input type="button" onClick="populatePatient()" />