So basically I have a button on my html which has a small js on it which onclick turns the button green and when clicked again turns the button grey to make it feel like its turning on and off. Here is the JS and the HTML code for the button
<script>
$('#button1').click(function() {
//Now just reference this button and change CSS
$(this).toggleClass('buttonClassA');
});
</script>
<button type="button" class="col-md-2 notice-btns btn " id="button1">
<span class="glyphicon glyphicon-phone" aria-hidden="true"></span>
<p data-bind="if : $data.emailNotification == 1 ">On</p>
<p data-bind="if : $data.emailNotification == 0 ">Off</p>
</button>
I have two knockout function which needs to be called when the button is clicked
which are
self.emailNotification = ko.observable();
self.turnOnEmailNotification = function () {
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/checkNotificationValue/' + auth + "/" + self.emailNotification(1) ,
contentType: 'application/json; charset=utf-8'
})
.done(function(notifications) {
self.emailNotification.removeAll();
self.emailNotification.push(notifications);
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
};
self.turnOffEmailNotification = function () {
$.ajax({
type: 'POST',
url: BASEURL + 'index.php/myprofile/checkNotificationValue/' + auth + "/" + self.emailNotification(0) ,
contentType: 'application/json; charset=utf-8'
})
.done(function(notifications) {
self.emailNotification.removeAll();
self.emailNotification.push(notifications);
})
.fail(function(xhr, status, error) {
alert(status);
})
.always(function(data){
});
};
I tried the data-bind checked but then i lose the buttons so need help to call both the ajax calls
$root.turnOnEmailNotification
and
$root.turnOffEmailNotification
in the same button and so I can give it a feeling its turning on and off.
Checked isn't a valid attribute for button element .Instead you can use click to achieve the same via toggling .
view:
<button type="button" data-bind="click:tgle,style:{'background-color':emailNotification()==0 ? 'red':'green'}">
<p data-bind="text:$data.emailNotification() == 1 ? 'On' : 'Off' "></p>
</button>
viewModel:
var ViewModel = function() {
var self = this;
self.emailNotification = ko.observable(0);
self.tgle = function() {
self.emailNotification(self.emailNotification() == 1 ? 0 : 1)
switch (self.emailNotification()) {
case 0:
console.log('turn off ajax fired');
//turnOFFEmailNotification
//$.ajax({
// Do ajax stuff
//});
break;
case 1:
console.log('turn on ajax fired');
//turnOnEmailNotification //default off
//$.ajax({
// Do ajax stuff
//});
break;
default:
break;
}
}
};
ko.applyBindings(new ViewModel());
working sample up for grabs
Related
My page has a button that calls a Razor Page page handler to delete the associated item.
<a class="delete-item" data-id="#item.Id" asp-page-handler="delete" asp-route-id="#item.Id"><img src="/images/delete.png" title="Delete" /></a>
I've defined a Javascript click handler. I need that handler to return false if the item should not be deleted.
$('.delete-item').on('click', function (e) {
var id = $(this).data('id');
var tr = $(this).closest('tr');
var td = tr.find('.item-description');
// Get number of lease details for this lease
$.ajax({
type: 'GET',
url: '?handler=LeaseDetailCount',
contentType: 'application/json',
dataType: 'json',
data: { 'leaseId': id },
})
.done(function (response) {
var description = 'Delete "' + description + '"? Are you sure? This cannot be undone.\r\n\r\n';
if (response.count == 0)
description += 'This lease has no lease details.'
else
description += 'WARNING: This lease has ' + response.count + ' lease detail(s).';
if (!confirm(description))
return false;
})
.fail(function (response) {
alert(response.responseText);
})
//.always(function (response) {
//});
}
The problem, of course, is that the AJAX call is asynchronous. And so it returns before my confirmation is displayed.
How can I get the code above to work as I want?
If you not wish to set asp-page-handler for the anchor tag, it is possible. As you mentioned
AJAX call is asynchronous
we can't predict which result come first, href navigation or onclick AJAX response
<a class="delete-item" data-id="#item.Id"><img src="/images/delete.png" title="Delete" /></a>
In AJAX .done event, If the confirmation is OK page redirect to delete handler
window.location.href = "/?id=" + id + "&handler=delete";
.done(function (response) {
......
.......
if (!confirm(description))
return false;
else
window.location.href = "/?id=" + id + "&handler=delete";
})
I load replies to comments asynchronously in php like in youtube comments.
The ajax handler for forms (ie reply forms) loaded like this is not working. e.preventDefault() is not working. The forms are submitted to the action page itself and page is redirected to action url. If i edit a reply. It works but page is redirected to the action url. This happens only for the ajax loaded replies. The same handler is used for regular comments and it works fine.
A comment :
A comment with loaded replies :
When a reply is edited it just goes to /path/to/submit.php and shows the value of json output like this
result on submitting a reply form
Ajax to show or hide replies:
//load or hide replies
function loadmore(id) {
var val = $('#' + id).data("value");
var count = $('#' + id).data("count");
$.ajax({
type: 'post',
url: '/path/to/submit.php',
data: {
replyof: val
},
success: function(response) {
var content = document.getElementById("show" + val);
content.innerHTML = response;
var clicknum = $('#' + id).data("clicknum");
$('#' + id).data("clicknum", 2);
if (!$("#show" + val).is(":hidden") && clicknum != 1) {
document.getElementById(id).innerHTML =
' View all ' + count + ' replies <i class="fas fa-angle-down"></i>';
$("#show" + val).hide();
} else {
document.getElementById(id).innerHTML =
'Hide all replies <i class="fas fa-angle-up"></i>';
$('#show' + val).show();
}
}
});
}
I use the same class for comments as well as replies and ajax submit the form to the same page /path/to/submit.php using
eg
<form class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
The form handler
$(".replyform").submit(function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});
The .replyform render by ajax so use on instead of traditional way
$(document).on("submit", ".replyform",function(e) {
var URL = $(location).attr('href');
$.ajax({
async: true,
type: "POST",
url: $(this).attr('action'),
data: $(this).closest('form').serialize(),
success: function(data) {
if (data.result === 1) {
window.location = "/login";
} else if (data.result === 2) {
alert('Some error occured.Please try Later');
} else if (data.result === 3) {
replyer(data.comment);
$('body').load(URL);
} else {
$('body').load(URL);
}
},
dataType: "json"
});
e.preventDefault();
});
I think your calling your form wrong. You need an id attribute. I don't think you can call it by it's class name like that.
<form id="myForm" class="replyform" action="/path/to/submit.php">
...
<button type="submit">Delete</button>
...
</form>
$("#myForm").submit(function(e) {
...rest of script.
When you click the button when the display of a content, and then click the button when the content hidden, and then click the button when the show repeat, I do not know how to solve the problem? Big god can help solve? Thank you very much!
HTML file
<button id="liuyan" type="button" class="btn btn-primary btn-lg">my click</button><div id="mydiv2">
JavaScript file
$("button#liuyan").on("click", function(e) {
e.preventDefault();
$.ajax({
url: 'http://localhost:3000/api/comment',
method: 'GET',
dataType: "jsonp",
async: false,
}).done(function(data, textStatus, jqXHR) {
var mydiv2 = $("#mydiv2");
if (mydiv2.css("display") === "none") {
mydiv2.show();
var mycode = document.createElement('div');
mycode.innerHTML = '<pre><code data-language="json">' + JSON.stringify(data, undefined, 2) + '</code></pre>';
Rainbow.color(mycode, function() {
document.getElementById('mydiv2').appendChild(mycode)
});
} else {
mydiv2.hide();
}
console.log(data);
console.log(jqXHR.responseText);
});
});
I dont have AJAX URL. I gave dummy data. It should work.
Every time, while showing you are appending the content with existing content. So it will repeat. So you have to remove the existing content in div and append it to div.
Add this line before appending
document.getElementById('mydiv2').innerHTML = '';
Then existing content will get cleared.
$("button#liuyan").on("click", function(e) {
e.preventDefault();
data = {
"name":"hello"
}
var mydiv2 = $("#mydiv2");
if (mydiv2.css("display") === "none") {
mydiv2.show();
var mycode = document.createElement('div');
mycode.innerHTML = '<pre><code data-language="json">' + JSON.stringify(data, undefined, 2) + '</code></pre>';
//Rainbow.color(mycode, function() {
document.getElementById('mydiv2').innerHTML = '';
document.getElementById('mydiv2').appendChild(mycode)
//});
} else {
mydiv2.hide();
}
// console.log(data);
// console.log(jqXHR.responseText);
// });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="liuyan">Click</button>
<div id="mydiv2"></div>
Another Way:
You can make a call on ready function and show and hide when click on the button
My code have a button that can print a file to a pdf form (it works fine). Now I want to add another button that just print it in a html page. I have added the new button and it works too.
The problem is that now when I have created a new button, it will now overwrite it method on the old one. So both button will do the same thing. (Both print it in html form)
Here are some part of my code:
The function for the invoice datatable looks like this:
function invoiceDatatable(tableId, extras, url, optionParser) {
var options = $.extend(true, {}, documentOptions, {
tableId: tableId,
url: url || '/api/invoices/?type=i',
extras: extras
});
Here i create both buttons, with their url - the code always use the last created one:
options.tasks.push({
url: '/print_to_pdf',
queryParam: 'documents',
label: '<i class="fa fa-print"></i> Print pdf'
});
options.tasks.push({
url: '/print_to_html',
queryParam: 'documents',
label: '<i class="fa fa-print"></i> Print html'
});
Finally the code for the tasks of the buttons looks like this:
for (var i = 0; i < self.tasks.length; i++) {
var task = self.tasks[i];
var taskButton = $('<button type="button">' + (task.label || task) + '</button>');
taskButton.addClass('btn btn-default');
$(taskButtons).append(taskButton);
if (task.action) {
// An entry point for custom actions
$(taskButton).click(function(){
task.action(self.selected);
})
} else {
$(taskButton).click(function () {
var downloadUrl = task.url + '?' + task.queryParam + '=' + self.selected.join(',');
downloadUrl += "&ordering=" + self.ordering()['ordering'];
$(infoPanel + ' .alert').remove();
$(infoPanel).append('<div class="alert alert-info">' +
'<i class="fa fa-circle-o-notch fa-spin"></i> Building document' +
'</div>');
$.ajax(downloadUrl, {
success: function (data) {
function doPoll(url, success) {
$.ajax(jobUrl, {
type: "HEAD",
success: function (pdfData, status, xhr) {
if (xhr.status == 202) {
setTimeout(function () {
doPoll(url, success)
}, 2000);
} else {
success()
}
}
});
$.ajax(url, function (data) {
alert(data); // process results here
setTimeout(doPoll, 5000);
});
}
How do I fix my code so that each button have its own functionality?
edit
I think it is the push method that overwrites the action. What do you guys think?
I am submitting a form with JavaScript.
Here is my form:
<form id="rolesSelectForm" class="stdform" action="" onsubmit="return submitForm()">
<p>
<label>Select User</label>
<span class="field">
<select name="selectUser" id="selectUser">
#foreach (var item in Model.Users)
{
<option value="#item.Id">#item.UserName</option>
}
</select>
</span>
</p>
<p class="stdformbutton">
<button class="submit radius2" type="submit">Save</button>
</p>
And here is my script:
<script>
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.userId = jQuery('#selectUser').val();
model.rolesList = usersRoles;
console.log('model: ' + 'user: ' + model.userId + 'roles: ' + model.rolesList);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { showSuccessMessage(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
}
//Shows the success message
function showSuccessMessage(data) {
alert(data);
}
Now when I click the button, the page does refresh and I never get my alert.
In chrome its at least makes the ajax post request but in Firefox, it just reloads the page before the post is even made.
From what I read if I made my form return the JavaScript function, it would not reload. However this is not my case.
From what I read if I made my form return the java script function it would not reload.
No. You have to return false.
This is typically done by returning the return value of the function, and then returning false from that function. A lot of the time this will be done conditionally (since often you will be testing the user input to make sure it is OK before allowing the form to submit.)
You don't have a return statement in your function.
Please add return false in function
function submitForm() {
var usersRoles = new Array;
jQuery("#dualSelectRoles2 option").each(function () {
usersRoles.push(jQuery(this).val());
});
var model = new Object();
model.userId = jQuery('#selectUser').val();
model.rolesList = usersRoles;
console.log('model: ' + 'user: ' + model.userId + 'roles: ' + model.rolesList);
console.log('JSON: ' + JSON.stringify(model));
jQuery.ajax({
type: "POST",
url: "#Url.Action("AddUser")",
dataType: "json",
contentType: "application/json",
data: JSON.stringify(model),
success: function (data) { showSuccessMessage(data); },
failure: function (errMsg) {
alert(errMsg);
}
});
return false;
}