I am working on a survey that will go at the bottom of a FAQ page. My problem is that everytime a form is submitted, it sends you to a different page. I was wondering - is there a way to submit the form and have a little message that replaces the survey that says "Thanks for your feedback" instead of sending the user to another page or refreshing the page?
So far, I have a file that contains the HTML form, CSS, and jQuery and another file that contains the PHP connection to database and insertion of data to the database.
I would appreciate an explanation that is dumbed-down and an example would help since I am relatively new to programming.
An important note: My jQuery is set up to automatically submit if a user answers very helpful/extremely helpful. If not, two more questions appear below with a submit button at the bottom.
More specifically it looks like this:
$(document).ready(function() {
$('.rating').click(function() {
$('.rating').removeClass('selected');
ratingClick(this);
});
});
function ratingClick(that) {
console.log(that.id);
if (that.id == 'rating4' || that.id == 'rating5') {
//$('#questions').fadeOut('slow');
//$('#thankYou').fadeIn('slow');
$('#questions').submit();
} else {
$('#getMore').fadeIn();
$(that).toggleClass('selected');
}
}
$(document).ready(function() {
$('#submit').click(function(){
//$('#questions').fadeOut('slow');
//$('#thankYou').fadeIn('slow');
});
});
What you want is the jquery post function: http://api.jquery.com/jQuery.post/
Make sure your data is JSON.
$("#formdiv").click(function(){
$.post("somepage",{ yourformdata} );
$("#formdiv").replacewith("Thanks for filling out the form!");
});
You can use the replaceWith function to replace the desired content with the thankyou message.
Alex,
from the code you supply, the reason for leaving the page is due to the fact that you don't preventDefault() on the click event. Your page will always reload after that submit unless you take abortive action. No guarantees, but try a quick refactor to:
$(document).ready(function() {
$('#submit').click(function(e){
e.preventDefault();
//$('#questions').fadeOut('slow');
//$('#thankYou').fadeIn('slow');
});
});
This should get you a stage closer. You then just have the ajax logic to define, which should come good with a quick search to match your needs.
Related
I included a php form into my html code and changed it from index.html to index.php. The contact form is working well and sending everything. After submitting the user gets the message "Thank you. The message has been sent.". However, when the page is refreshed it jumps up to the header and the user has to scroll down again to see the message.
I know why this happens. A couple of days ago I had included this code:
$(document).ready(function(){
$(this).scrollTop(0);
});
I did so because when somebody visited my website he was directed to the contact form first and the page did not load at the header first. However, now, when somebody is submitting a message the page scrolls again to the top. Do you know any way to avoid this? It would be nice if the user would see the header first when visiting the website but should be redirected to the form section when submitting a message.
Thank you for your help.
Use a cookie:
https://www.w3schools.com/js/js_cookies.asp
$(document).ready(function(){
if(!getCookie(cname)){
$(this).scrollTop(0);
}
});
$( "#formID" ).submit(function( event ) {
setCookie(cname, cvalue, exdays)
});
Essentially you have two possible states. The first possible state is when you want to scroll to the top, the other is when you do not want to scroll to the top. Let's assume that you know what the condition is to be tested. In that case your code would look like:
<?php
if ($condition) {
?>
//your scrolling JS code
<?php
}
?>
Now, how could we determine $condition? an idea is to store some value in the $_SESSION of the user, which will be a logical value which will determine whether we need to scroll or not. You should check whether the value exists in $_SESSION and if not, default it to true or false (depending on your actual need).
When using jQuery, return false is doing 3 separate things when you call it:
event.preventDefault();
event.stopPropagation();
Stops callback execution and returns immediately when called.
See jQuery Events: Stop (Mis)Using Return False for more information and examples.
Ref
Wrap that particular JS code block with a PHP if condition that checks whether the form has not been submitted. E.g.
<?php if (!$formSubmitted) { ?>
[JS code here]
<?php } ?>
Try this
$('form').submit(function(e)
{
e.preventDefault();
$.ajax({
type: 'POST',
url: "your_page.php",
data: $('form').serialize(),
success: function(response) { /*what to do on response*/ },
});
});
Here i prevent default submit with reloading and send ajax post
If i have a page which has an ajax link and that the code returns a that form needs validating, where do i put the validation code please. Say my form had this validation using the jquery validation plugin
jQuery(document).ready(function() {
$("#basicForm").validate({
showErrors: function(errorMap, errorList) {
// Clean up any tooltips for valid elements
$.each(this.validElements(), function(index, element) {
var $element = $(element);
$element.data("title", "") // Clear the title - there is no error associated anymore
.removeClass("error")
.tooltip("destroy");
});
// Create new tooltips for invalid elements
$.each(errorList, function(index, error) {
var $element = $(error.element);
$element.tooltip("destroy") // Destroy any pre-existing tooltip so we can repopulate with new tooltip content
.data("title", error.message)
.addClass("error")
.tooltip(); // Create a new tooltip based on the error messsage we just set in the title
});
},
submitHandler: function(form) {
var myselect = $('select[name=ddCustomers]');
//alert(myselect.val());
window.location.replace("customer.php?customer_id=" + myselect.val());
}
});
$("#basicForm").removeAttr("novalidate");
});
where do i put it as the document.ready where i would normally out this code has already been called
I hope this makes sense
Could i have it on the page in the initial page load ready for when the form is returned
I've read i coud have the validation in the document.on function but dont really understand. Would i post something like this back with my ajax response for the validation
$(document.body).on('click', '#basicForm', function(){
$("#basicForm").validate({
submitHandler: function() {
// do whatever you need here
}
});
});
Thanks for your help. Its confusing and I cant find a decent example on google
EDIT
I know how to write the validation code for the dynamically generated forms so thanks for those answers but I am alright on that. The question is WHERE that code should i put it in the ajax return?
Perhaps i have a misconception but i am using jquery validate module (base assistance( and i have only ever seen the `form validate method called in doc. ready on the first page - never an ajax postback
document.ready
Options
1) Hard coded in page already writing for when form injected by ajax? not dynamic enough - the injected form is created dynamically so the validation may need to
be
2) Add validation code to
document.on
when i do ajax postback for the new form? Is this even possible? Im not a client side programmer.
I am bemused that such a common scenario doesnt have a design pattern. Though i have read postng back forms via ajax is bad practice as it can confuse the browser and now what ajax whs written for so perhaps that why i cant find a solution
thanks
I've coded and developed many web apps just with jquery, php being the server side script. The way I formed was to have the jquery code and html on the same page since jquery needs to check the html element and respond with the proper error message and sanitize all the data fields before I submit to the "form-process.php" for an example if that was the name of your server side script.
Have:
$(document.body).on('click', '#basicForm', function(){
$("#basicForm").validate({
submitHandler: function() {
// do whatever you need here
}
});
});
code as the same page as say: create-username.html or create-username.php page
html elements. Some prefer to have jquery on the bottom, depends on how you have your
page structured, but I like to put the js on top from old practices although sometimes it doesn't apply to jquery.
include your tooltips code in the same block. I don't like to have jquery all over the place; incase of errors or if you need to modify in future reference it wouldn't be hard to pinpoint to edit, add or fix code. I hope this helps.
You need to initialize the validation plugin first and set up the rules you want. Then when a user submits the form, prevent the default form submission behavior and if all is validated successfully based on the criteria of the rules you set, you manually submit the form to the server using ajax.
$('#basicForm').validate({ // initialize the plugin
rules: {
field1: {
required: true,
email: true
},
field2: {
required: true,
minlength: 5
}
}
});
$('document').on('submit', '#basicForm', function(e){
if($(this).valid()){
//client side is valid, make ajax call
}
e.preventDefault();
});
I have looked at a few similar examples on StackOverflow but I can't seem to get this to work. I have an onclick event that goes to one function and if that returns ok it goes to another function and if that is fine it will submit it in the else statement like:
document.forms["input"].submit();
so I tried commenting this out and sending it to a function called showHide()
function showHide() {
$('#input').submit(function () {
$('#main-content').hide();
$('#progress').show();
});
}
It doesn't seem to submit the form like expected. I basically want to use bootstrap and show an animated progress bar so the user knows something is happening because sometimes the submission can take awhile.
Update:
I was able to get this working with both bootstrap progress bars and the jquery ui progress bar. I just run the progress bars right before it submits the form. I hide the div when i load the view.
$(function() {
$("#progress").show();
});
document.forms["input"].submit();
Without seeing more HTML, it's a bit hard to troubleshoot. But it looks like you've defined a function, and within this function you're expecting an element to trigger it, which won't really work. You could call your function from your form's submit event, like so:
//this assumes you have a form with id "input"
$('#input').submit(function () {
showHide();
});
function showHide() {
$('#main-content').hide();
$('#progress').show();
}
Simple JSFiddle demo
document.forms is an object containing the names of forms not the IDs.
If your form doesn't have a name of input (<form name="input">...</form>), the jQuery selector you're binding to won't work. Instead you'll need to use $('[name=input']).submit(...).
form submit reloads page.
hence in your head section add:
$(window).load(function() {
// Animate loader off screen
console.log("loading");
$("#dvLoading").fadeOut(2000);
});
I have a one page website in the works that has a contact form where its contact error and contact thank you messages are placed further down the page as hidden divs.
The contact form calls an external php file that calls the anchor links of the error and thank you message divs in the index.html file.
www.photograsurfer.com/test/index.html
www.photograsurfer.com/test/code/contact-panel.php
Everything works successfully as long as the divs are not hidden. So now I need to use the following javascript to get the hidden divs to display when needed.
<script type="text/javascript">
function showContactPanelError() {
document.getElementById('contact-panel-error').style.display = "block";
}
</script>
My problem, besides being a complete PHP beginner, is that I don't know how to get the PHP file to reference the Javascript code to display the hidden divs properly on the main page.
Any help is appreciated.
Thanks.
Use jQuery forms (http://malsup.com/jquery/form/) to submit your form via AJAX, then show/hide divs depending on values you return from PHP scripts.
you could assign php variable to javascript as
var error="<?php echo $_GET['error']; ?>";
the $error is the data passed along with the url like wwww.example.com/test.php?error=1
Now you could check var error and call your function showContactPanelError().
I ended up going with a mixture of the 2 methods on these pages.
http://trevordavis.net/blog/ajax-forms-with-jquery
https://spruce.it/noise/simple-ajax-contact-form/#contact
Ditched the div idea since the Ajax method allowed me to not reload the page and enter error and thank you messages within the contact form itself. Seemed like an easier approach.
Thanks for all of the suggestions, as I never would have looked at using Ajax otherwise.
You can add a onclick event on submit button. On clicking it will create an ajax call send data to the required external PHP file and then on success will display the hidden division properly on the main page.
here's a sample code just for an explanation
**
* Description : Function that will trigger the AJAX request.
* #param none
*/
function CategorySubscriber_Unsubscribe(){
var data = {
'data-1': data-1,
'data-2': data-2,
// as per your need you can put any number of data
};
var url = // your url
jQuery.post(url, data, function(response){
jQuery.show("#your-div-id");
});
}
function(response) will be executed when ajax call will be in success status.
You can learn it from these links
http://www.w3schools.com/jquery/ajax_post.asp
http://api.jquery.com/jQuery.post/
I will try to walk you through this very slow. I am trying to make a poll that are subject to change often so I have to make it dynamical. I also need to have this without page reload, so I would need to use Ajax to submit the form. So what I did was to create a PHP script that will echo the poll for me. This works nicely and I get the poll just the way I want it. Oh yeah, forgot to tell that it is a multi step poll. I navigate through 2-4 questions at a time by hiding/showing divs within a JQM 'page'. And by that I mean:
<div data-role='page'>
At the last page I do have a submit button instead of a next button since the poll obviously has no "next" div to show. This submit button does in no way, shape or form work, and thus is the issue here.
$("#submit").click(function()
{
if ($("#form").validate())
{
$.ajax(
{
type:'POST',
url:'add.php',
data:$('#form').serialize(),
success:function(response)
{
$("#answers").html(response);
}
});
}
else
{
return false;
}
})
This is supposed to send my form data to another PHP file that is named add.php, when then is supposed to post it to the div shown abit underneath. (It's really supposed just to save to database but I try to echo it until I see that it works). Now, the twist is that I did another identical piece of code on a non-dynamical form that was not created through PHP, but merely plotted down in HTML. This was also a multi step poll that span out over 3 divs/'pages'. And this had no problems submitting at all.
So to summarize: I had 2 different projects that each handled half my problem. One generated the form dynamically and the other saved a static form that I made. Both forms consisted of a variety of checkboxes, radiobuttons and textareas. Problem is, they won't work together. When I click the submit button I expect the form to echo out the answers into this div (the one you read about a few lines up):
<div data-role="content" id="answers">
Answers comes here:
</div>
Nevertheless, this div remains the same. I stripped down the $("#submit").click(function()) to alert('test'); and I still could not get a reaction. I've quadrillion-checked the variable names and div names and any other names that are relevant, and I've made various minor adjustments on each separate part (both generating the poll and posting it with ajax) as well as to my attempt to combine them without success. So, the million dollar question is what could be wrong? My last remaining hypothesis is that somehow the JavaScript function for $("#submit").click ... is loaded before the script that generates the poll. This would make sense that when the submit click function is declared it would not be linked up to any button like shown here:
<input type="button" id="submit" name="Submit"/>
Does anyone have any clue on how I can make this submit button to work, or even have a clue as to why it does not work? Thanks to anyone who read this far and I hope you posess and are willing to share some knowledge that could help me. Also thanks to the creators of Stack Overflow for implementing an alt+z function for this as I accidentally clicked alt+a then random letters while writing the sentence before this one. Have a nice day!
EDIT: Tried this after a tip from Kevin an answer below, but even the first alert button doesn't react:
$("#submit").click(function()
{
alert("it works");
if ($("#form").validate())
{
$.ajax(
{
type:'POST',
url:'add.php',
data:$('#form').serialize(),
success:function(response)
{
$("#answers").html(response);
return false;
}
});
}
else
{
return false;
}
})
});
You need a return false; under $("#answers").html(response); inside the scope of the success function. Let me know if this works. Good luck, Kevin
I just tried the script above without the post and it worked fine. Do you have jquery loaded before this script executes, and/or do you have or do you have any javascript errors in your console?