I am using jquery validation 1.9.0. I have used the latest Jquery and on back to 1.6.0. with no change in result
My problem is this: When I deliberately put in the wrong values (not enough characters etc) the validation script rightfully shows the errors yet allows the script to be submitted anyways.
I have tried methods of validation including add rules, rules and the very simple form type below.
<script>
jQuery.validator.setDefaults({
debug: true,
success: "valid"
});
</script>
<script>
$(function() {
$("#comm").validate();
});
</script>
the form
<form action="comm.php" method="post" name="comm" id="comm">
Name: <input type="text" name="name" id="name" minlength="3" class="required" />
Email:<input type="email" name="email" id="email" class="required email" /> <br />
<label for="comment"> Comment </label> <br />
<textarea name="comment" id="comment" cols="80" rows="5" minlength="6" class="required" /></textarea>
<?php
date_default_timezone_set('America/New_York');
$date = date("Y-n-j h:i:s");?>
<input type="hidden" name="date" id="date" value="<?php echo $date; ?>" />
<?php $post_id = $id;?>
<input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id; ?>" />
<?php $ip = $_SERVER["REMOTE_ADDR"]; ?>
<input type="hidden" name="ip" id="ip" value="<?php echo $ip; ?>" />
<input type="submit" value="Post" name="post" id="post" /> <input type="reset" value="Reset Form" name="reset" id="reset" />
</form>
Very simple stuff.
Submission happens on all my forms on the net, and all of them on localhost. I can always detect errors but never stop them. What am I doing wrong?
Firebug shows me submitting properly and no script errors. Also all jquerys are connected. Firebug also shows me this After submission novalidate="novalidate" in the form html. using onsubmit=return false does not change anything
I am using ajax to submit the form, works flawlessly
$(function() {
$("#comm").submit(function() {
var data = $('#comm').serialize();
alert (data); return false;
$.ajax({
url: "comm.php",
data: data,
type: "POST",
success: function(msg){
if(msg){
$('.comme').prepend().html(msg).show();
}else{
$('.comme').text("nothing came back");
}
}
});
return false;
});
});
Thank you
Try to do your Ajax handling after clicking the submit button instead of doing with jQuery form submission perhaps you're submitting the form data through Ajax only.
$(function() {
$("#post").click(function() {
var data = $('#comm').serialize();
// TODO: validate your data - $("#comm").validate();
// TODO: submit your form though ajax
// Other operations on form data
return false;
});
});
Note: If the form submission is happening with page redirection then try with 'onsubmit=return false;'.
Update:
I seems you've to submit the FORM from the validate function's submit callback handler(submitHandler) to avoid the redirection after submission. Please try to check this demo example which is working fine with Ajax form submission, review the source code of this example page and then adjust your code accordingly.
var v = jQuery("#form").validate({
submitHandler: function(form) {
jQuery(form).ajaxSubmit({
target: "#result"
});
}
});
If you're usig jquery to receive the form when it is submitted, then then you should specify the php file containing the jquery code as the action of the form, instead of "listening" the submit event. Another option would be letting the 'action' parameter empty. The point here is that you're sending the form twice: when you click summit, the form is automatically sent to the file specified in the 'action' parameter, (that is the submission that is taking place, because it has no validation); and, at the same time when you click submit, it also triggers the ajax request, which will perform the validation and in case of success do the submission again.
Related
I have a pretty simple form. I am submitting with Ajax. The form works fine. However when I try to use php to check if an input button was pressed before I execute the code, It does not seem to pick up the button.
Any advice on what to do would be great. I have added a sam[le of the code below
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="Email-student" method= "post">
<input class="form-control" type="text" name="Email-subject" placeholder="Email Subject">
<textarea class="form-control" id="message" name="Email-message" placeholder="Enter messages"></textarea>
<input type="submit" id="btnSubmit" name="btnSubmit" value="Save Changes" />
</form>
<script>
$(document).ready(function(){
$('.Email-student').submit(function(e){
e.preventDefault();
var url = "mysql.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), // serializes the form's elements.
success: function(data) {
//$('.Email-student').html(data);
alert(data);
}
});
})
})
</script>
This is a simplified version of my Php file
if (isset($_POST['btnSubmit'])) {
echo 'btnSubmit';
}
serialize() will not include any submit buttons in the form. They are only successful controls if used to submit the form, and serialize():
isn't really part of the form submission process
can't know which, if any, submit button was used to submit the form
Consequently, isset($_POST['btnSubmit']) will not be true.
Use some other mechanism to determine if there is form data that you are interested in (such as the existence of the Email-subject field).
Hi I am using AJAX for the first time and I'm watching this tutorial so I can implement the feature on my website: https://www.youtube.com/watch?v=PLOMd5Ib69Y. What I'm trying to do is make a contact us form where the user can write a message and when he click a button the message is sent to my email. With AJAX I'm trying to change the button content without reloading.
I have this AJAX code:
<script src="/js/jquery-1.4.3.min.js" type="text/javascript"></script>
<script>
var ajax =
{
send: function()
{
var userName = $("input[name=un]").val();
var userEmail = $("input[name=email]").val();
var userMsg = $("input[name=msg]").val();
if(userName == "" || userEmail == "" || userMsg == "")
{
alert("All fields are required!");
}
else
{
ajax.SetText("Sending...");
$.post("sendMSG.php", {
name : userName, email : userEmail, message : userMsg
}, function(data){
ajax.SetText(data);
});
}
},
SetText: function(text)
{
$("input[type=button]").val(text);
}
}
</script>
And the html form:
Name: <br> <input type="text" size="40" name="un">
<br>
Email: <br> <input type="text" size="40" name="email">
<br>
Write us a Message!
<br>
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br/>
<input type="button" value="Send Message!" onClick="ajax.send()" />
For some reason when I click on the button nothings happens. As I said this is my first time using AJAX and I don't have idea how to use AJAX code. So please take it easy on me if the answer is simple :p
Thanks
You seem to be using a rather old version of jQuery. You should use the latest one which can be found on the jQuery Website.
Now for this example we'll use the submit event listener.
First you need to set up a form correctly:
<form id="myform" method="post">
Name: <br> <input type="text" size="40" name="un">
<br />
Email: <br> <input type="text" size="40" name="email">
<br />
Write us a Message!
<br />
<textarea rows="4" cols="50" name="msg" id="content"></textarea>
<br />
<input type="submit" value="Send Message!"/>
</form>
Now for the jQuery (as stated above; we'll be using the submit event.) But first we have to ensure the DOM element is loaded before running our jQuery. That is done by using:
$(document).ready(function(){});
Setting up our jquery is as simple as writing what we want to do in our submit event listener:
$(document).ready(function(){
$('#myform').submit(function(e){
e.preventDefault();
$.post('sendMSG.php',{name: userName, email: userEmail, message: userMsg}, function(data) {
console.log(data);
});
});
});
Obviously doing all the proccessing you require before running the $.post ajax request.
A Few Notes:
You could use e.preventDefault() or return false; within your event to stop the default actions taking place. (see below)
e.PreventDefault()
$('#myform').submit(function(e){
e.preventDefault();
// do ajax and processing stuff
});
return false;
$('#myform').submit(function(e){
// do ajax and processing stuff
return false;
});
You should look into using jQuery.ajax instead of the jQuery.post as it gives you more options.
I think you are using jquery,So you should put each code in
$(document).ready(function(){});
I am building a web application, I am having lots of confusion when ever I use POST method.
Lets say I have the below code
<?php
$abc = 'abc';
if(some condition){
$abc = 'xyz';
}
if(isset($_POST['submit'])){
header("Location:http://someexample.php/$abc");
die();
}
?>
<form method="POST">
<input type="text" name="textinput" />
<input type="submit" name="submit" value="submit" />
<input type="submit" name="clear" value="clear" />
</form>
so as per my understanding, If I am not wrong.
When I click the SUBMIT / CLEAR button. The PHP file reloads the self page first before redirecting it to the header location.
If I am right. Is there any other way to avoid multiple redirects when we are working on big PHP files. When I have multiple SUBMIT button.
thank you in advance
You are basically redirecting your request to another page. Instead of redirecting the page using header you should use the action attribute of the form.
<form method="POST" action="yourexample.php" id="myForm">
<input type="text" name="textinput" />
<input type="submit" name="submit" value="submit" />
<input type="submit" name="clear" value="clear" />
</form>
the form will redirect you to the second page. If you do not want to reload your page at all you should use ajax. You can use jquery and post your values to another page buy creating a function. In this case your form tag should not have the action attribute or you
should use preventDefault method.
$("#myForm").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
});
url will be the name of the page to which you want to redirect the user.
The data will be your form. You can use the .serialize() method to get your form data.
var data = $("myForm").serialize();
In success you can define a function on what to do in case of successful result.
Nothing wrong with multiple redirects: this is how traditional web works.
You may get reduce the number of redirects by using AJAX calls though.
Some notes on your pseudo-code:
it is quite useless to echo anything before Location header: noone is supposed to read the message. Not to mention that no output is allowed before headers.
http:// in front of address allowed only in case of fully qualified URI.
so, the code actually have to be
<?php
if(isset($_POST['submit'])){
header("Location: someexample.php");
die();
}
?>
Forms always post to the "action" attribute in it. If you don't want it to post to self, put your form opening tag as <form action="someexample.php" method="post">. The result will be the POST data being sent to someexample.php instead of to the same page as the form.
If you're looking into multiple form options on one page without redirect, take a look into AJAX submits.
The idea would be to send over the form to your receiving file, process the POST data, and return whatever you wanted returned from that process. For example:
$("form").submit( function(event) {
event.preventDefault(); //prevent the file submitting
var formData = $(this).serialize(); //process the form into an array for submission
$.ajax({
url: "receiver.php", //the url of the receiving file
type: "post", //setting method to post
data: formData, //set the data being sent to the form contents
success: function(response) {
$("div").html(response); //set the receiving div to the html you echo'd in the php document
}
});
});
Your receiver.php file can look exactly the same as a normal PHP document receiving POST data, so <?php if(isset($_POST['submit'])) {} ?> will still work exactly as you're expecting, without the page redirects! This solution does require jQuery though.
Edit:
To deal with the questions update of if(criteria) { $abc = 'xyz'; } there are a couple of suggestions.
To keep the asynchronous approach, go with $_SESSION variables. You could set them using the receiver.php and deal with them in the starting document.
To go back to a standard submission method onto the same document, either break your multiple options into radio inputs, checkboxes, or separate forms.
So:
<input type="radio" name="method" value="submit" />
<input type="radio" name="method" value="clear" />
That way you can choose what method to submit there.
Or you can break them into forms:
<form method="post">
<input type="submit" name="submit" value="submit" />
</form>
<form method="post">
<input type="submit" name="clear" value="clear" />
</form>
Finally, you could change the value of a hidden input on click if you wanted to change between submit and clear, so:
The HTML:
<form method="post">
<input type="hidden" id="method" name="method" value="" />
<input type="submit" id="submit" value="submit" name="submit" />
<input type="submit" id="clear" value="clear" name="clear" />
</form>
The jQuery:
$("#submit").click( function(event) {
event.preventDefault();
$("#method").val("clear"); //set the method to clear
$("form").submit(); //submit the form normally
});
$("#clear").click( function(event) {
event.preventDefault();
$("#method").val("submit");
$("form").submit();
});
The PHP:
<?php
if(isset($_POST['submit'])) {
//do something
} elseif(isset($_POST['clear'])) {
//do something else
}
I have php code that echos a form that was inserted into my html by another jquery code. This all works fine. I am trying to submit this form with ajax.
echo '<form id="comment_form" action="commentvalidation.php?PhotoID='.$_GET['PhotoID'].'" method="POST">';
echo '<label>Comment: </label>';
echo '<textarea id="description" name="CommentDesc" cols="25" rows="2"></textarea>';
echo '<input class="button" id="comment_btn" type="submit" name="Comment" value="Comment" >';
echo '</form>';
The form works fine when submitted traditionally. The problem is I cant get it to be be submitted with ajax. The .submit just wont prevent the default action.
<script>
$(function(){
$('#comment_form').submit(function() {
alert("we are in");
$.post($('#comment_form').attr('action'), $('#comment_form').serialize(), function(data){
$('#comment_form').html("<div id='message'></div>");
});
//Important. Stop the normal POST
return false;
});
});
</script>
You're probably binding the submit event handler before the form is in your page. Use event delegation instead of direct binding, for example
$(document.body).on('submit', '#comment_form', function(e) {
e.preventDefault();
alert('We are in');
// and the rest, no need for return false
});
As an addendum, try not to echo out great chunks of HTML from PHP. It's much more readable and you're less likely to run into problems with quotes and concatenation if you just switch to the PHP context when required, eg
// break out of the PHP context
?>
<form id="comment_form" action="commentvalidation.php?PhotoID=<?= htmlspecialchars($_GET['PhotoID']) ?>" method="POST">
<label>Comment: </label>
<textarea id="description" name="CommentDesc" cols="25" rows="2"></textarea>
<input class="button" id="comment_btn" type="submit" name="Comment" value="Comment" >
</form>
<?php
// and back to PHP
The problem seems to be from the fact that form that was inserted into my html by another jquery code. From what I understood from this, the form was dynamically created after the page was loaded.
In that case when the submit handler registration code was executed the element was not existing in the dom structure - means the handler was never registered to the form.
Try using a delegated event handler to solve this
$(function(){
$(document).on('submit', '#comment_form', function() {
alert("we are in");
$.post($('#comment_form').attr('action'), $('#comment_form').serialize(), function(data){
$('#comment_form').html("<div id='message'></div>");
});
//Important. Stop the normal POST
return false;
});
});
Demo: Problem
Demo: Solution
I have a form that is called via the fancybox plugin login example.
Here is the code I have:
Form:
<form method="post" action="" id="events_form">
<p class="clearfix"><label for="Name">Name:</label> <input type="text" name="Name" id="Name" /></p>
<p class="clearfix"><label for="Company">Company:</label> <input type="text" name="Company" id="Company" /></p>
<p class="clearfix"><label for="Email">Email:</label> <input type="text" name="Email" id="Email" /></p>
<p class="clearfix"><label for="Tel">Tel:</label> <input type="text" name="Tel" id="Tel"/></p>
<p class="clearfix"><input type="submit" value="Submit details" /></p>
</form>
JavaScript / jQuery:
<script type="text/javascript">
$(document).ready(function(){
$("#event_trigger").fancybox({
'padding' : 0,
'scrolling' : 'no',
'titleShow' : false,
});
$("#events_form").bind("submit", function() {
$.fancybox.showActivity();
$.ajax({
type : "POST",
cache : false,
url : "/events/index.php",
data : $(this).serializeArray(),
success: function(data) {
$.fancybox(data);
}
});
return false;
});
});
</script>
The PHP file returns and empty array. However the Firebug post tab displays the form data.
Also, I noticed that if I do
print_r($_SERVER['REQUEST_METHOD'])
This returns GET, even though I have specified POST.
$(this).serializeArray()
with the name of the form CSS id (#my-form-ID, in this example) like this:
$("#my-form-ID").serializeArray()
Hope that solves it. It worked for me. ;-D
$.ajax expects the parameter data to be an object or a string.
http://api.jquery.com/jQuery.ajax/ scroll down to data.
If you wrap your data in an object e.g. data: {array:$(this).serializeArray()} it may work. I'm not 100% sure on that though.
You are doing an AJAX request on a form submit.
Unless the AJAX request is synchronous (which I wouldn't recommend, anyway) there is a danger that your form will be submitted before there is any chance for the AJAX request will return.
In the line:
$(this).serializeArray()
$(this) is referring to the the form element you have selected in the bind method. I'm assuming this is intended