Why is variable is showing as a string? - ajax

I don't understand why call_script_id is showing as a string instead of the content stored in the variable. The other variables work fine, but literally, call_script_id is setting id="call_script_id" whereas call_reason_id is setting the proper number.
$.ajax({
url: "../selections/call-reasons.php",
type: 'post',
data: {company_uid:"<?php echo $row['company_uid']; ?>"},
dataType: 'json',
success:function(response){
var len = response.length;
$("#call_reasons").empty();
for( var i = 0; i<len; i++){
var call_script_id = response[i]['call_script_id'];
var call_reason_id = response[i]['call_reason_id'];
var call_type = response[i]['call_type'];
var active = response[i]['active'];
$("#call_reasons").append("<tr><td href='../modals/call-types.php' class='call_reason_row' id=" + call_script_id + ">" + call_reason_id + "</td><td id=" + call_script_id + "></td><td id=" + call_script_id + "></td><td><i class='far fa-edit'></i><i class='far fa-calendar-alt'></i><i class='far fa-trash-alt call_reason_trash' id=" + call_reason_id + "></i></td></tr>");
}
// Brings up the pop up to edit call reasons/types
$(".call_reason_row").click(function() {
$('#main-content',parent.document).load($(this).attr('href'), {call_reason_id: this.id, company_uid: "<?php echo $row["company_uid"];?>", active: active});
});
},
error: function (xhr, status, error) {
alert(xhr.responseText);
}
});
$sql = "SELECT cs.id, cs.call_reason, sct.call_type FROM call_script AS cs INNER JOIN selection_call_types AS sct ON cs.call_reason = sct.id WHERE cs.company_uid = '$company_uid'";
$result = mysqli_query($conn, $sql);
$my_array = array();
while($row = mysqli_fetch_array($result) ){
$call_script_id = $row['id'];
$call_reason_id = $row['call_reason'];
$call_type = $row['call_type'];
$active = $row['active'];
$my_array[] = array("call_script_id" => call_script_id, "call_reason_id" => $call_reason_id, "call_type_id" => $call_type, "active" => $active);
}

I guess I expecting the issue to be in ajax since I'm not as familiar with the language. Instead, it was because I was missing the dollar sign on the variable call_reason_id, in $my_array on the very last line.

Related

How to change 'active/inactive status of user' through ajax?

I am display list of users in datatable based on 2 parameters through AJAX in codeigniter. I want to change the status of user in database and display in table. I have 3 status 0-> inactive, 1->active, -1->left. I want to change the status and display in datatable without reloading the page.
I have tried changing the status but the status is changing only once. After first AJAX call there is no change when i again change the status.
//view
<script>
$(document).ready(function()
{
$('#academicTable_wrapper').hide();
$('#studentTable').DataTable();
showStudents();
function showStudents()
{
$('#submitBtn').on('click',function(){
var courseId = $('#courseId').val();
var classId = $('#classId').val();
$.ajax({
type : 'POST',
url : "<?php echo base_url();?>Student/getStudentsList",
// async : true,
data : {courseId:courseId,classId:classId},
dataType : 'json',
success : function(data){
//alert(data);
var html = '';
var i;
for(i=0; i<data.length; i++){
var studentId = data[i].studentId;
if(data[i].status == 1)
var status = "Approved";
else if(data[i].status == 0)
var status = "Pending";
else
var status = "Left";
html += '<tr>'+
'<td>'+data[i].studentId+'</td>'+
'<td>'+data[i].studentName+'</td>'+
'<td>'+data[i].studentPhoneNum+'</td>'+
'<td>'+data[i].created_on+'</td>'+
'<td id="changeStatus">'+status+'</td>'+
'<td>'+
'View'+
' '+
'<a id="activateBtn" data-id="'+data[i].id+'" data-status="'+data[i].status+'" class="btn btn-primary btn-sm text-white">Activate/Deactivate</a>'+
' '+
'Delete'+
'</td>'+
'</tr>';
}
$('#studentTable').DataTable().destroy();
$('#showData').html(html);
$('#studentTable').DataTable();
$('#academicTable_wrapper').show();
}
});
});
}
$(document).on('click','#activateBtn',function()
{
var id = $(this).data('id');
var status = $(this).data('status');
$.ajax({
method: 'POST',
url: "<?php echo base_url();?>Student/approveStudent",
data:{id:id,status:status},
success : function(data)
{
alert(data);
$('#changeStatus').text('');
if(data == 0)
{
showStudents();
$('#changeStatus').html('Inactive');
}
else{
showStudents();
$('#changeStatus').html('Approv');
}
},
error:function(data)
{
console.log(data);
}
},1000);
});
});
</script>
//controller
function approveStudent()
{
$id = $this->input->post('id');
$status = $this->input->post('status');
$col = 'id';
$query = $this->Admin_model->activate($col,$id,$status,$this->studentDetail);
if($query){
$result = $this->Admin_model->getData($col,$id,$this->studentDetail);
}
$status = 1;
if ($result[0]->status == 0)
{
$status = 0;
}
echo $status;
}
I expect whenever I click activateBtn the status should change in database and also in datatable.

How to load data on scroll in select2 dropdown without using pagination?

I have more than 1000 rows and it is taking much time in taking AJAX response and loading data in dropdwon.
I am using below code .
function fillperson() {
$.ajax({
// delay: 250 ,
url: Url,
type: "GET",
minimumInputLength:0,
data: { isGetAll: false, Id1: 0, ID2:0},
complete: function (data) {
var ele = document.getElementById('ddlperson');
ele.innerHTML = '';
var persondata = JSON.parse(data.responseText);
ele.innerHTML = '<option value="' + -1 + '">Select Person</option>';
ele.innerHTML += '<option value="' + 0 + '">ALL Person</option>';
var totaldata = persondata.length;
var i = 0;
for ( i ; i < data.length; i++) {
ele.innerHTML = ele.innerHTML +
'<option value="' + data[i]['Id'] + '">' +data[i]['name'] + '(' + data[i]['code'] + ')' + '</option>';
}
$('#ddperson').select2();
},
});
}

Flask-Admin: How to filter selectable data of a field based on values entered in the previous field, with search conditions in another table

in flask-admin model view I want to filter a dropdown menu in the edit/create view of field that is a relationship, based on values entered in the previous field.
In the specific case, I would like to see only the ones in the "posto" that are displayed in another table belonging to the selected 'categoria'
class Tag(db.Model):
__tablename__ = 'tags'
nr_TAG = db.Column(db.Integer, primary_key=True)
categoria_id = db.Column(db.Integer, db.ForeignKey('categorie.id'), nullable=False)
categoria = db.relationship('Categoria', backref='tags')
posto_id = db.Column(db.Integer, db.ForeignKey('stalli.id'), nullable=False)
posto = db.relationship('Stallo', backref='tags')
cognome = db.Column(db.String(30), nullable=False)
nome = db.Column(db.String(30))
auto = db.Column(db.String(20))
targa = db.Column(db.String(10))
recapito = db.Column(db.String(80))
stato = db.Column(db.Integer)
posto_occ = db.Column(db.Integer)
orario = db.Column(db.Integer)
fuoriposto = db.Column(db.String(10))
parcheggio = db.Column(db.String(40))
class TagsAdmin(sqla.ModelView):
can_edit = True
can_create = True
column_list = ['nr_TAG', 'categoria', 'posto', 'cognome', 'targa',
'stato', 'orario', 'fuoriposto', 'parcheggio']
can_view_details = True
details_modal = True
form_columns = ['nr_TAG', 'categoria', 'posto', 'cognome', 'nome', 'auto', 'targa', 'recapito']
Any idea?
Thanks
I came up with following solution, maybe it's not perfect but it does the job:
master.html
function populateSelectField(to_populate, options, select) {
$('#s2id_' + to_populate + ' > a > span').text('');
var el = $('select[name$="' + to_populate + '"]');
el.children().remove();
option = '<option value=""></option>';
el.append($(option));
options.forEach(function(row) {
var option_id = row.id,
option_title = row.title;
if (select && option_id == select) {
option = '<option value="' + option_id + '" selected>' + option_title + '</option>';
$('#s2id_' + to_populate + ' > a > span').text(option_title);
} else {
option = '<option value="' + option_id + '">' + option_title + '</option>';
}
el.append($(option));
});
}
function getOptions(el, to_populate, url, select) {
var item_id = el.val(),
url = window.location.origin + url + item_id + '/';
$.get(url).done(function(options) {
populateSelectField(to_populate, options, select);
}).fail(function(err) {
console.error(err.message);
return false;
});
}
function selectFieldManipulation(from_populate, to_populate, url) {
var main_select = $('select[name$="' + from_populate + '"]'),
to_populate_el = $('select[name$="' + to_populate + '"]');
getOptions(main_select, to_populate, url, to_populate_el.val());
main_select.change(function(e) {
getOptions(main_select, to_populate, url, null);
});
}
create.html / edit.html
$(document).ready(function() {
selectFieldManipulation('from_populate', 'to_populate', '/api/route_to_view/');
});

Pass function parameters for json fill drop down

How would pass the parameter into "foodName" from the function that sends the url and id? i.e. could you do something like the function:
call('/url/to/foodlist', "foodList", "food");
and replace
var input = item.food;?
Below is working code but would like a more general function then having to use part of name in the function (replace foodName so that it isn't in this function)
function call(url, id){
var string = '';
$.ajax({
type: "GET",
url: url,
success: function (item)
if (item != '') {
var input = item.foodName;
for (var i = 0; i < input.length; i++) {
string += = '<option value=' + input[i].name + '">' + input[i].name + '</option>';
}
$('#' + id). append(string);
}
});
call('/url/to/foodlist', "foodList");
function call(url, id, paramName){
var string = '';
$.ajax({
type: "GET",
url: url,
success: function (item)
if (item != '') {
var input = item[paramName]; // you can access to the properties using braces
for (var i = 0; i < input.length; i++) {
string += = '<option value=' + input[i].name + '">' + input[i].name + '</option>';
}
$('#' + id). append(string);
}

MVC 3 asp.net 500 internal server error

hi guys sorry i m really new to mvc3 javascript jquery etc.
i have an internal server error 500
this is the controller:
[HttpGet]
public JsonResult GetEmail(string title, string notes)
{
byte[] pdf = null;
byte[] excel = null;
string userEmail = "";
try
{
pdf = GetFileForMail("PDF", "ServiceArea_" + System.DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".pdf", title, notes);
excel = GetFileForMail("EXCEL", "ServiceArea_" + System.DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".xls", title, notes);
MembershipUser mu = Membership.GetUser(this.MembershipData.Principal.Identity.Name);
userEmail = mu.Email.ToString();
System.Net.Mail.MailMessage mailMsg = new System.Net.Mail.MailMessage(userEmail,
"mailexample#mail.com",
title,
notes);
mailMsg.To.Add("no-replay#valuelab.it");
mailMsg.IsBodyHtml = true;
string mese = "";
string giorno = "";
string ore = "";
if (DateTime.Now.Month < 10)
mese = "0" + DateTime.Now.Month;
else
mese = "" + DateTime.Now.Month;
if (DateTime.Now.Day < 10)
giorno = "0" + DateTime.Now.Day;
else
giorno = "" + DateTime.Now.Day;
if(DateTime.Now.Hour < 10)
ore = "0" + DateTime.Now.Hour;
else
ore = "" + DateTime.Now.Hour;
System.Net.Mail.Attachment att = new System.Net.Mail.Attachment(new MemoryStream(pdf), DateTime.Now.Year + mese + giorno + "_" + ore + DateTime.Now.Minute + " Report.pdf", System.Net.Mime.MediaTypeNames.Application.Pdf);
System.Net.Mail.Attachment att2 = new System.Net.Mail.Attachment(new MemoryStream(excel), DateTime.Now.Year + mese + giorno + "_" + ore + DateTime.Now.Minute + " Report.xls", "application/vnd.ms-excel");
mailMsg.Attachments.Add(att);
mailMsg.Attachments.Add(att2);
System.Net.Mail.SmtpClient sc = new System.Net.Mail.SmtpClient();
sc.Host = "192.168.99.1";
sc.Send(mailMsg);
return Json(new { text = "Everything is fine " + userEmail, risultato = true });
}
catch (Exception e) {
return Json(new { text = "Unexpected error" + userEmail , risultato = false});
}
}
and this is the way in which i call the controller:
jQuery.ajax({
type: "GET",
url: options.EmailUrl,
dataType: "json",
data:
{
title: viewModel.saReportTitle(),
notes: viewModel.saReportNotes()
},
success: function (data, textStatus, jqXHR) {
jQuery("#sa-dialog-alert").dialog('open');
jQuery("#sa-dialog-alert").dialog('option', 'title', 'Invio Mail Eseguito');
jQuery("#sa-dialog-alert").text(data.text);
}
,
error: function (data, textStatus, errorThrown) {
jQuery("#sa-dialog-alert").dialog('open');
jQuery("#sa-dialog-alert").dialog('option', 'title', 'Errore');
jQuery("#sa-dialog-alert").text("Errore nell'invio mail: " + errorThrown);
}
});
If you read the code the controller just send an email
and IT WORK FINE THERE are no exception
so why ajax say there is a 500 internal server error?
By default GET requests are not allowed on JsonResult so you need to excplicitly allow them, with setting the JsonRequestBehavior property:
return Json(
new { text = "Everything is fine " + userEmail, risultato = true },
JsonRequestBehavior.AllowGet
);
Or use POST as your request method in your AJAX call.

Resources