Im following this question trying to post to a php page and have it perform an action on the data the problem is it seems to just refresh the page and not sure what its doing. In the network tab in element inspector my php page never appears.
Here is my code:
js:
<script>
$(function () {
$("#foo").submit(function(event){
// variable to hold request
var request;
// bind to the submit event of our form
// abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "/DormDumpster/session/login-exec.php",
type: "post",
data: json
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
alert("hello");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
alert("bye");
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
});
html:
<form id = "foo" method="post" >
<fieldset id="inputs">
<input id="email" type="email" name="login" placeholder="Your email address" required> <br>
<input id="password" type="password" name="password" placeholder="Password" required>
</fieldset>
<fieldset id="actions"">
<input type="submit" id="submit" name "Submit" value="Log in"">
<label><input type="checkbox" checked="checked"> Keep me signed in</label>
</fieldset>
</form>
php
$email = clean($_POST['login']);
$password = clean($_POST['password']);
Any Ideas to what I am doing wrong or how to figure out what im doing wrong.
You are probably trying to attach the event listener prior to the form being available in the DOM - thus your form won't be found and no event listener will be attached. Try wrapping your code in a DOM-ready callback, to make sure that your form is in the DOM before trying to select it.
$(function () {
$("#foo").submit(function(event){
// All your code...
});
});
More on why and when to use DOM-ready callbacks here.
i think you have to wrap your submit function inside doc ready:
$(function(){
// here your form submit
});
It is always good to note what arguments you are passing as parameters and to check if it is valid within that function or property.
$(function(ready) {
$.ajax({
type: "POST",
url: "/DormDumpster/session/login-exec.php",
data: { name: "John", location: "Boston" },
dataType: "JSON"
})
}
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests.
- from http://api.jquery.com/jQuery.ajax/
Related
This should be simple, yet it's driving me crazy. I have an html5 form that I am submitting with ajax. If you enter an invalid value, there is a popup response that tells you so. How can I check that the entries are valid before I run my ajax submit?
form:
<form id="contactForm" onsubmit="return false;">
<label for="name">Name:</label>
<input type="text" name="name" id="name" required placeholder="Name" />
<label for="subject">Subject:</label>
<input type="text" name="subject" id="subject" required placeholder="Subject" />
<label for="email">Email:</label>
<input type="email" name="email" id="email" required placeholder="email#example.com" />
<label for="message">Message:</label>
<textarea name="message" id="message" required></textarea>
<input type="submit" id="submit"/>
</form>
submit:
$('#submit').click(function(){
var name = $("input#name").val();
var subject = $("input#subject").val();
var email = $("input#email").val();
var message = $("input#message").val();
var dataString = 'email=' + email + '&message=' + message + '&subject=' + subject + '&name=' + name ;
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: dataString,
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
If you bind to the submit event instead of click it will only fire if it passes the HTML5 validation.
It is best practice to cache your jQuery selectors in variables if you use it multiple times so you don't have to navigate the DOM each time you access an element. jQuery also provides a .serialize() function that will handle the form data parsing for you.
var $contactForm = $('#contactForm');
$contactForm.on('submit', function(ev){
ev.preventDefault();
$.ajax({
url: "scripts/mail.php",
type: 'POST',
data: $contactForm.serialize(),
success: function(msg){
disablePopupContact();
$("#popupMessageSent").css("visibility", "visible");
},
error: function() {
alert("Bad submit");
}
});
});
By default, jQuery doesn't know anything about the HTML5 validation, so you'd have to do something like:
$('#submit').click(function(){
if($("form")[0].checkValidity()) {
//your form execution code
}else console.log("invalid form");
});
If you are using HTML5 form validation you'll have to send the ajax request in the form's submit handler. The submit handler will only trigger if the form validates. What you're using is a button click handler which will always trigger because it has no association with form validation. NOTE: not all browsers support html5 form validation.
I prefer using the jQuery submit handler, you will still get the response to your form with the following method.
jQuery('#contactForm').on('submit', function (e) {
if (document.getElementById("contactForm").checkValidity()) {
e.preventDefault();
jQuery.ajax({
url: '/some/url',
method: 'POST',
data: jQuery('#contactForm').serialize(),
success: function (response) {
//do stuff with response
}
})
}
return true;
});
Not exactly sure what you mean. But I assume that you want to check in realtime if the input is valid. If so you should use .keyup instead of .click event, because this would lead to an action if the user presses submit. Look at http://api.jquery.com/keyup/
With this you could check the input with every new character insert and display e.g. "not valid" until your validation ist true.
I hope this answers your question!
U can also use jquery validate method to validate form like
$("#form id").validate();
which return boolean value based on form validation & also u can see the error in log using errorList method.
for use above functionality u must include jquery.validate.js file in your script
I have managed to validate my textboxes using JS but know I need to allow the captcha to work alongside the validation.
<script>
function validateForm() {
var x = document.forms["reg"]["User"].value;
var letters = "#";
if (x.match(letters))
{
alert("Can't Have Email Address As USERNAME!");
return false;
}
return true;
}
First Form
<form name="reg" action="DBLogin.php" onsubmit="return validateForm()" method="post">
Captcha:
<form action="validate.php" method="post">
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Register">
</form>
Is there a way of having the captcha work alongside my JS validation?
Thank you
use ajax to validate the captcha. and when he submits the form send an ajax request to verify captcha.
give a submit button only to the captcha form.
<form id ="captcha-form" >
Enter Image Text
<input name="captcha" type="text">
<img src="captcha.php" /><br>
<input name="submit" type="submit" value="Register">
</form>
main form :
<form id="main-form" name="reg" action="DBLogin.php" method="post">
<!-- this shoulnt have an submit button -->
now use a js code to first verify the captcha and validate form
$("#captcha-form").submit(function(event){
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "validate.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
if(response == "true")
{
validateform();
}
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// handle error
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
now the validate function
function validateForm() {
var x = document.forms["reg"]["User"].value;
var letters = "#";
if (x.match(letters))
{
alert("Can't Have Email Address As USERNAME!");
}
$("#main-form").submit();
}
as RiggsFolly has pointed out this is not recommended. as this would defeat the purpose of captcha.
Im working on fixing some validation to my forms. The validation works, problem is that when no validation error occur, the form submits as many times the user tried to submit. It is like the requests stacks up on a pile.
Forms has this submit button that calls my ajax function create_new_stuff
<input id='submitButton' onclick='create_new_stuff()' name='submit' type='submit' value='create' />
The function
function create_new_stuff(){
$("#createForm").submit(function(event){
event.preventDefault();
event.returnValue = false;
var input_value = $("#createValue").val();
if(input_value === "" || null){
console.log("Wrong input value");
return;
}
else{
var request;
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "/new_stuff.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
console.log("Stuff created!", response);
create_new_stuff_form();
var successDiv = $("<div class='success'>Stuff was created</div>");
$("#responseMessages").html(successDiv);
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
}
});
}
instead of adding onclick event to submit button, add onsubmit event to form.
<form onsubmit= 'create_new_stuff()'>
</form>
<input id='submitButton' onclick='return create_new_stuff()' name='submit' type='submit' value='create' />
And return false when you don't want to submit the form from your javascript function.
Change button type submit to button or change onclick to onsubmit
Prevents the event from bubbling up by:
event.stopPropagation();
Every time you click on Submit button the onclick calls the create_new_stuff() method to do the required stuff. If you think to do this on form submit or button click both shall show the same behaviour. You can try something like this:
HTML
<label for="formelement">Enter Value Here:</label>
<input type="text" id="formelement" name="formelement">
<input type="submit" id="submitbutton" value="Submit">
JS
$("#submitbutton").on('click', function(e) {
e.preventDefault();
$('#submitbutton').attr('disabled',true);
var x = $("#formelement").val();
if(x=="" || null)
{
console.log("Wrong Input..!!");
return;
}
else {
console.log("Hello" + " " +x);
}
});
Working Demo : DEMO
And you can put a loader here to show server action being done.!!!
I think the best solution specifically for the situation when you are trying to use same code for different forms and you have to use separate function for form submission instead of direct submission
$("#this_is_form_id_string").on('submit', function(e){ });
you can do the trick
function submit_forms(form_id){
var avoid_duplicate_form_submission = 0;
$("#"+form_id).submit(function(e){
e.preventDefault();
avoid_duplicate_form_submission++;
if(avoid_duplicate_form_submission === 1){
// All your code....
}
});
}
Update 2: I found out what was wrong! There was a 301 redirect in the .htaccess file. I will post it as an answer once I am allowed to (users under 10 rep have to wait 8 hours).
Update: I have taken Barmar's suggestion and checked the network tab (a tab I'm not too familiar with) and noticed I am receiving a 301 from handle.php See screenshot. I am going to do some searching and post my results.
Original Post: I am using the JQuery validation plugin to validate and send form data via ajax. The problem isn't that the data is being sent, but the form handler is saying there are no elements in the $_POST array. I have tested a few different methods to send ajax, and the data sends, but the form handler does not see any $_POST[] values.
Note: I have to use the JQuery validation plugin so it has to be handled by .validate.submitHandler(). Any $(form).on() won't suffice.
html + js (index.php)
<form action="handle.php" class="sky-form sky-form-modal" id="sky-form-modal" method=
"post" name="sky-form-modal">
<label class="input">
<input name="name" placeholder="Name" type=
"text">
</label>
<label class="input"><input name="company" placeholder="Company" type=
"text">
</label>
<footer>
<button class="button" type="submit">Send request</button>
<div class="progress"></div>
</footer>
</form>
<script>
$("#sky-form-modal").validate({
submitHandler: function(form) {
var $form = $("#sky-form-modal"); //being explicit for testing
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
request = $.ajax({
url: "handle.php",
type: "POST",
data: serializedData
});
console.log('data: ' + serializedData);
request.done(function(response, textStatus, jqXHR) {
console.log("Response: " + response);
});
},
});
</script>
handle.php:
<?php
if(isset($_POST['name'])) {
echo 'we got it';
} else {
echo 'name not set';
}
?>
Okay, so it seems like everything works, check out the console.log after I fill in the username and leave the company blank:
data: name=testtest&company=
Response: name not set
As you can see, serialize works and grabs all the info, but when handled by handle.php it tells me that the $_POST[] is empty. Looping through it on handle.php proves it:
foreach($_POST as $key=>$value) {
echo "$key: $value
\n";
}
Which doesn't return at all.
I have also tried ajaxSubmit() and form.submit() but I get the same exact results.
This one looks right to me, because I have searched and searched stackoverflow and came across that most of the problems with this is including the 'name' attribute on the input tags, which is already done.
Thanks in advance!!
My issue was irrelevant to my code and ended being a few declarations in the .htaccess. It was redirecting me from a .php file to a directory (for prettier URLS). Now, this is a common technique so:
if you are working on someone else's project and your URL's aren't standard with a file extension, check the .htaccess!
Page.html or .php
<form action="/" id="sky-form-modal" method=
"post" name="sky-form-modal">
<input name="name" placeholder="Name" type="text">
<input name="company" placeholder="Company" type="text">
<button class="button" type="submit">Send request</button>
</form>
<div id="result"></div>
<script>
var request;
$("#sky-form-modal").submit(function(event){
// abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, input");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "handle.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
$("#result").html(response);
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
</script>
handle.php
<?php
foreach ($_POST as $key => $value) {
echo "POST Key: '$key', Value: '$value'<br>";
}
?>
I removed your labels and classes for the simple look of the form.
i Guess you missed '(' after validation
$("#sky-form-modal").validate {
$("#sky-form-modal").validate ({
So i have this function in JS, sending a request to insert a new Status message to the database.
function DoStatusInsert(){
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
With this form:
<input name="message" type="text" id="message" value="" size="60">
<input type="hidden" name="uID" id="uID" value="<?php echo $v["id"]; ?>">
<input name="submit" type="submit" id="submit" value="Spara">
<div id="statusResponseNow"></div>
Now I wish to do something like blocking the submit button or the message field to "read-only" until you receive response / success, so you don't have the opportunity to like press submit alot of times so it inserts alot.. (i know you could make a php for checking after doubleĀ“s in DB)
So: when you click on submit then it makes either message field and/or submit button to read only
How should i do it?
function DoStatusInsert(){
$('#IdOfYourSaveButton').attr('disabled', 'disabled');
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val(),
success: function(msg){
$('#IdOfYourSavebutton').removeAttr('disabled');
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
}
});
}
enabled and disable the button. nice and easy :)
On calling the function, set the disabled property of the button, and then set it back on success.
function DoStatusInsert(){
$('#submit').attr("disabled", "true");
var wrapperId = '#statusResponseNow';
$.ajax({
type: "POST",
url: "misc/insertStatus.php",
data: {
value: 'y',
uID : $('#uID').val(),
message : $('#message').val()
},
success: function(msg){
$('#message').val("");
$('#statusResponse').toggle();
$(wrapperId).prepend(msg);
$(wrapperId).children().first().fadeIn('slow');
$('#submit').attr("disabled", "false");
}
});
}
My initial thoughts would be to insert
$('input[type=submit]', this).attr('disabled', 'disabled');
before the ajax call is started and then removed the disabled attribute with the success function of the ajax request.
Manually toggling the disabled state of the button works well enough, but jQuery has a couple helper events to make that a bit nicer: .ajaxStart() and .ajaxStop(). You can use those two handlers on your submit button and not have to worry about maintaining that manual code around your $.ajax() request.
Just throw this in with your other initialization code, probably in $(document).ready():
$('#submit').ajaxStart(function() { this.disabled = true; });
$('#submit').ajaxStop(function() { this.disabled = false; });
You can use for example jQuery BlockUI Plugin from http://jquery.malsup.com/block/ (see demo on http://jquery.malsup.com/block/#element and http://jquery.malsup.com/block/#demos).
If a div with all your form elements which you need to block has id formDiv then you can call
jQuery('#formDiv').block({ message: '<h1>Just a moment...</h1>' });
before jQuery.ajax and call
jQuery('#formDiv').unblock();
as the first line in both success and error handler of the jQuery.ajax.