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};
Related
For example, when I (administrator) create a record and leave the Bootstrap toggle on, the record will be visible to the users. However, if I create a record and make the Bootstrap toggle off the record will be invisible to the users.
<script>
//Using a function technique to create a JavaScript class, WebFormData
function WebFormData(inSessionSynopsisName, inIsVisible) {
this.sessionSynopsisName = inSessionSynopsisName;
this.isVisible = inIsVisible;
}
$('#toggle-event').change(function () {
var collectedIsVisible = $('#isVisibleInput').val();
})
$('#saveButton').on('click', function () {
var collectedSessionSynopsisName = $('#sessionSynopsisNameInput').val();
var webFormData = new WebFormData(collectedSessionSynopsisName, collectedIsVisible);
var webFormDataInString = JSON.stringify(webFormData);
$saveSessionSynopsisHandler = jQuery.ajax({
type: 'POST',
url: '/API/SessionSynopses/',
dataType: 'json',
contentType: 'application/json;',
data: "'" + webFormDataInString + "'"
})//end of ajax() call
$saveSessionSynopsisHandler.done(function (data, textStatus, jqXHR) {
new Noty({
text: data.message, type: 'success',
layout: 'center',
template: '<div class="noty_message"><span class="noty_text"></span>'
}).show();
});//end of saveCourseHandler.done();
$saveSessionSynopsisHandler.fail(function (data, textStatus, jqXHR) {
console.log(textStatus);
console.log(data);
console.log(jqXHR);
new Noty({
text: data.responseJSON.message, type: 'error',
layout: 'center',
template: '<div class="noty_message"><span class="noty_text"></span>'
}).show();
});//end of $saveCourseHandler.fail();
});//end of $('#saveButton').on('click', function () {
</script>
check befor onload your page the user:
if user admin change style to your button to turn it on
else if user not admin change style to your button to turn it off
to do some processing before loading a page you can use onunload please read this https://www.w3schools.com/jsref/event_onunload.asp
I have the following Javascript code that works perfectly as far as the autocompleting as well as filling 5 additional input fields, based on the loaded array from MySQL in the type_code.php file.
The sixth element of the array val(names[6]) is filled with a database value of either Yes or No and I am trying to use this value to control whether an additional form field becomes readonly or readwrite at the front end.
It seems as if my if statement is badly formatted, as if I run the two lines of codes without the if everything works as expected.
// Autocomplete Invoice To from Code and sets ReadOnly/ReadWrite based on Editable field in Code record
$('#add_at_inv2_code1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'type_code.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'code_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#desc_at_inv2_code1').val(names[1]);
$('#add_at_inv2_code2').val(names[2]);
$('#add_at_inv2_client').val(names[3]);
$('#add_at_salesrep').val(names[4]);
$('#add_at_category').val(names[5]);
// Code that is not working
if($(val(names[6])) == "Yes") {
$('#add_at_inv2_client').prop('readonly',false);
$('#add_at_inv2_client').prop('disabled',false);
} else {
$('#add_at_inv2_client').prop('readonly',true);
$('#add_at_inv2_client').prop('disabled',true);
}
}
});
Can someone please help me structure this if statement correctly?
Thanks,
Adri
The val() method returns or sets the value attribute of the selected elements.
Note: The val() method is mostly used with HTML form elements.
Use
if(names[6] == "Yes")
instead of
if($(val(names[6])) == "Yes")
=========================================================================
<script type="text/javascript">
// Autocomplete Invoice To from Code and sets ReadOnly/ReadWrite based on Editable field in Code record
$('#add_at_inv2_code1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'type_code.php',
dataType: "json",
method: 'post',
data: {
name_startsWith: request.term,
type: 'code_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#desc_at_inv2_code1').val(names[1]);
$('#add_at_inv2_code2').val(names[2]);
$('#add_at_inv2_client').val(names[3]);
$('#add_at_salesrep').val(names[4]);
$('#add_at_category').val(names[5]);
// Code that is not working
if(names[6] == "Yes") {
$('#add_at_inv2_client').prop('readonly',false);
$('#add_at_inv2_client').prop('disabled',false);
} else {
$('#add_at_inv2_client').prop('readonly',true);
$('#add_at_inv2_client').prop('disabled',true);
}
}
});
</script>
Need following change in your code
// Code that is not working
if(names[6] == "Yes") //Change this if($(val(names[6])) == "Yes")
{
$('#add_at_inv2_client').prop('readonly',false);
$('#add_at_inv2_client').prop('disabled',false);
}
else
{
$('#add_at_inv2_client').prop('readonly',true);
$('#add_at_inv2_client').prop('disabled',true);
}
As the title suggests I would like to load remote data once only.
I thought about loading a data with independent ajax call and set it "locally" at the control but wonder if there is more "built in" way to do so...
a solution can be found here:
https://github.com/ivaynberg/select2/issues/110
$("#selIUT").select2({
cacheDataSource: [],
placeholder: "Please enter the name",
query: function(query) {
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData.result});
return;
} else {
$.ajax({
url: '/ajax/suggest/',
data: { q : query.term },
dataType: 'json',
type: 'GET',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data.result});
}
})
}
},
width: '250px',
formatResult: formatResult,
formatSelection: formatSelection,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
});
Edit:
I might have misinterpreted your question. if you wish to load all data once, then use that is Select2, there is no built in functionality to do that.
Your suggestion to do a single query, and then use that stored data in Select2 would be the way to go.
This is for Select2 v4.0.3:
I had this same question and got around it by triggering an AJAX call and using the data returned as the initialized data array.
// I used an onClick event to fire the AJAX, but this can be attached to any event.
// Ensure ajax call is done *ONCE* with the "one" method.
$('#mySelect').one('click', function(e) {
// Text to let user know data is being loaded for long requests.
$('#mySelect option:eq(0)').text('Data is being loaded...');
$.ajax({
type: 'POST',
url: '/RetrieveDropdownOptions',
data: {}, // Any data that is needed to pass to the controller
dataType: 'json',
success: function(returnedData) {
// Clear the notification text of the option.
$('#mySelect option:eq(0)').text('');
// Initialize the Select2 with the data returned from the AJAX.
$('#mySelect').select2({ data: returnedData });
// Open the Select2.
$('#mySelect').select2('open');
}
});
// Blur the select to register the text change of the option.
$(this).blur();
});
This worked well for what I had in mind. Hope this helps people searching with the same question.
To load data once:
Assumptions:
You have a REST API endpoint at /services that serves a JSON array of objects
The array contains objects which have at least a "name" and "id" attribute. Example:
[{"id": 0, "name": "Foo"}, {"id": 1, "name": "Bar"}]
You want to store that array as the global 'services_raw'
First, our function to load the data and create the global 'services_raw' (AKA 'window.services_raw'):
fetchFromAPI = function() {
console.log("fetchFromAPI called");
var jqxhr = $.ajax(
{
dataType:'json',
type: 'GET',
url: "/services",
success: function(data, textStatus, jqXHR) {
services_raw = data;
console.log("rosetta.fn.fetchServicesFromAPI SUCCESS");
rosetta.fn.refreshServicesSelect();
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Error inside rosetta.fn.fetchServicesFromAPI", errorThrown, textStatus, jqXHR);
setTimeout(rosetta.fn.fetchServicesFromAPI(), 3000); // retry in 3 seconds
}
}
)
.done(function () {
console.log("success");
console.log(jqxhr);
})
.fail(function () {
console.log("error");
})
.always(function () {
console.log("complete");
});
// Perform other work here ...
// Set another completion function for the request above
jqxhr.always(function () {
console.log("second complete");
});
};
Second, our Select2 instantiation code which transforms our data into a format that Select2 can work with:
refreshServicesSelect = function () {
// ref: http://jsfiddle.net/RVnfn/2/
// ref2: http://jsfiddle.net/RVnfn/101/ # mine
// ref3: http://jsfiddle.net/RVnfn/102/ # also mine
console.log('refreshServicesSelect called');
$("#add-service-select-service").select2({
// allowClear: true
data: function() {
var arr = []; // container for the results we're returning to Select2 for display
for (var idx in services_raw) {
var item = services_raw[idx];
arr.push({
id: item.id,
text: item.name,
_raw: item // for convenience
});
}
return {results: arr};
}
});
};
Here's what the Select2 element in HTML should look like before your call the above functions:
<input id="add-service-select-service" type="hidden" style="width:100%">
To use all of this, call (in JS):
window.fetchFromAPI();
window.refreshServicesSelect();
Lastly, here's a JSFiddle where you can play with a similar thing: http://jsfiddle.net/RVnfn/102/
Basically, in my example above, we're just using ajax to populate the equivalent of window.pills in the Fiddle.
Hope this helps :)
Please reply if you know how to do this via the Select2 .ajax function, as that would be a bit shorter.
In my condition, it is working perfectly with the given code
$('#itemid').select2({
cacheDataSource: [],
closeOnSelect: true,
minimumInputLength: 3,
placeholder: "Search Barcode / Name",
query: function(query) {
// console.log(query);
self = this;
var key = query.term;
var cachedData = self.cacheDataSource[key];
if(cachedData) {
query.callback({results: cachedData});
return;
} else {
$.ajax({
url: "./includes/getItemSelect2.php",
data: { value : query.term },
dataType: 'json',
type: 'POST',
success: function(data) {
self.cacheDataSource[key] = data;
query.callback({results: data});
}
});
}
},
});
And my data return from the ajax is in this form
<?php
$arr = [
["id" => 1, "text" => "Testing"],
["id" => 2, "text" => "test2"],
["id" => 3, "text" => "test3"],
["id" => 4, "text" => "test4"],
["id" => 5, "text" => "test5"]
];
echo json_encode($arr);
exit();
?>
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
},
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);