I want to insert in my page an event that trigger when the window close or change except that in the case that has been triggered by a submit button of a particular submit which bring in an analogus page. I tried the follow but it doesn't work. (prova is the name of submit).
$(window).bind("unload", function (event) {
alert('1');
if (event.target.tagName != "prova") {
alert('2');
var postData = {
'chat_message': "I left"
};
$.ajax({
type: "POST",
dataType: "json",
url: base_url + "chat/ajax_add_message/" + chat_id + "/" + user_id,
data: postData,
success: function (data) {
get_messages();
}
});
}
});
Do you really have HTML element with tag "prova" ?
event.target.tagName != "prova"
Maybe you need to check className or id?
Related
Is there a way I could change the default ajax alert box? I currently have the code below, that deletes a user and reloads the current page. It works, but I would like to add some styling to the alert box that it triggers before the user is actually deleted.
function deleteUser(id) {
var action = confirm("Are you sure you want to delete this student?");
if (action != false) {
$.ajax({
url: '{% url "student-delete" %}',
data: {
'id': id,
},
dataType: 'json',
success: function (data) {
if (data.deleted) {
$("#userTable #user-" + id).remove();
window.location.reload()
}
}
});
}
}
I tried changing the confirm to
function deleteUser(id) {
var action = bootstrap.confirm("Are you sure you want to delete this student?");
if (action != false) {
$.ajax({
url: '{% url "student-delete" %}',
data: {
'id': id,
},
dataType: 'json',
success: function (data) {
if (data.deleted) {
$("#userTable #user-" + id).remove();
window.location.reload()
}
}
});
}
}
This displayed nothing.
You cannot style the custom confirmation box. It varies from browser to browser. If you want something custom you can build out one yourself using HTML and CSS. For example attach click events for yes button and for a no button and based on that you can make the 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.
Hi I'm working on an ajax function in jquery that saves the value of a checkbox. Here is my question, What if the user clicks in multiple times even the saving is not yet finished/success? How can i Prevent the user to tick the checkbox when the form is submitting? Thanks !
Heres my Code Snippet:
$(".chkOverride").click(function (e) {
var userId = $("#UserId").val();
var isChecked = $(this).is(":checked")
$.ajax({
url: "/Worker/Worker?Id=" + Id + "&isChecked=" + isChecked + "&UserId=" + UserId,
type: "post",
success: function (result) {
alert("Success!");
location.reload();
},
error: function () {
}
});
});
You can disable the checkbox before starting the ajax call. You may use the prop() method to do that. Set the disabled property value to true
$(".chkOverride").click(function (e) {
var _this=$(this);
_this.prop('disabled', true);
var userId = $("#UserId").val();
var isChecked = $(this).is(":checked")
$.ajax({
url: "/Worker/Worker?Id=" + Id + "&isChecked=" +
isChecked + "&UserId=" + UserId,
type: "post",
success: function (result) {
alert("Success!");
//No point in enabling as you are going to reload the page
_this.prop('disabled', false);
location.reload();
},
error: function () {
alert("Error :(");
_this.prop('disabled', false);
}
});
});
Have you come across this link:
Inhibit a checkbox from changing when clicking it
You can disable the checkbox using
$this.attr('disabled', 1);
Disable the button before making the Ajax call.
I want to pass the link on textbox blur function.
Jquery code
<a id="checkEmail" href="#" ></a> | <a id="getCandidate"></a> */* this is the link for get the profile details*/*
<script type ="text/javascript">
$('#getCandidate').text('Get Profile') // Sets text for email.
.attr('href', '#');
$("#Email").blur(function () {
$('#checkEmail').trigger('click');
//$('#checkEmail').trigger('GetCandidateDetail?validateEmail=' + $('#Email').val());
$('#getCandidate').text('Get Profile')
.attr('href', 'GetCandidateDetail?validateEmail=' + $('#Email').val());
});
$(document).ready(function () {
$('#checkEmail').click(function () {
var name = $('#Email').val();
var data = 'validateEmail=' + name;
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: data,
success: function (data) {
alert(data);
}
});
return false;
});
});
</script>
Html code
<%: Html.TextBox("Email",Model.Email, new {#title="Enter the Candidate Email Id"})%>
<a id="checkEmail" href="#" ></a> | <a id="getCandidate"></a>
In the above code when I type the email id in textbox it triggers email id is registered or not. Then I give one more link getdetails. If I click that link then the profile will come by using the link GetCandidateDetail?validateEmail=' + $('#Email').val()).
But Now I want when I type the email id in textbox, if exists means it will load the link GetCandidateDetail?validateEmail=' + $('#Email').val())automatically otherwise false. How to do this? Help me to come out this issue?
You can do just like this:
$(document).ready(function() {
$("#Email").on('blur', function() {
// Check mail on blur
var email = $(this).val();
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: {validateEmail:email},
success: function(data) {
// handle your response
}
});
});
});
function verify() {
var name = $('#Email').val();
var data = 'validateEmail=' + name;
$.ajax({
type: "GET",
url: "ValidateCandidate",
data: data,
success: function (data) {
alert(data);
return false;
});
}
$("#Email").blur(function(){verify();)
$("#checkEmail").click(function(){verify()})
thats it !!
I am having strange behaviour when using jquery.on().
Basically, just trying to create a newsletter signup form (can be dynamically generated and not there on initial DOM load) and pass the details through in Ajax but it is not registering the first click on the submit button meaning that to successfully submit, the user has to click twice (only seeing the success message and 'subscribe' post on 2nd click).
The html:
<div class="newsletter-widget grid-item masonry-brick">
<input name="Email" type="email" placeholder="Please enter your email" required />
<input type="submit" value="Subscribe" class="newslettersubmit"/>
and the javascript (in document ready);
var newsletterFocus = $('.newsletter-widget').find('input[type=submit]');
$(document).on('submit', newsletterFocus, function (e) {
e.preventDefault();
var newsletterLinks = newsletterFocus;
DD.newsletter.behavior(newsletterLinks);
});
and the functions within an object that are called;
DD.newsletter = {
behavior: function (item) {
item.click(function (e) {
e.preventDefault();
var where = $('.newsletter-widget').find('input[type=submit]').parents('section').attr('id');
var email = $(this).siblings('[name$=Email]'),
emailVal = email.val();
DD.newsletter.subscribe(email, emailVal, where);
});
},
subscribe: function (self, email, where) {
$.ajax({
type: "POST",
data: '{"email":"' + email + '", "method":"' + where + '"}',
url: '/Subscriber/Subscribe',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
self.val(response);
},
failure: function (msg) {
self.val(msg);
}
});
},});
I've tried using 'click' as the action for on() but this registers an event on each click and i get thousands of forms submitted!
Any help appreciated!
Change the div container to a form element:
<form class="newsletter-widget grid-item masonry-brick">
You'll want to register the submit event to the form, not the input field. Here's a quick refactor of your form submission:
$(document).on('submit', '.newsletter-widget', function (e) {
e.preventDefault();
DD.newsletter.behavior(); //Submit the form via AJAX
});
If you wanted to hook this up to your behavior method, just unwrap the click:
behavior: function () {
var where = $('.newsletter-widget').find('input[type=submit]').parents('section').attr('id');
var email = $(this).siblings('[name$=Email]'),
emailVal = email.val();
DD.newsletter.subscribe(email, emailVal, where);
}
The first click on the button will cause the behaviour click event handler to be bound to the button. Bind the behaviour directly instead of in the click event handler.
Replace this:
var newsletterFocus = $('.newsletter-widget').find('input[type=submit]');
$(document).on('submit', newsletterFocus, function (e) {
e.preventDefault();
var newsletterLinks = newsletterFocus;
DD.newsletter.behavior(newsletterLinks);
});
with:
DD.newsletter.behavior($('.newsletter-widget input[type=submit]'));
It should probably (I think) be something like this:
DD.newsletter = {
behavior: function (item) {
var where = $(item).parents('section').attr('id');
var email = $(item).siblings('[name$=Email]'),
var emailVal = email.val(); // why were you declaring this without 'var'?
DD.newsletter.subscribe(email, emailVal, where);
},
subscribe: function (self, email, where) {
$.ajax({
type: "POST",
data: '{"email":"' + email + '", "method":"' + where + '"}',
url: '/Subscriber/Subscribe',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
self.val(response);
},
failure: function (msg) {
self.val(msg);
}
});
},});