I,m using PHP, Jquery and Ajax to submit user info, to validate the input fields and submit the info I use this
$(document).ready(function(){
$("#contact_form").validate({
... my validation code goes here ...
submitHandler: function(form) {
$.ajax({
type: $(form).attr("method"),
url: $(form).attr("action"),
data: $(form).serialize(),
dataType : "json",
success: function(result){
$("#contact_form").fadeOut(1000, function(){
$("#success_message").fadeIn();
});
}
})
}
});
});
I know it is very simple but I have a question: do I need to add the preventDefault() method? If the answers is yes, could you please help me with an example?
Thanks.
No you are not required to put e.preventDefault(); since jquery validator does that for you. when the form is submitted the default action of form is prevented by the Jquery validator.
Related
I am using the plugin formtomail to send emails. The problem that I am experiencing is that I do not want the page to refresh after submitting the form from the template which is called in the action of the form on the primary page. Does someone know how to do this that has worked with this plugin?
I think this might help a little:
first you need to edit the html page that has the form.
then add this script to it and adjust it properly.
// this is the id of the form
$("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
I know js validation is for client side and php validation is for server side.
User can skip the js validation and submit but is it possible when I am getting the action php file in ajax?
I mean I am using the following code to validate the form. as you see I am calling postProjectAction.php in the ajax..
If an user skip the JS/disable the js and submit the form, form won't be submitted because,
my form has no action
the form data will not be inserted or submitted to the database if the postProjectAction.php is not called. when user disable the js the code won't call the postProjectAction.php
so there is no chance to submit the form.
Is this still insecure?
html:
<form id="form_validation" method="POST">
</form>
js validation:
$(document).ready(function() {
$("#form_validation").submit(function() {
if ($("#form_validation").valid()) {
var data1 = $('#form_validation').serialize();
$.ajax({
type: "POST",
url: "postProjectAction.php",
data: data1,
success: function(msg) {
console.log(msg);
$('.messagebox').hide();
$('#alert-message').html(msg);
$('.messagebox').slideDown('slow');
}
});
}
return false;
});
});
Well PHP validations are at server end while JQuery are at front end.
So its basically depend on need or requirements.
Bots can break front end validations while its bit difficult to break server end validations.
Bottom line, doing server side validation is making more secure :)
Yes, your form is still insecure. A user need not disable JavaScript or even submit your form to bypass the validation implemented.
Your code does validation only when the form is submitted. A user can simply paste the below code to the browser console and run it to post data without doing any validation.
var data1 = $('#form_validation').serialize();
$.ajax({
type: "POST",
url: "postProjectAction.php",
data: data1,
success: function(msg) {
console.log(msg);
$('.messagebox').hide();
$('#alert-message').html(msg);
$('.messagebox').slideDown('slow');
}
});
This is just one of the many ways validation on your form can be bypassed. It is always a good practice to validate all data coming from the client side.
$(document).ready(function() {
$("#form_validation").submit(function() {
if ($("#form_validation").valid()) {
var data1 = $('#form_validation').serialize();
$.ajax({
type: "POST",
url: "postProjectAction.php",
data: {data1:data1},
success: function(msg) {
console.log(msg);
$('.messagebox').hide();
$('#alert-message').html(msg);
$('.messagebox').slideDown('slow');
}
});
}
return false;
});
});
edit postProjectAction.php
if(!$_POST['data1'] OR !$_POST['blalbla']) header("HTTP/1.0 404 Not Found");
else{Your actions}
I am trying to submit a form using ajax.
Without the ajax, the form action 'send.php' works fine, it sends an email with data from the form (including files etc...)
But I want it to do so without redirecting to the php page,
so I try to use ajax but the php is not executed (I think), it should send an email and the email is not sent (reminder - without ajax it works fine).
The ajax alert "Form submitted" (success) but the mail is not sent and non of the echo/alert in the php file shows up...
HTML form:
<form method="post" action="send.php" enctype="multipart/form-data"id="myForm" target="_blank">
ajax:
$(document).on('submit', '#myForm', function(e) {
e.preventDefault();
$.ajax({
url: $('#myForm').prop('action'),
type: $(this).attr('method'),
data: $('#myForm').serialize(),
beforeSend: function() {
$('#gif').css('visibility', 'visible');
},
success: function(data) {
$('#gif').css('visibility', 'hidden');
alert('Form submitted');
},
error: function() {
// The request failed - So something here
alert('Form NOT submitted'); //display an alert whether the form is
}
});
});
Edit:
Found the source of the problem, my ajax is not complete I need to make use of FormData!
I can't find how to make use of it for all the files in my form can someone please show an example for the right ajax?
create a variable in your JavaScript like
var myData = $('#form_ID').serialize();
and then when making ajax call use
$.ajax({
url: URL_HERE,
method: "POST",
data: myData,
success: function (results) {
it will submit the form data, simple is that.
I have an issue where I need a simple contact form to have an action to post to a data collection service, AND to a thank you page for conversion tracking.
The data collection service page does not allow for any sort of redirection unfortunately, so my best bet is to submit to BOTH a thank you page, and to the data collection service.
I just don't know how to to this though... can someone please steer me in the right direction? I've done a lot of searching, but can't really get anything to work with jquery or javascript.
Any advice / feedback / methods would be greatly appreciated.
Per the reply below, I'm trying to get the AJAX to redirect after it sends data to the collection service like this, but I can't get it to work:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
// Shorthand for $( document ).ready()
$(function() { $("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
window.location.replace("http://example.com");
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}); });
</script>
<form name="ajaxform" id="ajaxform" action="https://secure.velocify.com/Import.aspx?Provider=IdealHomeLoansWebPOST&Client=IdealHomeLoansLLC&CampaignId=46"method="POST">
Using jQuery, you could send everything to your data collection service and wait for an answer. If it was successful, redirect to the thank you page.
Everything you need to know can be found in this article: http://hayageek.com/jquery-ajax-form-submit/
$(function() {
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
});
This replaces the default form-submission with an AJAX-Request.
Then just use the following code to redirect to the thank you page:
window.location.replace("http://example.com");
Submit to the Thank You page and have the Thank You page do a CURL request to the data collection service.
Or, submit to an intermediate page that submits the CURL request and then redirects to the Thank You page.
The most straight forward way I can think of doing this would be to have a onClick handler for your submit button and then using JavaScript fire off some sort of XHR post request to your data collection service containing the form data. You would then return true and the browser would post to the Thank You page.
For example using JQuery (your code will need more check and complexity)
HTML:
<form id="form" action="somewhere.php" method="post">
<!-- form stuff here -->
<input type="submit">
</form>
JS:
$('#form').submit(function() {
$.post('somewhereElse.php', {data: $('#form-element').val()});
return true;
});
JQuery Ajax Post, might have to set it to async.
On the success submit from the first one, you can submit to the second. Then on the success you can redirect to the the thankyou page.
For some reason my submit event is not working, however, if i change it to click on the form, it works, this is my code:
JQUERY:
<script>
(function(){
$('form').on('click',function(){
$.post("../includes/register.php", $('form').serialize(),
function(data){
$('body').append(data);
});
});
})();
</script>
REGISTER.PHP:
<?php
if(isset($_POST['username'])){
echo $_POST['username'];
}
?>
This works perfectly fine, it appends the username whenever I click on a form text input, however, when I try to use the submit method, it doesnt output anything:
<script>
(function(){
$('form').submit(function(){
$.post("../includes/register.php", $('form').serialize(),
function(data){
$('body').append(data);
});
});
})();
</script>
As a matter of fact, it doesn't even work when I use button.on('click')
You are using an immediately invoked function instead of document ready handler, also you should prevent the default action of the event, try the following:
$(function(){
$('form').on('submit',function(event){
event.preventDefault();
$.post("../includes/register.php", $(this).serialize(),
function(data){
$('body').append(data);
});
});
});
The form will submit to the form's action by default. You need to prevent this from happening. You are waiting for a server response via ajax, so it is most likely you will never witness your callback executing before the default action occurs.
$('form').submit(function(e){
e.preventDefault(); // put this first
$.post("../includes/register.php", $('form').serialize(),
function(data){
$('body').append(data);
});
});
This is speculation right now since I do not know what your HTML code looks like.
But on submit the form will be submitted, and any active ajax requests will be cancelled.
Try something like
<script>
(function(){
$('form').submit(function(){
$.post("../includes/register.php", $('form').serialize(),
function(data){
$('body').append(data);
});
return false;
});
})();
</script>
That will stop the submit event and you should get the post event to occur. Though it will NOT actually submit the form. So you'll have to do that manually.