Reputation: 47
I have an ajax method that runs as soon as the page is loaded without listening to any event. The ajax fetches student ID from the database and shows the student ID in a select box. I want the select box to be editable (http://indrimuska.github.io/jquery-editable-select/). The function $('#studentID').editableSelect();
runs completely fine when the options are hardcoded in the select tag. However, no data is shown in the selectbox when $('#studentID').editableSelect();
is called and the data is fetched from the database.
Here is the code that is written in the JavaScript file
$('#studentID').editableSelect();
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
$('#studentID').html(html);
}
});
#studentID
definition
<label for="studentID">ID</label>
<select id = "studentID" class="form-control">
</select>
php code
<?php
$connection = new mysqli ("127.0.0.1", "root", "", "test");
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$query = "SELECT `SID` FROM `student` ORDER BY `SID` ";
$result1= mysqli_query($connection, $query);
while($row1 = mysqli_fetch_array($result1)):;?>
<option value="<?php echo $row1[0];?>"><?php echo $row1[0];?></option>
<?php endwhile;
$connection->close();
?>
Any help will be appreciated.
Upvotes: 1
Views: 1125
Reputation: 3506
Move the editableSelect
into the ajax.success
method. The problem is that you are initializeing an empty select element, and then inserting it the options with the asynchronous ajax
method. The success will forever happen after the data will successfully loaded, and then you can initialize the select with any framework/library, including editableSelect
that you want to.
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
let student_el = $('#studentID');
student_el.html(html);
student_el.editableSelect();
}
});
EDIT:
you might not included the library in the right way, so for any case, here is the two ways to include it:
<head>
<!--Include jQuery + you libraries...-->
<script src="https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
<link href="https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet" />
</head>
$.ajax({
type: 'POST',
url: './public/api/studentID.php',
success: function(html){
let student_el = $('#studentID');
student_el.html(html);
$.getScript("https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js")
.then(() => {
student_el.editableSelect(); // Call this function after the script have been successfully loaded.
});
//student_el.editableSelect();
}
});
Upvotes: 2
Reputation: 123
Why don't you try calling editableSelect on your callback
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
$('#studentID').html(html);
$('#studentID').editableSelect();
}
});
Upvotes: 0