Body of notifications not showing up JavaScript - javascript

I made a live chat script and when the user sends a message it should show a notification, although it does show the notification it does not show the body of the notification. Here is my code:
$(document).ready(function () {
function askNotificationPermission() {
function handlePermission(permission) {
if(Notification.permission === 'denied' || Notification.permission === 'default') {
alert("You denied notification access");
} else {
}
}
if (!('Notification' in window)) {
console.log("This browser does not support notifications.");
} else {
if(checkNotificationPromise()) {
Notification.requestPermission()
.then((permission) => {
handlePermission(permission);
})
} else {
Notification.requestPermission(function(permission) {
handlePermission(permission);
});
}
}
}
function checkNotificationPromise() {
try {
Notification.requestPermission().then();
} catch(e) {
return false;
}
return true;
}
$("#submitmsg").click(function () {
var clientmsg = $("#usermsg").val();
$.post("post.php", { text: clientmsg });
$("#usermsg").val("");
var img = "../../images/icon.png";
var notofication = new Notification("Chat", { body: clientmsg, icon: img });
return false;
});
function loadLog() {
var oldscrollHeight = $("#chatbox")[0].scrollHeight - 20;
$.ajax({
url: "log.html",
cache: false,
success: function(html) {
$("#chatbox").html(html);
var newscrollHeight = $("#chatbox")[0].scrollHeight - 20;
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal');
}
}
});
}
setInterval(loadLog, 200);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" autocomplete="off" id="usermsg" placeholder="Type something..."/> <button id="submitmsg">Send</button>
It does show the notification but does not show the body of notification, any help is appreciated.

Related

function not run again if status === false

iam trying to run my function again if the status of my json false but its not working
$(document).ready(function(){
function checkIfCompleted(){
$('.btn').click( function(e) {
e.preventDefault();
var url = "https://localhost/check/1";
$.ajax({
url: url,
success: function(response) {
if(response.status === false){
checkIfCompleted();
}else{
alert(done);
}
},
});
});
}
checkIfCompleted();
});
You are adding click multiple times to the button, you are not rerunning the Ajax call
$(document).ready(function() {
function checkIfCompleted(cnt) {
var url = "https://localhost/check/1";
$.ajax({
url: url,
success: function(response) {
if (response.status === false) {
if (cnt >= 5) {
throw new Error('too many retries');
} else {
checkIfCompleted(++cnt);
}
} else {
alert(done);
}
},
});
}
$('.btn').click(function(e) {
e.preventDefault();
checkIfCompleted(0);
});
});

Only one alert for multiple execution in Ajax

I am working rails application.i need to get status of the each selected device.I am able to achieve this but after executing i am putting alert "Successfully created execution record".For every mac selection it is showing alert message.I need to give one alert in end of execution.I am calling display_result in call_endpoint method.Since it is an Ajax call,it is giving alert for every execution.i don't how to limit to single alert for this.
function display_result() {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
alert('Successfully created execution record");
}
});
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 0; i < m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result();
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
Below is changed code..
Copy below code as it is.
function display_result(total,current) {
$('#http_status').html("");
$('#http_status').append(result["response"].status);
if (result["response"].status == "404") {
console.log("HTTP 404");
$('#response_div').addClass("bs-callout-warning");
} else if (result["response"].status == "520") {
console.log("HTTP 502");
$('#response_div').addClass("bs-callout-danger");
} else {
console.log("HTTP 200");
$('#response_div').addClass("bs-callout-success");
if (result["response"].status == "200") {
// $('.loader').show();
$('#cover-spin').show();
$.ajax({
method: "GET",
dataType: "text",
url: "create_execution",
data: {
http_status: result["response"].status,
mac_address: mac,
},
success: function (execution_record_id) {
$('#cover-spin').hide();
if(total == current)
{
alert('Successfully created execution record");
}
}
});
}
}
}
function call_endpoint() {
var values = new Array();
webpa = $('#Device-PA').is(":visible");
rpil = $('#Device-SN').is(":visible");
groupselect = $('#Group-Select').is(":visible");
parameter_name = $('#tr_object').val();
if (webpa) {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
} else {
$.each($("input[name='checkBox[]']:checked").closest("td").next("td"), function () {
values.push($(this).text().trim())
});
m = values.length
}
serialnumber = $('#pa_serialnumber').val();
oid = $('#sn_serialnumber').val();
protocol = {
pa: pa,
sn: sn,
}
if (pa) {
for (var i = 1; i <= m; i++) {
(function () {
var macAdd = values[i];
$.ajax({
method: "GET",
url: "get_object",
dataType: "json",
data: {
parameter: parameter_name,
mac: macAdd,
protocol: protocol,
serialnumber: serialnumber,
},
success: function (result) {
console.log(result);
NProgress.done();
console.log("result for webpa");
display_result(m,i);
},
statusCode: {
404: function () {
console.log("Call failed");
}
}
});
})();
}
}
}
result and mac is not defined in display_result function. result appears intended to be the resulting value of jQuery promise object returned from $.ajax(). Am not certain what mac is indented to be.
You can substitute $.when() and $.map() for for loop, return a jQuery promise object from call_endpoint(), include error handling, chain .then() to call_endpoint() call to execute alert() once.
function call_endpoint() {
return $.when.apply($, $.map(values, function(macAdd) {
return $.ajax().then(display_result)
}))
}
callEnpoint()
.then(function() {
alert('Successfully created execution record');
}, function(jqxhr, textStatus, errorThrown) {
console.error(errorThrown)
});
function display_result(reuslt) {
..
if (if (result["response"].status == "200")) {
return $.ajax() // remove `alert()` from `success`
}
return;
}

Show partial view model using Ajax - ASP.NET C# AJAX JQuery

I am looking to show a modal, I have my Modals as partial classes, so if you select the class .js-verify-songs it loads up the partial _VerifySong . If however there is an error, it should load up the error partial _ErrorMessage. And finally if you select .js-reject-song it should load _RejectSong partial.
Any idea how I would do this, please?
to show errors. Currently I have this in my Controller to handle errors:
public partial class SongsManagementController : BaseController
{
private const string NoDataFound = "No data found.";
private const string InvalidDataPosted = "Invalid data posted";
private const string InvalidRequest = "Invalid request.";
private const string VerificationFailedUnexpectedError = "The following song failed to verify due to an unexpected error, please contact RightsApp support.";
private const string ConcurrencyError = "The following song failed to verify as another user has since changed its details.";
[HttpPost]
[Route("VerifyNewSongs")]
[AuthorizeTenancy(Roles = "super,administrator")]
public async Task<ActionResult> VerifyNewSongs(List<VerifySongViewModel> verifySongViewModels)
{
// Not AJAX method - refuse
if (!Request.IsAjaxRequest())
return RedirectToAction("NewSongs", "SongsManagement");
if (verifySongViewModels.NullOrEmpty())
{
// return error;
return Json(new JsonBaseModel
{
success = false,
message = InvalidRequest,
data = null,
errors = new List<string>
{
InvalidDataPosted
}
});
}
foreach (var verifySong in verifySongViewModels)
{
if (verifySong.WorkId == default(Guid) || verifySong.RowVersion == default(Guid))
{
return Json(new JsonBaseModel
{
success = false,
message = InvalidDataPosted,
data = null,
errors = new List<string>
{
$"Invalid data posted for following song.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
var work = await _artistAccountService.GetWorkGraphAsync(verifySong.WorkId, includeWriterAmendments: true);
if (work == default(WorkGraphModels.Work))
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
$"No data found for following song.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
if (work.VerifiedState != Domain.Enumerators.VerifiedStateType.NotVerified)
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
$"Song already verified.",
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
work.RowVersion = verifySong.RowVersion;
var workAndAmendment = new WorkGraphModels.WorkAndAmendment
{
Original = work,
Amendment = null
};
var verifiedState = await _artistAccountService.VerifyWorkGraphAsync(workAndAmendment, GetLoggedUserId());
if (!verifiedState.ValidationErrors.NullOrEmpty())
{
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
VerificationFailedUnexpectedError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
else if (!verifiedState.DatabaseErrors.NullOrEmpty())
{
if (!verifiedState.FatalException)
{
// concurrency exception
return Json(new JsonBaseModel
{
success = false,
message = NoDataFound,
data = null,
errors = new List<string>
{
ConcurrencyError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
else
{
// fatal
return Json(new JsonBaseModel
{
success = false,
data = null,
errors = new List<string>
{
VerificationFailedUnexpectedError,
$"Song Title: {verifySong.SongTitle}",
$"Song Id: {verifySong.UniqueCode}"
}
});
}
}
}
return Json(new JsonBaseModel
{
success = true,
message = "All songs verified successfully."
});
}
};
}
This is my Main View:
Layout = Request.IsAjaxRequest() ? null : "~/Views/Shared/_SentricLayout.cshtml";
var actionName = ViewContext.RouteData.Values["Action"].ToString();
#* calc full account code *#
var fullAccountCode = Model.WorkUniqueCode;
ViewBag.Title = "New Songs";
}
#section scripts {
#Scripts.Render("~/bundles/jqueryajaxval")
#Scripts.Render("~/bundles/jqueryval")
#Scripts.Render("~/bundles/datetimepicker")
<script language="javascript" type="text/javascript">
#* DOM ready? *#
$(function () {
addTableStylingScripts();
var selectFormDiv = $('.catalogSelector');
selectFormDiv.hide();
$(".records-selected").hide();
// clear all filter boxes and reset search.
$("#btnClear").click(function()
{
$("#newSongsSearch").find(':input').each(function ()
{
if (this.type === "text")
{
$(this).val("");
}
});
$("#btnSearch").click();
});
#* edit catalogue button *#
$('#changeCat').click(function () {
$('#errorContainer').hide();
var label = $('#catLabel');
if (label.is(":visible")) {
label.hide();
selectFormDiv.show();
$('#changeCat').addClass("active");
} else {
label.show();
selectFormDiv.hide();
$('#changeCat').removeClass("active");
}
});
#* edit dropdown *#
$("#catalogueSelect").on("change", function () {
#* change display on select change *#
$('#errorContainer').hide();
$('#catLabel').show();
selectFormDiv.hide();
$('#changeCat').removeClass("active");
#* set up ajax post to controller *#
var model = {
AccountCode: '#fullAccountCode',
CurrentAccountId: $('#currentAccountId').val(),
CurrentRowVersion: $('#currentRowVersion').val(),
NewCatalogueId: $('#catalogueSelect option:selected').val(),
Action: '#actionName'
};
$.ajax({
url: '#Url.Action("ChangeCatalogue", "ArtistAccount")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
#* ajax worked *#
if (result.ChangeStatus === "Success")
{
var newSelected = $('#catalogueSelect option:selected').text();
$('#catLabel').html(newSelected);
#* update dropdown context *#
var newSelectedId = $('#catalogueSelect option:selected').val();
$('#currentCatalogue').val(newSelectedId);
#* update rowversion *#
var newRowVersion = result.OldOrNewRowVersion;
$('#currentRowVersion').val(newRowVersion);
}
else
{
$('#errorContainer').show();
$('#errorMessage').html(result.ErrorMessage);
#* return downdown context *#
var currentCatId = $('#currentCatalogue').val();
$("#catalogueSelect").val(currentCatId);
$('#catalogueSelect').select2({ width: '180px', dropdownAutoWidth: true });
}
},
error: function () {
#* failed *#
$('#errorContainer').show();
$('#errorMessage').html('There was a server error, please contact the support desk on (+44) 0207 099 5991.');
#* return downdown context *#
var currentCatId = $('#currentCatalogue').val();
$("#catalogueSelect").val(currentCatId);
$('#catalogueSelect').select2({ width: '180px', dropdownAutoWidth: true });
}
});
});
function loadPartialPage(url) {
$('.spinnerOverlay').removeClass('hide');
$.ajax({
url: url,
type: 'GET',
cache: false,
success: function (result) {
$('.spinnerOverlay').addClass('hide');
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
}
function getSelectedWorks() {
var selectedWorks = $(".individual:checked");
var works = [];
$.each(selectedWorks, function (key, value) {
works.push(getSelectedWork(this));
});
return works;
}
// verify songs in bulk
$(document).on("click", ".js-verify-songs", function (e) {
e.preventDefault();
var works = getSelectedWorks();
verifySongs(works);
});
// reject songs in bulk
$(document).on("click", ".js-reject-songs", function (e) {
e.preventDefault();
var works = getSelectedWorks();
});
function getSelectedWork(element) {
var work = new Object();
work.WorkId = getRowData(element, "id");
work.RowVersion = getRowData(element, "rowversion");
work.UniqueCode = getRowData(element, "uniqueworkid");
work.SongTitle = getRowData(element, "songtitle");
return work;
}
// verify one song
$(document).on("click", ".js-verify-song", function (e) {
e.preventDefault();
var works = [];
works.push(getSelectedWork(this));
verifySongs(works);
});
// reject one song
$(document).on("click", ".js-reject-song", function (e) {
e.preventDefault();
var works = [];
works.push(getSelectedWork(this));
});
function verifySongs(songs) {
$('.spinnerOverlay').removeClass('hide');
$.ajax({
url: '#Url.Action("VerifyNewSongs", "SongsManagement")',
data: JSON.stringify(songs),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('.spinnerOverlay').addClass('hide');
if (result.success) {
loadPartialPage($(".paginate_button.active a").attr("href"));
}
},
error: function(error) {
$('.spinnerOverlay').addClass('hide');
}
});
}
#* Pagination Async Partial Handling *#
$(document).on("click",
"#indexPager a",
function() {
if ($(this).parent().hasClass('disabled') || $(this).parent().hasClass('active'))
return false;
loadPartialPage($(this).attr("href"));
return false;
});
$(document).on("change",
"#pageSizeSelector",
function() {
var selectedValue = $(this).val();
loadPartialPage(selectedValue);
return false;
});
#* Sorting Async Partial Handling *#
$(document).on("click",
"#tableHeader a",
function()
{
loadPartialPage($(this).attr("href"));
return false;
});
});
// Ensure that after paging and sorting ajax calls we re-bind
// the change event and hide the record count label.
$(document).ajaxComplete(function() {
$(".records-selected").hide();
$(".individual").on("change", determineActionButtonAvailability);
$(".selectall").click(function () {
$(".individual").prop("checked", $(this).prop("checked"));
determineActionButtonAvailability();
});
});
// Search functions
$('.searchDivider').click(function (e) {
$('#searchFields').slideToggle();
var isSearchShown = $(this).find('.caret').hasClass("caret-up");
if (isSearchShown) {
$(this).children('span').replaceWith('<span class="bg-white">Search <b class="caret"></b></span>');
} else {
$(this).children('span')
.replaceWith('<span class="bg-white">Search <b class="caret caret-up"></b></span>');
}
});
$(".searchArea input:text").keypress(function (e) {
if (e.which === 13) {
e.preventDefault();
$("#btnSearch").click();
}
});
$(window).resize(function () {
if ($(window).width() >= 1024) {
$('#searchFields').show();
}
});
$(".searchArea input:text").keypress(function (e) {
if (e.which === 13) {
e.preventDefault();
$("#btnSearch").click();
}
});
// Checks individual checkboxes and displays the count
$(".individual").on("change", determineActionButtonAvailability);
$(".selectall").click(function () {
$(".individual").prop("checked", $(this).prop("checked"));
determineActionButtonAvailability();
});
//Disable Top Verify Button if two or more checkboxes are selected.
$('.verify-btn').prop('disabled', true);
//Disable Action Button in the columns when more than one checkbox is selected
$('.table-btn').prop('disabled', false);
$(".individual").on("click", function () {
if ($(".individual:checked").length > 1) {
$('.table-btn').prop('disabled', true);
$('.verify-btn').prop('disabled', false);
}
else {
$('.table-btn').prop('disabled', false);
$('.verify-btn').prop('disabled', true);
}
});
// When one or more works are selected, will enable the top action menu.
// Will disable when none selected.
function determineActionButtonAvailability() {
if ($(".individual:checked").length > 1) {
$(".records-selected").show();
$("#selected").text($(".individual:checked").length);
$("#total").text($(".individual").length);
$(".verify-btn").prop('disabled', false);
if ($(".individual:checked").length > 1) {
}
}
else {
$(".records-selected").hide();
$('.table-btn').prop('disabled', false);
$(".verify-btn").prop('disabled', true);
}
}
// Enforce only numeric input in the Unique Id search textbox.
$(document).on("keydown", ".uniqueCodefield", function (e) {
var key = window.event ? e.keyCode : e.which;
var currentVal = $('.uniqueCodefield').val();
if (key === 8 || key === 9 || key === 13 || key === 37 || key === 39 || key === 35 || key === 36 || key === 46) {
return true;
} else if (key === 13) {
$('#newSongsSearch').validate();
if ($('#newSongsSearch').valid()) {
return true;
}
return false;
}
else if ((key < 48 || key > 57) && (key < 93 || key > 105)) {
return false;
} else if (currentVal.length >= 10) {
return false;
} else {
return true;
}
});
#* Wire up the Search button click to perform an AJAXified search *#
$(document).on("click", "#btnSearch", function (e) {
e.preventDefault();
// Only perform the search if the search criteria is valid.
if (!$('#newSongsSearch').valid()) {
return false;
}
$('.spinnerOverlay').removeClass('hide');
var model = {
SearchModel: {
WorkUniqueCode: $('#SongCode').val(),
SongTitle: $('#SongTitle').val(),
CatalogueUniqueCode: $('#CatalogueCode').val(),
CatalogueName: $('#CatalogueName').val(),
AccountUniqueCode: $('#AccountCode').val(),
AccountName: $('#AccountName').val()
}
};
$.ajax({
url: '#Url.Action("SearchNewSongs", "SongsManagement")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
return false;
});
#* Wire up the Search button click to perform an AJAXified search *#
$(document).on("click", "#btnSearch", function (e) {
e.preventDefault();
$('.spinnerOverlay').removeClass('hide');
var model = {
SearchModel : {
Name: $('#ContractNameSearch').val(),
ContractType: $('#ContractTypeSearch').val(),
CreatedBy: $('#CreatedBySearch').val(),
DateFrom : $('#DateFromSearch').val(),
DateTo : $('#DateToSearch').val()
}
};
$.ajax({
url: '#Url.Action("SearchContracts", "ClientSetup")',
data: JSON.stringify(model),
type: 'POST',
cache: false,
contentType: 'application/json',
success: function (result) {
$('#tableContainer').html(result);
addBootstrapTooltips("#tableContainer");
}
});
return false;
});
</script>
#Scripts.Render("~/bundles/searchusers-autosuggest")
}
#section additionalStyles {
#Styles.Render("~/plugins/datatables/media/css/cssDatatables")
}
<article class="row">
<h1 class="pageTitle artistHeader fw200 mb20 mt10">#ViewBag.Title</h1>
<div class="col-md-12">
<div class="panel panel-visible">
#Html.Partial("_NewSongsSearch", Model)
</div>
</div>
<div class="col-md-12">
<div class="panel panel-visible" id="tableContainer">
#Html.Partial("_NewSongsList", Model)
</div>
</div>
</article>
I am unsure though how I would show a list of error in my error partial view. Also how do you load a partial view with Ajax?
Currently you click verify and it loads the spinner, but I would like to load a partial view which is a modal. I’ve used partials because it’s what was decided. I’m just unsure how to get them to load using Ajax.

Handsontable autosave - ajax not defined

I copied the code from Handsontable official documentation, into a JSFiddle. This is handsontable 0.34.5.
I am getting an error in chrome console:
"ajax is not defined".
Code as follows, pre-loaded with handsontable.full.min.js and handsontable.full.min.css
HTML:
<div class="ajax-container">
<div class="controls">
<button name="load" id="load" class="intext-btn">Load</button>
<button name="save" id="save" class="intext-btn">Save</button>
<label>
<input type="checkbox" name="autosave" id="autosave" checked="checked" autocomplete="off">Autosave</label>
</div>
<pre id="example1console" class="console">Click "Load" to load data from server</pre>
<div id="example1" class="hot handsontable"></div>
</div>
Script:
var
$$ = function(id) {
return document.getElementById(id);
},
container = $$('example1'),
exampleConsole = $$('example1console'),
autosave = $$('autosave'),
load = $$('load'),
save = $$('save'),
autosaveNotification,
hot;
hot = new Handsontable(container, {
startRows: 8,
startCols: 6,
rowHeaders: true,
colHeaders: true,
afterChange: function(change, source) {
if (source === 'loadData') {
return; //don't save this change
}
if (!autosave.checked) {
return;
}
clearTimeout(autosaveNotification);
ajax('scripts/json/save.json', 'GET', JSON.stringify({
data: change
}), function(data) {
exampleConsole.innerText = 'Autosaved (' + change.length + ' ' + 'cell' + (change.length > 1 ? 's' : '') + ')';
autosaveNotification = setTimeout(function() {
exampleConsole.innerText = 'Changes will be autosaved';
}, 1000);
});
}
});
Handsontable.dom.addEvent(load, 'click', function() {
ajax('scripts/json/load.json', 'GET', '', function(res) {
var data = JSON.parse(res.response);
hot.loadData(data.data);
exampleConsole.innerText = 'Data loaded';
});
});
Handsontable.dom.addEvent(save, 'click', function() {
// save all cell's data
ajax('scripts/json/save.json', 'GET', JSON.stringify({
data: hot.getData()
}), function(res) {
var response = JSON.parse(res.response);
if (response.result === 'ok') {
exampleConsole.innerText = 'Data saved';
} else {
exampleConsole.innerText = 'Save error';
}
});
});
Handsontable.dom.addEvent(autosave, 'click', function() {
if (autosave.checked) {
exampleConsole.innerText = 'Changes will be autosaved';
} else {
exampleConsole.innerText = 'Changes will not be autosaved';
}
});
The code of the ajax function they are using is rather simple, is just a wrapper around XMLHttpRequest.
NOTE: I got it by just executing ajax.toString() via devtools on their docs page. It isn't referencing external functions, so it will work as is.
function ajax(url, method, params, callback) {
var obj;
try {
obj = new XMLHttpRequest();
} catch (e) {
try {
obj = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
obj = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support Ajax.");
return false;
}
}
}
obj.onreadystatechange = function () {
if (obj.readyState == 4) {
callback(obj);
}
};
obj.open(method, url, true);
obj.setRequestHeader("X-Requested-With", "XMLHttpRequest");
obj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
obj.send(params);
return obj;
}

My object is undefined when I test it i QUnit

I'm using QUnit and have a test script for a JQuery UI Widget:
define(
['jquery',
'knockout',
'../Widget/SearchPod/searchPod',
'jqueryui',
'jquery.ui.widget',
'../Widget/SearchPod/clr.searchPod'],
function ($, ko, searchPod) {
var checkSearchBy = function () {
test('check if select has Search By text', function () {
var expected = "Search By";
alert(searchPod.employees);//.checkSearchByWidget());
deepEqual(searchPod.employees, expected, "We expect drop down text to
display 'Search By' by default");
return 1;
});
};
return {
checkSearchBy: checkSearchBy
};
}
);
For some reason whenever I run the test script, an error occurs saying that the parameter searchpod above is undefined or null. The code of searchpod is below:
require(['jquery',
'knockout',
'jqueryui',
'jquery.ui.widget',
'domReady!',
'Widget/SearchPod/clr.searchPod',
'Widget/Listbox/clr.combobox'],
function ($, ko) {
$(document).ready(function () {
$("#search-pod").searchPod({
ready: function () {
var minimumLength = 2;
$("#search-message").hide();
//start
//end
var employees = [*some data*]
var leaves_filed = [*some data*]
var claims_filed = = [*some data*]
function sortData(prop, asc) {
data = data.sort(function (a, b) {
if (asc) return (a[prop] > b[prop]) ? 1 : ((a[prop] < b[prop]) ? -1 : 0);
else return (b[prop] > a[prop]) ? 1 : ((b[prop] < a[prop]) ? -1 : 0);
});
}
//This is to display search messages depends on selected search type and
function validateCriteria(selectedType) {
var searchMessage = 'No values match search criteria';
if (selectedType == 'ssn') {
if ($("#searchBox").val().length > minimumLength) {
searchMessage = 'Must enter all 9 digits of SSN';
}
}
$("#search-message").text(searchMessage);
}
// Search pod items
var selectedType = 'lastname';
var data = employees;
// Apply the combobox widget
$("#searchBy").combobox({
ready: function () {
},
select: function () {
selectedType = $("option:selected", this).val();
switch (selectedType) {
case 'lastname':
return;
if (employees.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetEmployeeListReport",
type: "GET",
processData: false,
success: function (result) {
employees.length = 0;
employees = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = employees;
}
});
}
else { data = employees; }
minimumLength = 1;
break;
case 'ssn':
minimumLength = 10;
break;
case 'eeid':
if (employees.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetEmployeeListReport",
type: "GET",
processData: false,
success: function (result) {
employees.length = 0;
employees = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = employees;
minimumLength = employees[5].eeid.length;
}
});
}
else { data = employees; minimumLength =
employees[5].eeid.length; }
break;
case 'leave_number':
if (leaves_filed.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetLeavesList",
type: "GET",
processData: false,
success: function (result) {
leaves_filed.length = 0;
leaves_filed = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = leaves_filed;
minimumLength = leaves_filed[0].leaveNumber.length;
}
});
}
else { data = leaves_filed; minimumLength =
leaves_filed[0].leaveNumber.length; }
break;
case 'claim_number':
if (claims_filed.length == 1) {
$("#loadingImage").css("display", "");
$("#searchBox").css("display", "none");
$.ajax({
url: "api/Dashboard/GetClaimsList",
type: "GET",
processData: false,
success: function (result) {
claims_filed.length = 0;
claims_filed = result.dataSet.dataTable.row;
$("#loadingImage").css("display", "none");
$("#searchBox").css({ display: '' });
data = claims_filed;
minimumLength = claims_filed[10].claimNumber.length;
}
});
}
else { data = claims_filed; minimumLength =
claims_filed[10].claimNumber.length; }
break;
}
sortData(selectedType, true);
$('#searchBox').val('');
}
});
sortData(selectedType, true);
//This will hide search-message when backpress is pressed.
$('html').keyup(function (e) {
if (e.keyCode == 8) {
if ($("#searchBox").val().length < minimumLength) {
if ($("#search-message").show()) $("#search-message").hide();
}
}
return;
});
//Code for Making SSN AutoComplete
$('#searchBox').keyup(function () {
if (selectedType == "ssn" && $('#searchBox').val().length == 10) {
var rptParam = "?ssn=" + $('#searchBox').val();
var ssnData = [{ "ssn": "", "lastname": "" }];
$.ajax({
url: "api/Dashboard/GetSsnList" + rptParam,
type: "GET",
processData: false,
success: function (result) {
ssnData = result.dataSet.dataTable.row;
var ssnArray = [];
ssnArray.push(ssnData);
if (ssnArray.length > 0) {
$("#searchBox").autocomplete({
minLength: 10,
source: function (request, response) {
var searchField;
var filteredArray = $.map(ssnArray, function (item) {
if (item.ssn != null) {
searchField = item.ssn;
if (searchField.toLowerCase().indexOf
(request.term) == 0 || searchField.indexOf
(request.term) == 0) {
return item;
}
} else { return null; }
});
response(filteredArray);
},
focus: function (event, ui) {
var focusValue;
focusValue = ui.item.ssn;
$("#searchBox").val(focusValue);
return false;
},
select: function (event, ui) {
}
}).data("ui-autocomplete")._renderItem =
function (ul,item){
return $("<li>")
.append(displayFormat)
.appendTo(ul);
};
}
$('#searchBox').autocomplete("search");
}
});
}
return;
});
$("#searchBox").focus(function () {
if (selectedType == 'ssn') {
$("#searchBox").autocomplete();
$("#searchBox").autocomplete("destroy");
return;
}
var searchField;
$("#searchBox").autocomplete({
minLength: minimumLength,
source: function (request, response) {
var filteredArray = $.map(data, function (item) {
if (selectedType === 'lastname') {
searchField = item.lastname;
}
if (selectedType === 'ssn') {
return false;
}
if (selectedType === 'eeid') {
searchField = item.eeid;
}
if (selectedType === 'leave_number') {
searchField = item.leaveNumber;
}
if (selectedType === 'claim_number') {
searchField = item.claimNumber;
}
if (searchField.toLowerCase().indexOf(request.term) == 0 ||
searchField.indexOf(request.term) == 0) {
if (selectedType === 'ssn' && request.term.length < 4) {
return null;
}
return item;
}
else {
return null;
}
});
if (!filteredArray.length) {
$("#search-message").show();
validateCriteria(selectedType);
}
else {
$("#search-message").hide();
}
response(filteredArray);
},
focus: function (event, ui) {
var focusValue;
if (selectedType === 'lastname') {
focusValue = ui.item.lastname;
}
if (selectedType === 'eeid') {
focusValue = ui.item.eeid;
}
if (selectedType === 'leave_number') {
focusValue = ui.item.leaveNumber;
}
if (selectedType === 'claim_number') {
focusValue = ui.item.claimNumber;
}
$("#searchBox").val(focusValue);
return false;
},
create: function (event, ui) {
$(this).autocomplete("widget").addClass("search-results-list");
},
open: function (event, ui) {
$(".search-results-list li.ui-menu-item").addClass("search-results-item");
},
select: function (event, ui) {
//return false; // Cancel the select event
var focusValue;
if (selectedType === 'lastname') {
focusValue = ui.item.lastname;
// TODO: call a function here that will send the name of the report to show
$('#report-popup-dialog-overlay').show();
$('#report-popup-dialog').show();
}
if (selectedType === 'eeid') {
focusValue = ui.item.eeid;
}
if (selectedType === 'leave_number') {
focusValue = ui.item.leaveNumber;
$('#dynamictext').text('Leave Report for ' + focusValue);
$('#dynamicHeader').text('Leave Report');
}
if (selectedType === 'claim_number') {
focusValue = ui.item.claimNumber;
$('#dynamicHeader').text('Claim Report for ' + focusValue);
$('#dynamictext').html("Loading...");
//Need to make Ajax Call to get the report.
var parameter = "?claimNumber=" + focusValue;
$.ajax({
url: "api/ViewReport/GetClaimReport" + parameter,
type: "POST",
processData: false,
success: function (result) {
$('#dynamictext').html("");
$('#dynamictext').html(result);
}
});
}
return false;
}
})
.data("ui-autocomplete")._renderItem = function (ul, item) {
var displayFormat = "";
return $("<li>")
.append(displayFormat)
.appendTo(ul);
};
});
}
});
});
//Test helper functions
//2. checkSearchBy
function checkSearchBy() {
alert($('#searchBy').text());
return $('#searchBy').text();
}
return {
checkSearchByWidget: function () {
return checkSearchBy();
}
};
});
I've been at this for two days but cant seem to make the searchpod be seen by the test script above

Categories

Resources