In AJAX, variable value is not updated - javascript

Below is my jquery stuff, it works correct to call REST Service and response result return back to AJAX Success event.
But, every time when it executes then it does not update the variable "SelectedVal" (document.getElementById('Text1').value) and remain same which is the value set at first time.
it looks like, event is attached and not updated on each click.How it could be resolve ?
jQuery(document).ready(function() {
var selectedVal = '';
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = jQuery('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'Plan Issues',
right: 'month,agendaWeek,agendaDay'
},
selectable: true,
selectHelper: true,
select: function(start, end, allDay) {
AJS.$(document).ready(function() {
var dialog = new AJS.Dialog({
width: 400,
height: 300,
id: "planissues-dialog",
closeOnOutsideClick: true
});
// PAGE 0 (first page)
// adds header for first page
dialog.addHeader("Plan Issues");
// add panel 1
dialog.addPanel("Issues Planning", "<table><tr><td>Enter issues ID (separated by comma):</td><td><input id='Text1' type='text' /></td></tr></table>", "panel-body"); //PROBLEM: "Text1" control is added here in dialog.
dialog.addButton("Submit", function (dialog)
{
selectedVal = document.getElementById('Text1').value; //PROBLEM:This returns every time same value even though, entering different value while dialog is popup. it preserve same value which was enter during first time and then after on each consequence , it remains same value.
if (selectedVal != '') {
alert(selectedVal); // PROBLEM: alert shows same value which set at first time.
var url = "http://localhost:2990/jira/rest/restresource/1.0/message/save/" + selectedVal;
jQuery.ajax({
type: "POST",
url: url,
contentType: "application/json",
dataType: "json",
data: "finaldatapassed",
cache: false,
success: function (resp, status, xhr) {
alert('in success JSON');
alert(status); //success
},
error: function(resp, status, xhr){
alert('in error json');
alert("Error: " + resp.e);
}
});
}
});
});

success is defined as
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
try
success: function (data) {
alert('in success JSON');
alert(data); //success
},

Related

JQuery chosen Dynamic ajax call option duplication issue, If use empty() element then lose default selected value

$(this.el).ready(function(){
setTimeout(function(){
var subItemsData = [];
$(self.el).chosen({
width: '100%',
allow_single_deselect: true,
no_results_text: "Oops, nothing found!",
search_contains: false,
max_selected_options: self.params.maxselected ? self.params.maxselected : 0
}).on('change', function(evt, params) {
var value = $(self.el).val();
self.set(value);
console.log("value",value);
}).on('chosen:showing_dropdown', function(evt, params) {
})
$('#patient_diagnosis_chosen ul li.search-field input').autocomplete({
source: function( request, response ) {
if(request.term.length >= self.params.minlength){
$.ajax({
url: baseURL+'api/service/v1/get-data',
dataType: "json",
method:'post',
data:{
'ids':$(self.el).val(),
'key':request.term
},
success: function( data ) {
var subItems=[]
data.input_data.forEach((item,index)=>{
subItems.push( "<option value="+item.id+">"+ item.code +' - '+item.short_description + "</option>" );
subItemsData.push(item)
})
$(self.el).append(subItems).trigger("chosen:updated");
}
});
}
}
});
},100);
});
This code able to call api and get api response, But issue is option are duplication If I use
$(self.el).empty().append(subItems).trigger("chosen:updated");
then lose default select value
If It is posible to empty the element and set the default element.
This question has solved this code is working for me.
var self = this;
// var ids=[]
$(this.el).ready(function(){
setTimeout(function(){
$(self.el).chosen({
width: '100%',
allow_single_deselect: true,
no_results_text: "Oops, nothing found!",
search_contains: false,
max_selected_options: self.params.maxselected ? self.params.maxselected : 0
}).on('change', function(evt, params) {
var value = $(self.el).val();
// ids = $(self.el).val();
self.set(value);
console.log("value",value);
}).on('chosen:showing_dropdown', function(evt, params) {
})
$('#patient_diagnosis_chosen ul li.search-field input').autocomplete({
source: function( request, response ) {
if(request.term.length >= self.params.minlength){
$.ajax({
url: baseURL+'api/service/v1/get-data',
dataType: "json",
method:'post',
data:{
'ids':$(self.el).val(),
'key':request.term
},
success: function( data ) {
var subItems=[]
var ids=$(self.el).val()
data.input_data.forEach((item,index)=>{
subItems.push( "<option value="+item.id+">"+ item.code +' - '+item.short_description + "</option>" );
})
$(self.el).empty().append(subItems).trigger("chosen:updated");
var test = $.trim(ids);
var testArray = test.split(',');
$(self.el).val(testArray).trigger("chosen:updated");
}
});
}
}
});
},100);
});
When call the ajax with selected values and it's give the response then empty the element and and again set the selected value in chosen
Api response is with seleced values

can i put schedule in fullcalendar as ajax?

I want to add the ability to schedule in fullcalendar, Laravel. The method is working as expected however, I do not understand what to do with the response data.
$('#calendar').fullCalendar({
header: {
left : 'today, prev,next',
center: 'title',
right : '',
},
locale:'ko',
height:'parent',
events : function(start, end, timezone, callback){
var month = $('#calendar').fullCalendar('getDate').format('YYYY-MM');
var url = '{{route('reservation.get_schedule',[request()->id])}}';
alert(url)
$.ajax({
type : 'get',
data : {'date' : month},
url : url,
datatype : 'json',
success : function(data){
console.log(data); // How do I use the data
}
});
}
});
The documentation for events-as-a-function says:
[The function]... will also be given callback, a function that must be called when
the custom event function has generated its events. It is the event
function’s responsibility to make sure callback is being called with
an array of Event Objects.
There's also an example on that page where the callback function is employed to pass the event data returned from the AJAX call into fullCalendar.
So in your case (assuming that your event data is already in the format required by fullCalendar and doesn't need any transformation) you would simply add a call to this function inside your "success" callback:
events : function(start, end, timezone, callback){
var month = $('#calendar').fullCalendar('getDate').format('YYYY-MM');
var url = '{{route('reservation.get_schedule',[request()->id])}}';
alert(url)
$.ajax({
type : 'get',
data : {'date' : month},
url : url,
datatype : 'json',
success : function(data){
console.log(data);
callback(data); //pass the event data to fullCalendar via the provided callback function
}
});
}
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
$.ajax({
url: 'myxmlfeed.php',
dataType: 'xml',
data: {
// our hypothetical feed requires UNIX timestamps
start: start.unix(),
end: end.unix()
},
success: function(doc) {
var events = [];
$(doc).find('event').each(function() {
events.push({
title: $(this).attr('title'),
start: $(this).attr('start') // will be parsed
});
});
callback(events);
}
});
}
});
DOC

syntax error jquery handle json

Firebug says that there's a syntax error near:
if (json['name'] !="")
But I still can't find it. This is part of a long poll script that hangs until the server sends a response. When the server response is empty, it throws the error near if (json['name'] !="")
var timestamp=null;
function waitForMsg(){
$.ajax({
type: "GET",
url: "auth/classes/getdata.php?id="+6,
async: true,
cache: false,
success: function(data){
var json=eval('('+data+ ')');
if (json['name'] !=""){
if(json['type'] ==1){
$.notification({
content: json['name']+" liked a post",
showTime: true,
icon: '8',
timeout: 10000,
click: function() {
window.location.href = "http://www.test.com/posts.php?post="+json['post'];
}
});
}
if(json['type'] ==2){
$.notification({
content: json['name']+" disliked a post",
showTime: true,
icon: 'Y',
timeout: 10000,
click: function() {
window.location.href = "http://www.test.com/posts.php?post="+json['post'];
}
});
}
if(json['type'] ==3){
$.notification({
content: json['name']+" commented a post",
showTime: true,
icon: 'i',
timeout: 10000,
click: function() {
window.location.href = "http://www.teest.com/posts.php?post="+json['post'];
}
});
}
}
setTimeout("waitForMsg()",1000);
},
error: function(XMLHttpRequest,textStatus,errorThrown) {
// alert("error: "+textStatus + " "+ errorThrown );
setTimeout("waitForMsg()",15000);
}
});
}
$(document).ready(function() {
waitForMsg();
});
When the server response is empty, it throws the error near if (json['name'] !="")
So check to see if there is data
if(!data || !data.length) {
return;
}
var json=eval('('+data+ ')');
Modern day browsers support JSON.parse() and also jQuery will automtically do this for you if you return the correct content type from the server.
Why don't you use "dataType: 'json'" as an attribute of you ajax call? That would create a json object from the response and you can work directly with that variable.
$.ajax({
type: "GET",
url: "auth/classes/getdata.php?id="+6,
async: true,
cache: false,
dataType: "json",
success: function(data){
var json=data; //or you can work directly with data
If you return an empty message from your server ("" instead of "{}"), it will trigger the "error" function of your ajax call, since it will throw a parse exception.
Hope this helps you.
Regards,
Marcelo

setting a flag in javascript

MODNOTE: I used the {} tags to format the code, but it looks horrible. I'm trying to fix it now.
My specific questions are:
I'm setting a flag with a javascript variable. Is the way I'm doing it a reasonable approach?
I've researched this a bit on this site and elsewhere, and noted that flags can be "set" (1) in an array, (2) in a hidden HTML element, (3) in a cookie. I've seen nothing about setting a flag with .data().
Is there an "elegant", "standard", "accepted" way to set a flag for use on ONE page to make a decision in an if/else statement? How do YOU set flags in situations like this?
My code is below:
After "ready" set flag to "not set".
Click on a button to input new info into a table - flag is set "add"
Click on a row in a table of existing data - flag is set to "update"
If flag is "add" use ajax to add to table, if flag is "update" update a row in the db.
CODE
$(document).ready(function() {
var flagaddupdate = "notset";
$("#onsetdate").mask("99-99-9999");
$("#entrydate").mask("99-99-9999");
$("#uonsetdate").mask("99-99-9999");
$("#uentrydate").mask("99-99-9999");
$(function(e) {
$("#reaction").autocomplete({
source: [ "none", "rash/hives", "Nausea/vomiting", "Diarrhea", "Headache", "Dizziness" ],
minlength: 1
});
});
$("#addintoleranceenterbutton").click(function() {
flagaddupdate = "add";
$( "#addintolerancetable" ).dialog(
{height: 320,
width: 450,
modal: true}
);
});//end of add click
$("#patienttable tr").click(function() {
flagaddupdate = "update";
$( "#addintolerancetable" ).dialog(
{height: 320,
width: 450,
modal: true}
);
uniqueid = $(this).find("#uniqueid").html();
$.ajax({
type: "POST",
url: "readintolerancebackend.php",
data: {uniqueid: uniqueid},
dataType : 'json',
})
.done(function(result){
$('#namegen').val(result['namegen']);
$('#nametrade').val(result['nametrade']);
$('#reaction').val(result['reaction']);
$('#onsetdate').val(result['onsetdate']);
$('#entrydate').val(result['entrydate']);
if ( result['status'] == "Active" )
{ $('#active').prop('checked',true);}
else
{ $('#inactive').prop('checked',true);}
})
.always(function(data, textStatus, jqXHR){
console.log(data, textStatus, jqXH);
});
});//end of update click
$("#submitbutton").click(function() {
var namegen = $('#namegen').val();
var nametrade = $('#nametrade').val();
var reaction = $('#reaction').val();
var onsetdate = $('#onsetdate').val();
var entrydate = $('#entrydate').val();
var status = $('input:radio[name=status]:checked').val();
if (flagaddupdate == "add")
{
$.ajax({
type: "POST",
url: "addintolerancebackend.php",
data: {
namegen: namegen, nametrade: nametrade, reaction: reaction,
onsetdate: onsetdate, entrydate: entrydate, status: status
}
})
.done( function( msg ) {alert( "Intolerance Added" + msg );
window.location = "intolerance.php";
})
.always(function(data, textStatus, jqXHR){
console.log(data, textStatus, jqXHR);
});
}
else
{ do another ajax call};

javascript returning an object but not what I expected to see

My code is returning an object and not what I expected to see. When I output the output in console, I get object but all the data is there. What is supposed to happen, is that the id is passed to actionrow and this does the ajax call to the db. The object is being output from console.log(datarow); in the code.
I am using jqxWidgets for grid and data
// action row.
$("#actionrowbutton").bind('click', function () {
var selectedrowindex = $("#jqxgrid").jqxGrid('getselectedrowindex');
var datarow = $("#jqxgrid").jqxGrid('getrowdata', selectedrowindex);
var rowscount = $("#jqxgrid").jqxGrid('getdatainformation').rowscount;
if (selectedrowindex >= 0 && selectedrowindex < rowscount) {
var rows = $('#jqxgrid').jqxGrid('getrows', selectedrowindex);
var id = $("#jqxgrid").jqxGrid('getrowid', selectedrowindex);
//var service = datarow;
console.log(datarow);
$("#jqxgrid").jqxGrid('actionrow', id);
//Open action dialog window
$( "#actionWindow" ).dialog({
//title: 'action error',
resizable: false,
modal: true,
position: ['center', 'center'],
buttons: {
"Ok": function() {
$(this).dialog("close");
$('#jqxgrid').jqxGrid('refreshdata');
},
Cancel: function() {
$( this ).dialog( "close" );
//$('#jqxgrid').jqxGrid('refreshdata');
}
}
});
}
});
actionrow: function (actrowid) {
// synchronize with the server - send action command
var data = "action=true&id=" + actrowid;
$.ajax({
dataType: 'json',
url: 'data.php',
data: data,
success: function (data, status, xhr) {
// action command is executed.
}
});
}
After looking at your code, I am left with a question.
What is "actionrow", is it a function or a method of jqxgrid object? If it isn't it should be written like so:
function actionrow(actrowid) {
// synchronize with the server - send action command
var data = "action=true&id=" + actrowid;
$.ajax({
dataType: 'json',
url: 'data.php',
data: data,
success: function (data, status, xhr) {
// action command is executed.
}
});
}
And called like so in your if statement.
actionrow(id); //not $("#jqxgrid").jqxGrid('actionrow', id);

Categories