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.
Related
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.
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.
I'm about to pull the hair out of my head with this one.
I'm sure the problem is simple, I'm new to Ajax with Jquery and I'm just overlooking something. But Man this is annoying. Every time the form is submitted, the page refreshes and .ajax throws error:. What could be causing this? I know I'm getting my form values to the Jquery for sure. And newcomment.php is working. I can post regular forms to it, but not with jquery.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
EDIT: Here's my html form:
<form>
<textarea id="comment" placeholder="Post Comment..."></textarea>
<input id="album" type="hidden" value="<?php echo "$a"?>"/>
<input id="photo" type="hidden" value="<?php echo "$p.$ext"?>"/><br/>
<button id="photo-comment-submit" onclick="postPhotoComment()">Post</button>
</form>
I also noticed that if I give the inputs names, Chrome puts them into the url bar like GET variables. And after every page refresh, it adds the ? at the end of the url. So, it seems like its trying to submit the form regularly.
Are you returning false to stop the browsers default action?
$('form').submit(function(){
var dataString = $(this).serialize(); // shortcut
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
});
return false;// cancels the default action
});
If the function where you're calling the AJAX form submission code is the onSubmit method of the form, you'll need to stop the default action from happening -- that is, you want to stop normal submission.
To accomplish this, use the preventDefault method of the event object:
function postPhotoComment(evnt) {
evnt.preventDefault();
// existing code continues...
}
You may also return false from your event, but be aware that doing so has different effects in different browsers, and that it is not as explicit or reliable as calling preventDefault or stopPropagation directly.
Edit
Also, the error handler is probably getting called because your code initiates the XHR request, but when the browser starts the default action (submitting the form), it cancels any pending XHR requests. This is causing the error handler to be triggered.
Edit 2 I have created a jsFiddle with a working demonstration: http://jsfiddle.net/wXrAU/
Documentation
event.preventDefault method on MDN - https://developer.mozilla.org/en/DOM/event.preventDefault
Make sure that you return false; to the form when submitting, otherwise it will still submit as a "normal" form without using Ajax and reload the page.
EDIT: After reading the comments I think that this would be most appropriate for you:
<form action="url.php" onsubmit="return false;"></form>
jsFiddle with appropriate code: http://jsfiddle.net/SO_AMK/ZVgNv/
The PHP messes things up a little, but it works.
I actually fixed this by simply removing the <form> tags. I didn't need them anyways. But everything seems to work now.
Make sure you write a valid, HTTP-accessible url instead of just a path to a script, e.g.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "http://yoursite.com/whatever/newcomment.php", // here
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
Because JavaScript is a client-side language. It knows nothing about your filesystem structure or anything of that kind. And AJAX request is based on HTTP protocol.
I desire to upload files asynchronous when the user select a file in a input file, with $.ajax. But the php that recive the call return index undefined.
The jquery code is the next:
$("#urlimatge").change(function(){
var filename = $("#urlimatge").val();
$.ajax({
type: "POST",
url: "utils/uploadtempimg.php",
enctype: 'multipart/form-data',
data: {'urlimatge' : filename },
success: function(response){
alert(response);
}
});
});
and the php that recibe the call:
$image = new gestorimatges();
$target_path = $image->uploadTemp($_FILES['urlimatge']['name'],$_FILES['urlimatge']['tmp_name']);
Thanks
you cannot pass the $_FILE from AJAX to PHP.
I would suggest use a plugin
It will make your life easier :) Here is a video tutorial to help too
You might wanna use tools like uploadify for that.
You can't upload files with AJAX, but you can use an iframe so you don't have to refresh the current page.
Many people go strait to plugins but you can do this yourself pretty easily, and with all the functionality of an AJAX request.
Instead of using an AJAX function, have a form submit to a hidden iframe that has a load event handler attached to it so when the form is submitted, you have a callback function that actually includes the server response (the HTML of the iframe after it loads).
Example:
HTML --
<form action="..." method="post" encrypt="application/x-www-form-urlencoded" target="workFrame" >
<input type="file" name="file" />
<input type="submit" />
</form>
<iframe id="workFrame" src="about:blank" style="display:none;"></iframe>
JS --
$(function () {
$('form').on('submit', function () {
//check if the form submission is valid, if so just let it submit
//otherwise you could call `return false;` to stop the submission
});
$('#workFrame').on('load', function () {
//get the response from the server
var response = $(this).contents().find('body').html();
//you can now access the server response in the `response` variable
//this is the same as the success callback for a jQuery AJAX request
});
});