I am aware that AJAX works asynchronously (that is what the “A” stands for). I moved all the code that depends on the result of the AJAX call inside the success callback. However after the call is being made, I am not getting the select dropdwon box to populate with any data. How can I populate the select dropdown menu after the ajax call?
Jquery/Ajax
<script>
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
function addNewCourse() {
var data;
$.ajax({
type: "POST",
url: "coursesOffered.php",
data: { value : option},
success: function(data){
//alert(data);
//console.log(data);
content += '<select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list"><option value="" >--- Select ---</option>"';
content += data;
content += '</select></br>';
}
});
}
addNewCourse();
}
}
</script>
coursesOffered.php
try {
$db_con = new PDO($dsn, $user, $password);
$db_con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list;");
$course_query->execute();
$data = $course_query->fetchAll();
foreach ($data as $row){
//dropdown values pulled from database
echo '<option value="' . $row['course_id'] . ':'.$row['course_name'].'">' . $row['course_name'] . '</option>';
}
See my comments in code:
function showFields(option) {
for (var i = 1; i <= option; i++) {
(function(i) {
$.ajax({
type: "POST",
url: "coursesOffered.php",
data: {
value: option
},
success: function (data) {
var content += '<select id="coursename_' + i + '" name="coursename_' + i + '" class="course_list"><option value="" >--- Select ---</option>"';
content += data;
content += '</select></br>';
// Insert the `content` into DOM here, you cannot return due to the async nature of AJAX
}
});
})(i); // you have to pass `i` into a function, otherwise when ajax complete, i will equal to `option + 1`
}
}
It seems you have not used return statement in addNewCourse(), try return content; after completion of Ajax.
$(document).ready(function () {
$('#courses_offered').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
function addNewCourse() {
$.ajax({
type: "POST",
url: "coursesOffered.php",
data: { value : option},
success: function(data){
content += '<div id="course_'+i+'"><label>Course # '+i+'</label><br /><label>Course Name:</label> <select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list"><option value="" >--- Select ---</option>"';
content += data;
content += '</select></div></br>';
}
});
return content;
}
content = addNewCourse();
}
$('#course_catalog').html(content);
}
});
Related
I have Allocate_classRoom DB table where I want to show data using ajax
function departmentQuery()
{
var department = $('#department' ).val();
if(department!=" ")
{
var urls = "{{ URL::to('roomAjax') }}";
var request = $.ajax({
url: urls+"/"+department,
type: "GET",
dataType: 'json'
});
request.done(function(data){
var allRoom ="";
for (var i=0; i<data.length;i++)
{
// room +="<option value=' " +data[i].id+ " ' >"+data[i].name+ "</option>";
allRoom +=" <tr> " +
"<td>"+data[i].id+"</td>"+
"<td>"+data[i].course_id+"</td>"+
/*"<td>"+ course->name+"</td>"+*/
"<td>"+data[i].Room_No+"</td>"+
"<td>"+data[i].date+data[i].start_time+data[i].end_time+"</td>"+
"</tr>";
}
$("#allRoom").html(allRoom);
});
request.fail(function(){
alert('failed to get items for that department');
});
}else {
alert('Select Department');
}
}
And I am uploading controller code
public function ajaxRoom($id)
{
$allRoom = AllocateClassroom::where('department_id',$id)-
>with('course')->get();
return response()->json($allRoom);
}
.Data return from the database but I could not show it my view table please I want your suggestion.
This code tries to populate a dropdown list in a form with values. I have tested the PHP separately and the query is ok (small wonder !). I have a similar form whith 3 connected dropdown lists and they work flawlessly. Debugging this in Mozilla, I notice that the success function of JSON is not executed. I cannot understand why.
JavaScript
$(document).ready(function()
{
$.getJSON("/scripts/033A_GetJudet.php", success = function(data)
{
var str_options = "";
for (var i=0; i < data.length; i++)
{
str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#selJudet").append(str_options);
// var selOption = document.getElementById("selJudet");
// selOption.selectedIndex = localStorage.getItem("selJudIndex") || 0;
// document.getElementById("selJudet").selectedIndex = selOption.selectedIndex;
$("#selJudet").change();
});
$("#selJudet").change(function()
{
var selText = document.getElementById("selText");
// selText.value = selText.defaultValue;
selText.value = "Abcgcfkjsdhfsjkdh";
// $("#selText").change();
});
});
PHP (I skipped the database connection code)
$query = '(SELECT 1 AS sc, nume_judet FROM sa_Judet ';
$query .= 'WHERE nume_judet <> "N/A" ) UNION ';
$query .= '(SELECT 2 AS sc, "N/A" FROM sa_Judet) ';
$query .= 'ORDER BY sc, nume_judet';
//print $query;
$result = mysqli_query($db_conn, $query);
$judet = array();
if ($result == FALSE)
{
array_push($judet, 'QUERY_ERROR');
goto _adr1;
}
$rows = mysqli_num_rows($result);
if ($rows == 0)
{
array_push($judet, 'TBD_');
goto _adr1;
}
while ($row = mysqli_fetch_array($result))
{
array_push($judet, $row['nume_judet']);
}
_adr1:
print json_encode($judet);
mysqli_free_result($result);
mysqli_close($db_conn);
?>
Ajax variant of my original Javascript
$(document).ready(function()
{
$.ajax({
url: "/scripts/033A_GetJudet.php",
dataType: 'json',
success: function(data)
{console.log('SUCCESS: ', data);},
error: function(data)
{console.log('ERROR: ', data);}
var str_options = "";
for (var i=0; i < data.length; i++)
{
str_options += "<option value='" + data[i] + "'>" + data[i] + "</option>";
}
$("#selJudet").append(str_options);
var selOption = document.getElementById("selJudet");
selOption.selectedIndex = localStorage.getItem("selJudIndex") || 0;
document.getElementById("selJudet").selectedIndex = selOption.selectedIndex;
$("#selJudet").change();
});
$("#selJudet").change(function()
{
var selText = document.getElementById("selText");
selText.value = selText.defaultValue;
// $("#selText").change();
});
});
It is possibly an error in parsing the data received. HTTP 304 is the same as HTTP 200, only the contents is pulled from cache, not serverside.
$.ajax({
url: url,
data: data,
success: function(response, textStatus, jsqxhr) {
var obj; try { obj = eval(response); } catch(e) { console.error(e); }
// -- do something with obj --
},
fail: function(jqxhr, textStatus, error) {
console.log( "error", textStatus, error);
}
});
Use this function instead and look closer at the data. If data is returned through success, we try to evaluate the json string into an object. Should it fail, an exception is thrown (possibly SyntaxError) and log should show this.
Replace this line
$.getJSON("/scripts/033A_GetJudet.php", success = function(data)
with this one
$.getJSON("/scripts/033A_GetJudet.php", function(data)
guys i keep on getting this uncaught syntaxerror:unexpected token <, and it points to the jquery library file,i am making a request to AJAX(comment-insert-ajax.php) using JQuery(comment-insert.js),i try removing the closing token of php(?>) in the AJAX script but i still get the error.I actually get the error when i add the 'require_once' lines,sorry about that.
comment-insert-ajax.php
<?php
if(isset($_POST['task']) && $_POST['task'] == 'comment-insert')
{
$userId = (int)$_POST['userId'];
$comment = addslashes(str_replace("\n","<br>",$_POST['comment']));
$std = new stdClass();
$std->comment_id = 24;
$std->userId = $userId;
$std->comment = $comment;
$std->userName = "Thabo Ambrose";
$std->profile_img= "images/tbo.jpg";
require_once $_SERVER['DOCUMENT_ROOT'] . 'defines.php';
require_once MODELS_DIR . 'Comments.php';
echo json_encode($std);
}
else
{
header('location: /');
}
and following is the Jquery file that makes the request using the '$.post' method.
comment-insert.js
$(document).ready(function(){
$('#comment-post-btn').click(function(){
comment_post_btn_click();
});
});
function comment_post_btn_click()
{
var _comment = $('#comment-post-text').val();
var _userId = $('#user-id').val();
var _userName = $('#user-name').val();
if(_comment.length > 0 && _userId != null)
{
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(jQuery.parseJSON(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
else
{
//do something
$('#comment-post-text').addClass('alert alert-danger');
$('#comment-post-text').focus(function(){$('#comment-post-text').removeClass('alert alert-danger');});
}
//remove text in the text area after posting
$('#comment-post-text').val("");
}
function comment_insert(data)
{
var t = '';
t += '<li class="comment-holder" id="_'+data.comment_id+'">';
t += '<div class="user-img">';
t += '<img src="'+data.profile_img+'" class="user-img-pic">';
t += '</div>';
t += '<div class="comment-body">';
t += '<h3 class="username-field">'+data.userName+'</h3>';
t += '<div class="comment-text">'+data.comment+'</div>';
t += '</div>';
t += '<div class="comment-buttons-holder">';
t += '<ul>';
t += '<li class="delete-btn">x</li>';
t += '</ul>';
t += '</div>';
t += '</li>';
$('.comments-holder-ul').prepend(t);
}
The error points to line 7497 of the jQuery library,it point to the following code
jQuery.parseJSON = function(data)
{
return data;
}
Try using the JSON.parse function:
//proceed with ajax call back
$.post("ajax/comment-insert-ajax.php",
{
task : "comment-insert",
userId : _userId,
comment : _comment
}
).error(
function()
{
console.log("Error : ");
}
).success(
function(data)
{
comment_insert(JSON.parse(data));
console.log("Response text : "+ data);
}
);
console.log(_comment + " "+_userName + " id of "+_userId);
}
try puting the data in a array and then encode it
$array = ['comment_id' => 24,'userId' => $userId,'comment' => $comment,'userName' => "Thabo Ambrose",'profile_img'= "images/tbo.jpg"];
echo json_encode($array);
change if(isset($_POST['task']) && $_POST['task'] == 'comment-insert') this line of code to if(isset($_POST['task']) && isset($_POST['task'])&&$_POST['task']== 'comment-insert').
then change the ajax call to
$.ajax({
url: "ajax/comment-insert-ajax.php",
data :{"task":"comment-insert","UserId":_userId,"comment":_comment},
type: "POST",
dataType: "json",
success:function(msg) {
}
});
I'm trying to build a simple news page with ajax filters depending on what category the user wants to see. The javascript below connects to a php file and outputs HTML with data from the mysql database. I need to know how to tell the JS to put the data from the "heading" column into a php variable so that it wraps it in the correct href link.
This is the php that creates the heading and the link
$data_fields = '`id`, `heading`, `date`, `copy`, `summary`, `article`, `press_release`, `video`';
$from = '`media`';
$news_result = $db->selectByStrings($data_fields, $from, $where_conditions, $order_by);
$news = $db->getAllRows($news_result);
foreach ($news as $new) {
echo '<h2 class="news"><a class="news" href="'.$base_href.$new['id'].'">'.$new['heading'].'</a></h2>';
}
I somehow need to include this is the separate JS file, making sure it is only applied to data from the heading column.
Javascript
function makeTable(data) {
var tbl_body = "";
$.each(data, function () {
var tbl_row = "";
$.each(this, function (k, v) {
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>" + v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}
function getEmployeeFilterOptions() {
var opts = [];
$checkboxes.each(function () {
if (this.checked) {
opts.push(this.name);
}
});
return opts;
}
function updateEmployees(opts) {
$.ajax({
type: "POST",
url: "filter3.php",
dataType: 'json',
cache: false,
data: {filterOpts: opts},
success: function (records) {
$('#employees div').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function () {
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
updateEmployees();
The php file the above connects to:
<?php
$pdo = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
$select = 'SELECT heading, summary, created_date';
$from = ' FROM media';
$where = ' WHERE TRUE';
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : array('');
if (in_array("article", $opts)) {
$where .= " AND article = 1";
}
if (in_array("press_release", $opts)) {
$where .= " AND press_release = 1";
}
if (in_array("video", $opts)) {
$where .= " AND video = 1";
}
$sql = $select.$from.$where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
I think you are looking for something like this :
var base_href = 'http://www.stackoverflow.com/';
function makeTable(data) {
var tbl_body = "";
$.each(data, function (index, row) {
var tbl_row = "";
$.each(row, function (k, v) {
if(k == 'heading' && 'id' in row) {
v = '<a class="news" href="' + base_href + row.id +'">' + v + '</a>';
}
tbl_row += "<div class='row'><div class='col-md-8 col-md-offset-2'>"
+ v + " </div></div>";
});
tbl_body += "<div class='non-white'>" + tbl_row + "</div>";
});
return tbl_body;
}
Ajax
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '../include/ListOfCities.php',
dataType: "json",
data: {
Country: "Japan"
},
success: function(data) {
console.log(data);
var city = ('#city');
$(city).empty();
for (var i = 0; i < data.length; i++) {
$(city).append('<option id=' + data[i].sysid + ' value=' + data[i].city_name + '>' + data[i].city_name + '</option>');
}
}
});
});
php
$country = mysql_real_escape_string($_POST['Country']);
$stmt = $dbh->prepare("SELECT * FROM city_tbl WHERE country_name = ? ");
$stmt->bindValue(1, $country, PDO::PARAM_STR);
if ($stmt->execute()) {
if ($stmt->rowCount() > 0) {
while ($selected_row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$citylist[] = array('sysid' => $selected_row['sys_id'], 'code' => $selected_row['city_code'], 'name' => $selected_row['city_name'], 'parentid' => $selected_row['parent_id']);
}
$input = array_map("unserialize", array_unique(array_map("serialize", $citylist)));
echo json_encode($input, JSON_UNESCAPED_UNICODE);
}
}
I want to display the all the city in japan in a select option menu i want to load the cities when the page loads i am sending the ajax request like above but i don't get any result the ajax above works fine when i use it on button. Is sending ajax request different from on button click and on document ready..Any suggestion how to make ajax request on document ready is appreciated
Just try setting async:false in your ajax request. So the final code will be
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '../include/ListOfCities.php',
dataType: "json",
async:false,
data: {
Country: "Japan"
},
success: function(data) {
console.log(data);
var city = ('#city');
$(city).empty();
for (var i = 0; i < data.length; i++) {
$(city).append('<option id=' + data[i].sysid + ' value=' + data[i].city_name + '>' + data[i].city_name + '</option>');
}
}
});
});