The short question is when I fill a <div> containing a type=submit button the .click(function(){...} function fails.
What I'm doing is this, #formDialogButton opens #accordion populated by .ajax() containing #userForm with an input type=submit. When client clicks submit it is supposed to fire .ajax() where php does database stuff and returns one of the #userform.
$(".formDialogButton").click(function(){
var userDialog = "#" + this.id + "Dialog";
$("#userForm, #siteForm, #limitForm").html("<img src='ajax-loader.gif' />");
$("#userForm, #siteForm, #limitForm").load("ajax.php", {op: "forms"}, function(responseTxt,statusTxt,xhr){
$("#userForm").html($("#user").html());
$("#siteForm").html($("#site").html());
$("#limitForm").html($("#limit").html());
if(statusTxt=="success") {
$(userDialog).dialog({
autoOpen: false,
draggable: true,
modal: true,
resizable: true,
width: 700,
position: { within: "#mainContent" }
});
$(userDialog).dialog("open");
$( "#accordion").accordion({
collapsible: true,
heightStyle: "content",
});
};
if(statusTxt =="error")
alert("Error: "+xhr.status+": "+xhr.statusText);
});
});
This is working and returns a <input class="submitAndReturn" type="submit" value="Submit" /> in the form. But I can't "find" it to do anything.
$(".submitAndReturn").click(function() {
alert ('this is where I call my regular .formSubmitButton and let success: function() do a .formDialogButton ');
});
I'm a total self taught amateur so please forgive me and try to help. Thanks
Sounds like you are trying to add the click event before the element is loaded on the page. Change
$(".submitAndReturn").on("click", function() {
alert ('as .submit and return is dynamically loaded. so, use on function');
});
to
$(document).on("click", ".submitAndReturn", function(e) {
e.preventDefault(); //cancel the click action if needed
alert ('as .submit and return is dynamically loaded. so, use on function');
});
$(".submitAndReturn").on("click", function() {
alert ('as .submit and return is dynamically loaded. so, use on function');
});
What I'm doing is this, #formDialogButton opens #accordion populated by .ajax() containing #userForm with an input type=submit
If I understand it correct .formDialogButton DOM element is getting loaded in .ajax() callback event.
If you are loading the javascript in question above in header or at the page end, most likely the $(".formDialogButton").click(function() event is not getting attached to DOM.
This happens because the script has already fired before the AJAX has fetched the required DOM to which event has to be attached. You would need to attach the event in .ajax() success callback. Something like
$.ajax({
url: 'YOUR_URL_TO_FETCH_FORM',
success: function(data) {
// associate click
$(".formDialogButton").click(function() // rest of the code
}
});
Related
I have created a button. When I click the button, I want it to run a PHP file and display alert. Here's what I'm trying:
HTML:
<button id="testid" style="height:20px; width: 50px; cursor: pointer" onclick="logoutfunc()">Logout</button>
JavaScript:
function logoutfunc() {
$(document).ready(function() {
$("#testid").click(function() {
$.ajax({
url: 'logoutt.php',
type: 'post',
success: function(result11) {
//$(location).attr('href', 'login.php');
alert(result11);
},
error: function() {
alert("no");
}
});
});
});
}
logoutt.php
<?php
$a="Hello";
echo $a;
?>
Now the problem is that when I click the button first time, it doesn't display the alert. But when I click it again, it displays same alert twice. And when I click it again, it alerts 3 times and so on. What wrong have I written?
You are binding the click handler inside the inline event handler, thus when the button is clicked first time the event handler is attached. So it works second time.
Get rid of the inline click handler. just bind the event handler using jQuery
$(document).ready(function() {
$("#testid").click(function() {
$.ajax({
url: 'logoutt.php',
type: 'post',
success: function(result11) {
//$(location).attr('href', 'login.php');
alert(result11);
},
error: function() {
alert("no");
}
});
});
});
Why are you again and again binding the same event?
....onclick="logoutfunc()"...
Remove this part from your HTML and in your javascript remove the function which surrounds the document ready handler.
$(document).ready(function(){
$("#testid").click(function(){
// your ajax code.
});
});
this is my server-side code:
modify_emp.php
<?php
echo $_POST[id];
?>
And this is my Javascript in my html page:
<script>
$(document).ready(function () {
var alreadyClicked = false;
$('.element').hover(
//mouseenter function
function(){
$('.element').click(
function(){
$(this).css("color","blue");
var objName = $(this).attr('name');
var objColumn = $(this).attr('id');
if(!alreadyClicked){
alreadyClicked = true;
$(this)
.prepend('<form method="POST" class="newInput"><input type="text" name="newInput" style="width:140px"></input></form>');
var elemento = $(".newInput");
var position = elemento.position();
$(".newInput").css({
'position': 'absolute',
'top': position.top + 15,
'opacity':0.9,
'z-index':5000,
})
.focus();
//on enter keypress
$(document).keypress(function(e) {
if(e.which == 13) {
$.ajax({
url: 'modify_imp.php',
type: 'post',
data: { id : objName, column : objColumn },
success: function(data, status){
$("#debug").html(data);
}
});
}
});
} //if (!alreadyClicked) end
}); //end mouseenter function
},
//mouseleave function
function () {
alreadyClicked = false;
$(this).css("color","red");
$(".newInput").remove();
}
); //end .hover
});
The debug is a <div id="debug"> </div> at the end of my html page where i want to show my response from server. When i press 'ENTER' I can actually see the value for 0.1s inside that div, but then it disappears.
I already tried to pass the return value to a local or global variable but it didn't work.
For some reason the value inside response is lost after 0.1s, even if i pass it to another variable elsewhere.
Can someone explain me why and how can i "store" the server response?
EDIT: Just edited with my entire <script>
Since you see the result momentarily, I'm going to hazard a guess that you have a form element on your page and when you hit return, it's actually submitting the form. You briefly see the result of the ajax operation and then your form submits causing the page to reload as a new blank page. This is a common issue and always has these same symptoms.
You can either remove the form element or block the default submission of the form with javascript.
If you show us more of your actual HTML, we could help more specifically with how to prevent the form from submitting.
You can solve this by calling the function in the form tag i.e,
<form action="javascript:AnyFunction();">
your code goes here
.
Another way would be to assign a BUTTON to trigger the ajax, and set the button outside of the FORM
I call content for modal dialog from ajax
$.ajax({
url: "/Clerk/PauseServiceDialog",
success: function (data) {
$("body").append(data);
$("#pauseServiceDialog").modal({ keyboard: false });
}
});
When I close modal I use this code
$(document).on('hidden.bs.modal', ".modal", function (e) {
this.remove();
});
In firebug I see html code is deleted. But if I again call dialog and use some event I get 2 event. How I understand modal dialog do not correct deleted from DOM.
I found answer how fix duplicate event.
$(document).on('hidden.bs.modal', ".modal", function (e) {
var name = "#" + $(this).find("button.btn-primary").attr("id");
$("body").off("click", name);
$(this).remove();
});
You can hide modal by code
$("#pauseServiceDialog").data('bs.modal').hide()
P.S. sorry, i didn't understand notation $(document).on('hidden.bs.modal' in general - you should delete modal element AND object which handle its events ( it stored at $("#pauseServiceDialog").data('bs.modal') )
I have a jquery ui dialog that loads its content via ajax:
$('#register').click(function(e) {
var tag = $('<div></div>');
$.ajax({
url: 'signup.html',
success: function(data) {
tag.html(data).dialog({modal: true}).dialog('open');
}
});
e.preventDefault();
return false;
});
I have a second script within the content that is supposed to close the dialog when the submit button is pressed
$(function() {
$('form #submit').click(function(e) {
$(this).parents('.ui-dialog').dialog('close');
e.preventDefault();
return false;
});
});
When i click the submit button, i get the error:
Uncaught Error: cannot call methods on dialog prior to initialization; attempted to call method 'close'
What is it that i am missing to allow me to close the dialog from the content that has been loaded via ajax?
You have to call dialog('close') on the element where dialog('open') was called before. You're calling the function on$('.ui-dialog')instead of$('.ui-dialog ...')`.
You should define id or class for the tag element in your code:
var tag = $('<div id="signup-id"></div>');
Then find the correct element in click handler like this:
$(this).parents('.ui-dialog').children('#signup-id').dialog('close');
Note: You can find #signup-id in click handler directly like $(this).children('#signup-id') if you're sure that signup.html never contains element with signup-id id.
Define you tag dialog in html
<div id="tag_dialog" style="display:none">
</div>
then on document ready:
$(document).ready(function(){
$('#tag_dialog').dialog({
modal:true,
autoOpen:false,
//you could give some other options such as width, height .....
});
$('#register').click(function(e) {
$.ajax({
url: 'signup.html',
success: function(data) {
$('#tag_dialog').html(data).dialog('open');
}
});
e.preventDefault();
return false;
});
$('form #submit').click(function(e) {
$('#tag_dialog').dialog('close');
e.preventDefault();
return false;
});
});
I have the following code for the jQuery validation plugin.... basically on submit, I slide everything up & fade it out... the only problem is, if you're quick enough, you can submit the form multiple times. How can I make sure that any presses of the enter key on the input (or clicks on that submit button) will not submit further?
Basically what happens, is that the form will load up the url in the action attribute when no javascript is there, so purely unbinding doesn't work... (even if it did, I can always press enter / click fast enough to get it to do a couple more....)
jQuery('.desired').validate({
debug: true,
rules: {
email: {
required: true,
email: true
}
},
wrapper: "div",
messages: {
email: "Please enter a valid email address."
},
errorPlacement: function(error, element) {
error.hide().appendTo(element.parent()).hide().slideDown();
},
errorClass: 'help-text',
submitHandler: function(form) {
var $ = jQuery;
var url = $(form).attr('action');
var query = $(form).serialize();
$.ajax({
url: url,
type: "POST",
data: query,
success: function() {
$("<p class='help-jquery'><b>Thanks</b>")
.insertAfter(jQuery(form))
.css('height', function(i,h) {
$(this).hide()
return h;
});
// $(form).css('height', $(form).height());
$(form).slideUp('slow');
$(form).fadeOut({ queue: false, duration: 'slow' });
// $('.help-jquery').fadeIn('slow');
$('.help-jquery')
.css('opacity', 0)
.slideDown('fast')
.animate(
{ opacity: 1 },
{ queue: false, duration: 'slow' }
);
//$('.desired submit').click(function(){
//return false;
//});
},
error: function() {
console.log('Error: did not submit properly');
},
complete: function(e) {
//$('.desired').unbind('submit');
//e.preventDefault();
//return false;
}
});
},
success: function(error,element){
},
highlight: function(error){
// This empty function needs to be here for this to work
}
});
You're on the right track with unbind(), it solves half of your problem because it will effectively suppress validation on form submission.
To solve the second half, you only have to neuter the form's submit event after unbinding, by registering the appropriate handler:
$(form).unbind("submit").submit(function() {
return false;
});
Use a boolean variable, like this:
var didValidate = false;
if(!didValidate) {
jQuery('.desired').validate({
//... your code here
});
}
In your AJAX success function, set didValidate to true.
Have a variable that is 1 or 0. before you do any validation, check that the variable is equal to 0. If it isn't 0, do nothing. If it is, continue. Once the validation passes, set the variable to 1 so that the validation cannot occur again.
Use event namespaces:
The name following the '.' let's you target handlers more specifically.
This at the top of the submit handler:
$(form).bind('submit.temp_submit_hold', function(e){
e.preventDefault();
e.stopPropagation(); //added this in case the plugin's handler func uses bubbling
return false;
} );
This at the top of the complete callback for the ajax call:
$('.desired').unbind('submit.temp_submit_hold');
A little more explanation after seeing your comments in complete. The time to preventDefault is immediately after your onsubmit handler starts working. On complete is when you want to enable it again. So we bind a func that stops it with prevent default and then unbind it to toggle behavior. I also added stopPropagation in case the plugin uses delegation/bubbling.
Probably the simplest is to add something like this to your submithandler
submitHandler: function(form) {
var $ = jQuery;
if ( $.data(form, "submit") ) > "" return false;
$.data(form, "submit", "in progress");
// .. the rest of your handler
}
If you want to allow the form to submitted again later, remove the .data() on success.
Use the .destroy() method.
This question and its answers are quite old. So since that time, the developer has added a .destroy() method to detach the validation plugin from the form.
Destroys this instance of validator freeing up resources and unregistering events.
// Initialize the validation plugin on your form
var validator = $("#myform").validate();
// Remove validation from your form
validator.destroy();
// After this point `#myform` is back to its original state without validation.
https://jqueryvalidation.org/Validator.destroy/
To stop multiple submissions, disable the submit button within the plugin's submitHandler function. (The submitHandler only fires when the form is valid and you've already clicked the submit button.)
submitHandler: function(form) {
// validation & submit success, so disable submit button
$("#yourSubmitButton").prop('disabled', true);
// your ajax code here
return false;
}