jQuery object reference issue - javascript

function startCampaign(index, campaign_id) {
var btn = $('#toggleStateBtn' + index);
btn.html('<i class="icofont-pause"></i>');
btn.removeClass('btn-success');
btn.addClass('btn-warning');
btn.attr('title', 'Pause this campaign');
btn.width('9px');
// Start campaign
$.ajax({
url: '/campaign/startCampaign/' + campaign_id,
type: 'POST',
success: function(data){
// Reflect the new state in status column
btn.html(data);
}
});
}
function pauseCampaign(index, campaign_id) {
var btn = $('#toggleStateBtn' + index);
btn.html('<i class="icofont-play"></i>');
btn.removeClass('btn-warning');
btn.addClass('btn-success');
btn.attr('title', 'Run this campaign');
btn.width('9px');
// Pause campaign
$.ajax({
url: '/campaign/pauseCampaign/' + campaign_id,
type: 'POST',
success: function(data){
// Reflect the new state in status column
btn.html(data);
}
});
}
For some reason this is causing strange behaviour. If you replace btn with $('#toggleStateBtn' + index) in all places then everything works fine.
My guess is, if for instance you first call startCampaign() and then called pauseCampaign() the old btn reference gets changed to the new one. But I'm not sure.
Ideas?

Nevermind I am an idiot, the btn in btn.html(data) is actually a different control. I was mindlessly substituting. Looks like I need an extra dose of caffeine this morning.

Related

How to redraw jQuery DataTable after link is clicked without navigating from page?

I have a column in my jQuery datatable that renders a green checkmark link if data == true or a red X if data == false:
{
data: "HasPayment",
render: function (data, type, row) {
var paymentSet = '#Url.Action("Set", "Payment")?applicationId=' + row.Id + '&year=' + row.Year + '&month=' + row.Month + '&hasPayment=' + data;
if (data) {
return '';
}
return '';
}
},
The problem is that when I click one of the links (either green checkmark or red X), it navigates to another page. I know that this is because I am using href and Url.Action.
When a user clicks one of the links, I want to call the /Payment/Set method to update the data (green checkmark to red X and vice versa) and then I want to redraw my datatable (i.e. dataTable.draw()) without navigating from the current page (i.e. Index view). /Payment/Set method updates the data without returning anything (i.e. void).
Update: I tried the following and it almost works, meaning that when I click one of the links, the data is updated and the datatable is refreshed, except it still tries to navigate to another page.
{
data: "HasPayment",
render: function (data, type, row) {
var paymentSet = '#Url.Action("Set", "Payment")?applicationId=' + row.Id + '&year=' + row.Year + '&month=' + row.Month + '&hasPayment=' + data;
if (data) {
return '';
}
return '';
}
},
<script>
function onclickFunction() {
$.ajax({
type: "GET",
url: $(this).attr("href"),
success: function () {
paymentDataTable.ajax.reload();
}
});
}
</script>
If you use an anchor <a> it is obvious that the browser will navigate to another page. That's the actual purpose of the anchor tag.
You should use an AJAX function to call when your button is pressed and at the callback call the reload of the table.
This can be a way:
{
data: "HasPayment",
render: function (data, type, row) {
if (data) {
return '<button class="fas fa-solid fa-check" style="color: green" onclick="setPayment(row.Id, row.Year, row.Month, data)"></button>';
}
return '<button class="fas fa-solid fa-times" style="color: red" onclick="doSomethingElseMaybe()"></button>';
}
}
Then you should create two more functions, one with the AJAX call and one with the table reload to be called as callback.
function setPayment(id, month, year, data){
var url = `Payment/Set?applicationId=${id}&year=${year}&month=${month}&hasPayment=${data}`;
$.ajax({
type: "POST", //OR GET? it depends on your backend
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
reloadTable();
},
error: () => {
console.error("500 Internal Server Error.");}
});
}
Then in the reloadTable function just call the ajax.reload() method of the DataTable api.
for example
function reloadTable(){
datatable.ajax.reload();
}
Here is the documentation of DataTables reload method.
Here is the documentation of JQuery AJAX.
You may have to adapt the example code to your specific backend purpose.

JQuery click 1 does nothing

I have a feeling there is something wrong with my for loop. When my websites event is activated the first time, I get no response. It works as intended every time after that. I have tried tuning the numbers in the for loop looking for mistakes but as far as what I've tried. It works best as is.
For the full app: https://codepen.io/xcidis/full/KvKVZb/
var reference = [];
function random() {
$.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
});
}
$("button").click(function(){
random();
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
Your rest of the code ran before your ajax push the value to reference variable.
https://www.w3schools.com/xml/ajax_intro.asp
You can either put your page rendering code within the ajax or use some tips to run the rederer synchronously
$("button").click(function(){
$.when( $.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div class='tweet' align='left'></div><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
})).then(function() {
console.log(reference)
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
});

Why webkit notification event does not trigger?

I have wrote a webkit notification script on my web app to pull notifications from a database. The code is seen below:
function checkNotifications() {
if (window.webkitNotifications.checkPermission() == 1) {
window.webkitNotifications.requestPermission();
}
else {
$.ajax({
type: "GET",
dataType: 'json',
url: '/check_notifications',
success: function(data){
if (data){
var ticketId = data.ticket_id;
console.log(data);
var comment = data.comment;
var createdDate = data.created_at;
var notificationComment = data.comment;
var notificationId = data.notifcation_id;
var notification = window.webkitNotifications.createNotification('/pt_logo_small.png', 'Project Ticket '+ticketId+ ' Updated!', 'Ticket has been updated. Click here to see!');
notification.show();
console.log(notificationId);
notification.onclick = function(){
this.close();
console.log("NOTIFICATION WAS CLICKED!")
$.ajax({
type: "GET",
dataType: 'json',
url: '/read_notifications/' + notificationId,
success: function(){
window.location = '/pto/' + ticketId;
},
error: function(){
window.location = '/pto/' + ticketId;
}
});
console.log(ticketId, comment, createdDate);
};
}
}
});
}
setTimeout(checkNotifications, 20000);
}
For some reason. I if select another tab, or go to another path inside my webapp, the script still runs to display the notifications, however the .onclick event never triggers.
Anyone have any idea why the even wouldn't trigger?
According to Apple, onclick should bring the page which created the event to focus, which it does. However nothing inside my .onclick function triggers.

jqGrid: grid function executes only once

Sorry, this is a Javascript beginner question. My jqGrid function works fine the first time around, but when I call it a second time, nothing happens, no request is issued. Code fragment:
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var brandsDropdown = document.getElementById("brandsDropdown");
var brandId = brandsDropdown.options[brandsDropdown.selectedIndex].value;
var searchParams = "brandId=" + brandId;
doGrid(searchParams);
});
});
function doGrid(searchParams) {
alert("doGrid, searchParams:" + searchParams);
var url="${pageContext.request.contextPath}/services/setup/project";
var editurl="${pageContext.request.contextPath}/services/setup/project";
$("#projectList").jqGrid({
url: url + "?" + searchParams,
editurl: editurl,
datatype: 'xml',
mtype: 'GET',
...
});
The alert() shows me that doGrid() is really called successfully the second time. So it's really the $("projectList").jqGrid() function that doesn't execute, or fails silently .. Unless I made an obvious mistake in the way I call it?
I think the second time is no longer a need to regenerate the entire Grid. Then you only change the set parameters and grid computing to date. For this you need a trigger("reloadGrid") call.
$(document).ready(function() {
var runonce=false;
$("#submit").click(function(e) {
e.preventDefault();
var brandsDropdown = document.getElementById("brandsDropdown");
var brandId = brandsDropdown.options[brandsDropdown.selectedIndex].value;
var searchParams = "brandId=" + brandId;
doGrid(searchParams);
});
});
function doGrid(searchParams) {
alert("doGrid, searchParams:" + searchParams);
var url="${pageContext.request.contextPath}/services/setup/project";
var editurl="${pageContext.request.contextPath}/services/setup/project";
if (false==runonce) {
$("#projectList").jqGrid({
url: url + "?" + searchParams,
editurl: editurl,
datatype: 'xml',
mtype: 'GET',
...
});
runonce=true;
} else {
$("#projectList").jqGrid({
url: url + "?" + searchParams,
editurl: editurl
}).trigger("reloadGrid");
}

Onclick function on div not working

I have a function for getting records from database on keyup event.
Here is my code:
function displaySearch(key) {
$.ajax({
type:"POST",
url:"searchprofile.php",
data:{
k:key
},
success:function(data){
var details_arr=data.split("+");
$('.searchresult').empty();
for(var i=0;i<details_arr.length-1;i++){
$('.searchresult').append("<div class='profile' id='searchprofile'><img class='profilepic' src='images/profile.jpg'/><div class='doctorname'><div class='pname' onclick='saveName("+details_arr[i]+")'>"+details_arr[i]+"</div></div></div>");
$('.searchresult').show();
$('.searchresult .profile').show();
}
details_arr.length=0;
}
});
}
But i am getting javascript error here saying "Unexpected token ILLEGAL".
How do i give the onclick function with the value of details_arr[i]?
Please help.
As you have jQuery, you really shouldn't inline code. As you see it makes it more difficult to handle quotes inside quoted strings (yes, you're missing quotes around your argument to saveName).
You may do this :
(function(i){
$('.searchresult').append(
"<div class='profile' id='searchprofile'>"
+ "<img class='profilepic' src='images/profile.jpg'/>"
+ "<div class='doctorname'>"
+ "<div id=someId class='pname'>"+details_arr[i] // <- give some Id
+"</div></div></div>"
);
$('#someId').click(function(){saveName(details_arr[i])});
})(i);
$('.searchresult').show();
Note that I used a closure to ensure that i has the needed value in the callback (not the value at end of iteration).
Be careful with the split: on most browsers "+aaa".split('+') makes ["", "aaa"] and as you don't iterate up to the end of the array, this sample string would made you iterate on nothing.
function openNow(x)
{
var pageUrl = '<%=ResolveUrl("~/OnFriends.php")%>'
$.ajax({
type: "POST",
url: pageUrl + '/CreateNew',
data: '{k: "'+ x +'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(data)
{
<---Now Do Your Code Hear--->
}
});
}
CreateNew is my web service what i created in .php file
I would use something like that
bare in mind ID must be unique inside a document (HTML Page)
because the content is generated on the fly; it's better to use the JQuery "on"
$(".pname").on("click", function (event) {
saveName($(this).text());
});
event handler to bind the click event
function displaySearch(key){
$.ajax({
type: "POST",
url: "searchprofile.php",
data: {
k: key
},
success: function(data) {
var details_arr = data.split("+");
var searchResults = "";
for (var i = 0; i < details_arr.length - 1; i++) {
searchResults += "<div class='profile'>" +
"<img class='profilepic' src='images/profile.jpg'/>" +
"<div class='doctorname'>" +
"<div class='pname'>" + details_arr[i] +
"</div></div></div>";
}
$('.searchresult').html(searchResults).show();
}
});
}
$(".pname").on("click", function (event) {
saveName($(this).text());
});
use the Jquery html to replace everything inside searchresult outside the loop that way it
will be called once not details_arr.length - 1 times
you should tell the line at which you are getting error
i think you did not specified you web service in ajax call at...
"url:"searchprofile.php"
Finally got the onclick function working. :)
Instead of appending the div everytime, i just editted my php page by adding the html i needed in the data that is returned in ajax.

Categories

Resources