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.
Related
I am currently trying to check if a value of a string variable is "Apple". Now I need to pass a list of fruits to javascript from C#.
C# Code
List<String> fruits = new List<String>{"Apple","Mango","Orange"}
JavaScript Code
$(document).on('click','#dvAppContent input:checkbox[id*=chkfunction]', function () {
ToggleApplication(this);
});
function ToggleApplication(currentFunction) {
var fruitName = $(currentFunction).closest('ui').parent('label').text().trim();
If(fruitName == "Apple")
{
return true;
}
}
Use Ajax call in JavaScript.
Something like this:
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/api/StudentAPI/GetAllStudents",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(JSON.stringify(data));
$("#DIV").html('');
var DIV = '';
$.each(data, function (i, item) {
var rows = "<tr>" +
"<td id='RegdNo'>" + item.regNo + "</td>" +
"<td id='Name'>" + item.name + "</td>" +
"<td id='Address'>" + item.address + "</td>" +
"<td id='PhoneNo'>" + item.phoneNo + "</td>" +
"<td id='AdmissionDate'>" + Date(item.admissionDate,
"dd-MM-yyyy") + "</td>" +
"</tr>";
$('#Table').append(rows);
}); //End of foreach Loop
console.log(data);
}, //End of AJAX Success function
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
} //End of AJAX error function
});
});
</script>
And in the backend in c#, something like this:
public class StudentAPIController : Controller
{
// GET: api/GetAllStudents
[HttpGet]
public IEnumerable<PersonalDetail> GetAllStudents()
{
List<PersonalDetail> students = new List<PersonalDetail>
{
new PersonalDetail{
RegNo = "2017-0001",
Name = "Nishan",
Address = "Kathmandu",
PhoneNo = "9849845061",
AdmissionDate = DateTime.Now
},
new PersonalDetail{
RegNo = "2017-0002",
Name = "Namrata Rai",
Address = "Bhaktapur",
PhoneNo = "9849845062",
AdmissionDate = DateTime.Now
},
};
return students;
}
}
This is my javascript function which accepts id as a signature and alert the selected text of dropdown
function sendata(id) {
$(document).ready(function () {
$(id).on('change', function () {
var ctlevel = $(id).find("option:selected").text();
var selectedValue = $(id).val();
alert("Selected Text: " + ctlevel + " Value: " + selectedValue);
});
});
}
here ,i called the function but it didn't work and it did not alert the text message of dropdown also the data is not sent to controller .but when i replace the senddata function with the inner code of that function it works ??
$(document).ready(function () {
senddata('#ddtname');
$.ajax({
url:'#Url.Action("Getdata", "ConfigClass")',
type: "GET",
data: {'ctname':ctlevel},
dataType: "text",
//Response carry bunch of data from controller
success: function (response) {
alert(response);
//parse json obj to js
var obj = JSON.parse(response)
var ele = document.getElementById('sel');
$('#sel').empty();
//append default value to dropdown
var s = '<option value="-1">SubjectName</option>';
//using loop for populating dropdown ,values retrive through ajax
for (var i = 0; i < obj.length; i++) {
// POPULATE SELECT ELEMENT WITH JSON.
s+='<option value="' + obj[i]['aid'] + '">' + obj[i]['assignsubject'] + '</option>';
}
$('#sel').html(s);
},
error: function () {
alert('not working :(');
}
});
});
I´m trying to get a list with Ajax when a modal shows up, but for some reason my method always receives a null variable. I´m sure that the issue is on the Ajax call, because if I test my method using 1 as an argument instead of the value from Ajax, it returns the list the way I wanted.
JS:
$("#visualizacao").on('show.bs.modal', function (e) {
var data = $(e.relatedTarget);
var idAviso = data.context.dataset.avisoid;
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/' +idAviso,
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});
C#
[HttpGet]
public JsonResult ListaVisuAviso(string avisoId)
{
//var avisoid = 1;
var avisoid = Convert.ToDecimal(avisoId);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
}
I discovered what was causing the "issue". To use this way of sending the parameter, my route config on the backend was expecting it to be a parameter called "id". So I would either change my receiving parameter to "id" instead of "avisoId" like the following:
[HttpGet]
public JsonResult ListaVisuAviso(string id)
{
//var avisoid = 4;
var avisoid = Convert.ToDecimal(id);
var query =
from a in _dataContext.TB_AVISOS_NOTIFICACOES
join b in _dataContext.VW_USUARIOS4 on a.USUARIO_PR equals b.USUARIOID
where a.AVISO_ID == avisoid
select new VisuAviso()
{
NOME = b.NOME,
DATA_HORA = a.DATA_HORA.ToString(),
DEPARTAMENTO = b.DEPARTAMENTO
};
return Json(query, JsonRequestBehavior.AllowGet);
Or, I would have do specify the name of the parameter on the JS, like this "?usuarioId=", this way the route would know that it´s not the id parameter:
$("#visualizacao").on('show.bs.modal', function (e) {
var idAviso = $(e.relatedTarget).attr('data-avisoid');
$.ajax({
type: 'GET',
url: 'ListaVisuAviso/?usuarioId =' + idAviso,
dataType: 'json',
success: function (response) {
$('#visu-table tbody').empty();
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.NOME + '</td><td>' + item.DATA_HORA + '</td><td>' + item.DEPARTAMENTO + '</td></tr>';
});
$('#visu-table tbody').append(trHTML);
$('#modal-visu').modal('show');
},
error: function (xhr) {
console.log(xhr);
}
});
$('#modalAviso').modal('show');
});
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>');
}
}
});
});
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);
}
});