I have a page where almost every click is handled by delegate().
http://itsneworleans.com/shows/midnight-menu-plus-1/blogs/after-midnight?preview=1
I set up jQuery validate like so
$(document).ready(function(){
$(".commentform form").validate({
rules: {
antispam: { equalToParam: "INO" }
}
});
jQuery.validator.addMethod("equalToParam", function(value, element, param) {
return value == param;
},
"Anti-spam field does not match requested value.");
});
if I check in console with
$.validator.methods['equalToParam']
I get back
function (value, element, param) { return value == param; }
so that looks good.
The validation works on the form submission BUT the equalToParam method has no effect. Only the "required" events occur for it.
The field HTML is
<input name="antispam" type="text" class="required" id="antispam" size="5" />
Where am I going wrong?
EDIT Here is whole form code (generated from PHP script and added to page via AJAX):
<? if ($post = (int) $_POST['pID']) { ?>
<div class="commentform">
<form>
<div class="commenttext">Comment:<br>
<textarea name="comment" class="required"></textarea>
</div>
<div class="commenttext">Your name:<br>
<input type="text" name="name" class="required">
</div>
<div class="commenttext">Your email (will not be publically visible):<br>
<input type="text" name="email" class="required email">
</div>
<div class="commenttext">Type the letters INO here to help us beat spam!<br>
<input name="antispam" type="text" class="required" id="antispam" size="5" />
</div>
<div class="commenttext">
<input type="button" name="submitcomment" class="submitcomment" value="Submit Comment">
<input type="hidden" name="post" value="<?=$post?>">
<? if ($parentComment = (int) $_POST['cID']) { ?>
<input type="hidden" name="parent" value="<?=$parentComment?>">
<? } ?>
</div>
</form>
</div>
<? } ?>
EDIT AGAIN And here's the click delegation code...
$("body").delegate(".submitcomment", "click", function(e) {
e.preventDefault();
var theform = $(this).closest("form");
console.log('Posting comment');
if ($(".commentform form").valid()) {
$.ajax({
type: "POST",
url: "/addComment.php",
data: theform.serialize()
}).done(function(html) {
if (html == 'OK') {
$(theform).html("<div class='commentposted'>Your comment has been received. Thank you. A moderator will review it for public viewing.</div>");
} else {
alert(html);
}
});
}
});
EDIT Here is the code which populates the form into the space where the Reply to Post link was:
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
});
When you need to apply the .validate() method to more than one form, you must wrap it within a jQuery .each().
$(".commentform form").each(function() {
$(this).validate({
rules: {
antispam: {
equalToParam: "INO"
}
}
});
});
EDIT:
You need to initialize the plugin AFTER the form is inserted into the page. Assuming this code properly inserts the form... put your .validate() call as the last item inside...
$("body").delegate(".getcommentform", "click", function(e) {
e.preventDefault();
var pIDval = $(this).attr("data-pid");
var cIDval = $(this).attr("data-cid");
var thebox = $(this).closest("div.commentformcontainer");
console.log('Getting comment form');
$.ajax({
type: "POST",
url: "/commentForm.php",
data: { pID : pIDval, cID : cIDval }
}).done(function(html) {
thebox.html(html);
});
$(".commentform form").validate({ // <- initialize plugin AFTER form is inserted
// your rules & options
});
});
EDIT 2:
Include the equalToParam function someplace on your page within a DOM ready event handler.
Related
I am trying to submit a form on keyup, sort of a keylogger effect. Here is my attempt -
php loop form -
<form method="post" id="'.$vid.'" class="note-form">
<textarea id="'.$vid.'" name="quicknote" value="'.$quick_note.'" placeholder="add a quick note" class="quicknote">'.$quick_note.'</textarea>
<input type="hidden" name="tac" value="'.$vid.'"/>
</form>
$vid is the unique id for each form that im passing from the DB.
JS file -
// Capture keyup from textarea to submit form
$('.quicknote').bind('keyup', function() {
var id = this.id;
var formID = "#"+id;
$(formID).delay(200).submit();
});
$(formID).submit(function(e) {
var url = "ready-data/submit-note.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
// Do something
}
});
e.preventDefault();
});
I use the same ID for the form and the inputs but the form isnt submitting. I can submit if I use the form class note-form but it submits all forms. I cant make formID a global variable to pass to the ajax function also. What is the correct way to do this?
Your form id and textarea id are same that's why its causing problem . Instead you can use
$(this).closest('form') this will get closest form from textarea then you can submit only that form.
Demo Code :
$('.quicknote').bind('keyup', function() {
var selector = $(this).closest('form') //get closest form
$(selector).delay(200).submit(); //submit that.
});
$("form").submit(function(e) {
console.log("data to send --> " + $(this).serialize())
var url = "ready-data/submit-note.php";
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data) {
// Do something
}
});
e.preventDefault();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" class="note-form">
<textarea id="1" name="quicknote" value="somethings..." placeholder="add a quick note" class="quicknote">somethings..</textarea>
<input type="hidden" name="tac" value="1" />
</form>
<form method="post" class="note-form">
<textarea id="2" name="quicknote" value="somethings" placeholder="add a quick note" class="quicknote">somethings...</textarea>
<input type="hidden" name="tac" value="2" />
</form>
In a Tinymce textarea, it forces me to double click submit form. In the first send "var a" is empty, in the second click if you have the data and it is sent correctly. How can it be solved?
<script src="https://cdn.tiny.cloud/1/zgxpx6ymtwpuc7yy5x3wuic7eu7ughi6w7q98msfnxmbcpjp/tinymce/5/tinymce.min.js" referrerpolicy="origin"></script>
<script>
tinymce.init({
selector: '#comment',
});
</script>
<script type="text/javascript">
function FQB() {
var a = document.forms["Formularioqr"]["comment"].value;
if (a == null || a == "") {
alert(a);
return false;
}else{
a = a.replace(/\r?\n/g, '<br />');
$.ajax({
type: "POST",
url: "send-email-manual-envio.php?mesaje=" + a + "&correo=<?php echo $correo;?>" ,
dataType: "json",
success: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML =" Enviado Con exito ";
},
error: function() {
document.getElementById("Formularioqr").reset();
document.getElementById("showtextqr1").innerHTML = " ERROR!!";
}
});
}
}
</script>
<form method="POST" autocomplete="off" id="Formularioqr" name="Formularioqr" onsubmit="return FQB()">
<div class="form-group">
<label for="comment">Mesaje:</label>
<textarea class="form-control" rows="12" id="comment" name="comment"></textarea>
</div>
<p id="showtextqr1"></p>
<input type="submit" value="Enviar">
</form>
I haven't tried it, but i would guess, that '.value' isn't working properly for tinymce textareas.. the tinymce has an dedicated function to get the content. See https://www.tiny.cloud/blog/how-to-get-content-and-set-content-in-tinymce/
I would suggest, trying this way instead this var a = document.forms["Formularioqr"]["comment"].value;
I have an input field through which i am getting the value that user enters, although i am able to display it but instead of displaying it, i wish to store the user entry in a variable and then use it to get data from database. Below is the code that i have so far (#JSFiddle)
<form action="save.php" method="post">
<input type="text" value="" id="test">
<p></p>
<input type="text" value="">
<button type="button">submit</button>
</form>
<script>
$( "input" )
.keyup(function() {
var value = $( this ).val();
$( "p" ).text( value );
})
.keyup();
</script>
E.g: if a user enters 12 in input box and then click enter button, then 12 should get stored in a variable, but the whole form should not get submitted after every value of input field is filled then only the form should get submitted
$idd=12;
and then i wish to run a query as
$sql=" SELECT * from menu where id = '".$idd."' ";
$result = mysqli_query($con, $sql);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
/*
*
* code to display data
*
*/
}
}
and the result that i need to display will come from the code running inside while loop
Can anyone please tell how to obtain the result
With this code, you store the result to a variable declared before the keyup event.
<input type="text" value="some text">
<p></p>
<script>
var inputValue;
$( "input" )
.keyup(function() {
inputValue = $(this).val();
})
.keyup();
</script>
Than you could do your AJAX call.
EDIT
Here's the code that only respond to the "enter" keycode
var value;
$('input').on('keyup', function(ev) {
if(ev.keyCode == 13) {
value = $(this).val();
}
});
You can do by two ways
<input type="text" value="some text" id="input_id" name="input_name">
<input type="submit" name="submit">
With jquery/ajax
$('#input_id').on('keyup', function() {
var field_value = $("#input_id").val();
jQuery.ajax({
type: 'post',
url: 'path_to_the_file',
data: { fieldValue: field_value },
success: function(successData) {
//do whatever want on success
}
});
});
Or without jquery/ajax On same page
if(isset($_POST['submit']))
{
$my_value = $_POST['input_name'];
//Execute your query
}
you can use ajax to post value of input box and get the result like this
<form action="save.php" method="post">
<input type="text" value="" id="test">
<p></p>
<input type="text" value="">
<button type="button" id="btnsubmit">submit</button>
</form>
<script>
var value
$("input").keyup(function () {
value = $(this).val();
})
$('#btnSubmit').click(function(){
$.ajax({
type: "POST",
url: "url_of_php_page",
data: {id: value},
success: function (html)
{
$("p").text(html);
}
});
});
</script>
I am using the following script with a contact form, on OK it clears the input, textarea but unfortunately it also clears the submit buttons SEND text. How could I spare this field?
Thank you
The Form
<input class="required inpt" type="text" name="name" value="" placeholder="Name" /><br />
<input class="required inpt" type="email" name="email" value="" placeholder="E-Mail" /><br />
<textarea class="required textbox" name="message" rows="6" cols="30" placeholder="Comments" ></textarea><br />
<input name="submit" type="submit" class="btn" value="Send" />
The jQuery
var close_note = $("#note");
close_note.click(function () {
jQuery("#note").slideUp(1000, function () {
jQuery(this).hide();
});
});
$("#ajax-contact-form").submit(function() {
$('#load').append('<center><img src="images/ajax-loader.gif" alt="Currently Loading" id="loading" /></center>');
var fem = $(this).serialize(),
note = $('#note');
$.ajax({
type: "POST",
url: "contact.php",
data: fem,
success: function(msg) {
if ( note.height() ) {
note.slideUp(1000, function() {
$(this).hide();
});
}
else note.hide();
$('#loading').fadeOut(300, function() {
$(this).remove();
if(msg === 'OK') { $("#ajax-contact- form").find('input, textarea').val(""); }
// Message Sent? Show the 'Thank You' message and hide the form
result = (msg === 'OK') ? '<div class="success">Your message has been sent. Thank you!</div>' : msg;
var i = setInterval(function() {
if ( !note.is(':visible') ) {
note.html(result).slideDown(1000);
clearInterval(i);
}
}, 40);
}); // end loading image fadeOut
}
});
return false;
});
It looks like you're resetting your fields using the line:
if(msg === 'OK') { $("#ajax-contact-form").find('input, textarea').val(""); }
input, textarea is not very specific, so it hits all of your inputs. If you had css selectors available, you could use them. In your case, I might do:
if(msg === 'OK') {
$("#ajax-contact-form").find('input:not([type=submit]), textarea').val("");
}
You are writing $("#ajax-contact-form").find("input,textarea"), this includes all input and textarea fields including submit button.
Exclude submit from your selection.
Try this:
$("#ajax-contact-form").find("input,textarea").not("input[type='submit']").val("");
OR:
$("#ajax-contact-form").find("input[type='text'],input[type='email'],textarea").val("");
I am trying to post contact page data to my view, but it stopped working when I included if else statements.
Here is my script:
<script>
function Submit()
{
var name = document.getElementById('contact-name').value;
var email = document.getElementById ('contact-email').value;
var subject = document.getElementById ('contact-subject').value;
var message = document.getElementById ('contact-message').value;
var data = {"name":name,"email":email,"subject":subject,"message":message,csrfmiddlewaretoken:'{{ csrf_token }}'};
if (name && email && message)
{
$.ajax({ // create an AJAX call...
data: data, // get the form data
type: "POST", // GET or POST
url: "", // the file to call
dataType: "json",
success: function(response) { // on success..
alert(response['message']);
}
});
}else
{
return true;
}
}
</script>
And here is my form:
<form class="contact-form">
{% csrf_token %}
<p class="input-block">
<label for="contact-name"><strong>Name</strong> (required)</label>
<input type="text" name="name" value="" id="contact-name" required>
</p>
<p class="input-block">
<label for="contact-email"><strong>Email</strong> (required)</label>
<input type="email" name="email" value="" id="contact-email" required>
</p>
<p class="input-block">
<label for="contact-subject"><strong>Subject</strong></label>
<input type="text" name="subject" value="" id="contact-subject">
</p>
<p class="textarea-block">
<label for="contact-message"><strong>Your Message</strong> (required)</label>
<textarea name="message" id="contact-message" cols="88" rows="6" required></textarea>
</p>
<div class="hidden">
<label for="contact-spam-check">Do not fill out this field:</label>
<input name="spam-check" type="text" value="" id="contact-spam-check" />
</div>
<input type="submit" value="Submit" onclick="javascript:Submit();">
<div class="clear"></div>
</form>
Without the if else it was working fine but now all pages are reloading with all form data as query parameters. How can I correct this?
First you need to prevent the default action if you are trying to do AJAX.
Since, I see you are already using jQuery. I recommend adding the following to the top of your <script>:
$("#contact-form").submit(function(e){
e.preventDefault();
Submit();
});
Obviously, you won't need this anymore..
onclick="javascript:Submit();"
Now run this code in any sort of javascript debugger (Chrome and Safari both have good ones) and you should be good!
Try this please..i hope it works...
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".contact-form").submit(function(e){
e.preventDefault();
Submit();
});
});
</script>
<script>
function Submit()
{
var name = document.getElementById('contact-name').value;
var email = document.getElementById ('contact-email').value;
var subject = document.getElementById ('contact-subject').value;
var message = document.getElementById ('contact-message').value;
var data = {"name":name,"email":email,"subject":subject,"message":message,csrfmiddlewaretoken:'{{ csrf_token }}'};
if (name && email && message)
{
$.ajax({ // create an AJAX call...
data: data, // get the form data
type: "POST", // GET or POST
url: "", // the file to call
dataType: "json",
success: function(response) { // on success..
alert(response['message']);
}
});
return false;
}
}
You need to return a false from your Submit() function. Also, call the function from the form tag using onsubmit handle.
<form class="contact-form" onsubmit="Submit();">
and in Submit() function:
success: function(response) { // on success..
alert(response['message']);
}
});
return false;
} else {
return true;
}
Do not use javascript: in an onxxx event handler. javascript: is a protocol specifier that goes on a URL, but the onclick handler expects raw javascript, not a URL.
You need to return false from the onclick to prevent the default action of submitting the form. I assume you do want to prevent the default and use AJAX instead?