Alright, I know there are many questions/answers for a modal contact form, but I would like to know how I can have a normal contact form on the page and when submitted, the PHP action is popped up in a modal, saying "Thanks for contacting us", or something along those lines, and then the ability to close. I've done HTML contact forms and hooked in the PHP action before, just never in a modal... Any simple solutions (without the use of plugins)?
If anyone has this question and wants it answered, please be sure to vote up.
If you want to have a javascript-free solution, then your form-handling script will need to be able to present all states of the form. These include:
initial unfilled form
response to first submission which may be:
display of partially or incorrectly filled form with errors marked
thank-you message
response to thank-you message
A modal popup is only a translucent container element (e.g. <div>) styled to be z-positioned on top of all the other html (except its children) and to cover the entire viewport. It contains a form and anything else you might like. When it is not in use, its display attribute is set to none.
So your php form handler might work something like this:
$modalclass='modalhide';
$filteredpost=array();
if(isset($_POST['submit1']){ //user submitted form data
//validate submitted data
$filteredpost = my_cleanup_function($_POST);
if(my_form_is_good($filteredpost){
$modalclass='modalshow';
$filteredpost=array();
}
}
echo <<< EOF
<form method='POST' name='mainform' action='myhandler.php'>
//other form fields
<input type='submit' name='submit1'>
</form>
<div class='$modalclass'>
<form name='thanksmodal' method='POST' action='myhandler.php'>
//content of some sort
<input type='submit' name='thankssubmit'>
</form>
</div>
EOF;
The AJAX method is similar except that a javascript intercepts the submit button actions, submits to a form-handling script asynchronously and presents the results. There are lots of javascript libraries around to make this easier. jQuery and jQuery-UI are my two favourites.
Related
I am trying to submit a form using a hyperlink and it is not posting values onto the next page.Here is my code form:
<?php
$email = array('name'=>'accountno','id'=>'accountno','value'=>set_value('email'));
?>
<form method="post" id = "login_form" action="/salesrep/check" name = "login_form" class="custLogin">
<fieldset style="color: #BD1313; width: 440px;"> <input type="hidden" name="submit_type" id="submit_type" value="account_only">
<br><center><label for="customerNo"><b>Customer No:</b></label>
<? echo form_input($email);?>
Submit<? echo form_input($button);?> </center>
<p> </p>
</fieldset>
</form>
The code on the next page looks like this:
<?
print_array($_POST);
die();
?>
When i use the button here,it posts values to next page successfully.BUT I HAVE not been able to post values using the hyperlink on onclick event. Where i am making mistake??
Why i am getting empty array when i am already inserting value in the text box.?? Or is there any way i could post values using the link and retrieve them in the next page???
The real problem is that you are trying to use a link plus some JavaScript to submit a form in the first place. Don't do this. Buttons inform users that they will submit the form. They will show up in screen readers when they are in forms mode (a link with some JavaScript won't). They "just work".
If you insist on using a link and some JavaScript, then the reason that your code doesn't work is that the JavaScript runs, the form starts to submit, then the link is followed and a GET request is made to the page instead.
Normally you could call preventDefault on the event to stop this, but you are using old style intrinsic event attributes so you need to return false; from there instead.
Recommended reading: Progressive Enhancement and Unobtrusive JavaScript
I've been trawling through all the suggested posts for this topic but can't seem to find a solution that either works for me or I quite understand.
I am just trying to do a simple honeypot which checks if a hidden field is filled in by bots and breaks the form if so. My problem seems to be when it comes to using AJAX to see if the PHP value cleared. Hope that makes sense as I'm not well versed in coding languages.
My original idea was to disable the submit button for any bots that fill out the field. However seeing as the field is blank straight out the form loads the submit button and the point is lost.
This is the part of the form checking for the bots:
<!-- THE HONEYPOT -->
<li id="artificial-detect">
<label for="artificials">If you see this, leave this form
field blank and invest in CSS support.</label>
<input name="artificials" type="text" value="">
</li>
<!-- /HONEYPOT -->
<?php
$spam = $_POST['artificials']; // This is our Honeypot field
if($spam) { // If the Honeypot field has been filled in
die("No spamming allowed bitch!");
} else { ?>
<li class="last">
<input class="submit" type="submit" name="submit">
</li>
<?php } ?>
I don't understand what to do now:
jQuery.('#salesforce-crm-form .submit').click(function(){
jQuery.ajax({
// Get PHP function that determines whether the honeypot has been snatched.
});
});
I am using an external URL for the action="" so I thought maybe that could only be inserted if the PHP returns clean of bots.
You cannot do the things in the order you think.
First PHP runs to deliver your form.
Then the browser acts, displays the form to the user. He might enter data and send it back.
Then PHP is on again, checking the form values.
You pretty much have the code you want to check if the honeypot field is filled. You should not try to use AJAX, because this PHP check can only be taking place after sending the form. Simply don't do what the form is intended to do if you detect spam.
BTW, Bots dont press submit buttons. Bots send Request based on parsing forms, disabling all Javascript.
[EDIT]
If your form goes to an external URL, then you cannot control any spam detection. Because bots do not use Javascript, anything on this level will not work, either, but thats what you are trying to do.
Only thing that will work is to NOT send the form to the external URL directly, but to a PHP script on your server that will check for spam an then send it to the original destination. Don't know if this will mess up anything else because now it is not the users browser sending the form, but your server. If there is any detection and/or usage of request metadata on that side, you are interfering with this.
Put default value in honey pot input and ask user to delete it before post. Also there is no use for disabling submit button:) Bots do not work this way, they will simply submit form without clicking anything.
If you change the type of the input box to hidden, and give it an ID, like so
<input name="artificials" type="hidden" id="honeypot" value="">
then users will not be able to see the input but bots will fill it in.
Then in your javascript, using jquery you can check for a value like so
var honeypot = $('#honeypot').val();
if(honeypot == '' || honeypot == null) {
// Call ajax function
}
Note, that has not been tested and is only an example.
I have a simple form which accepts a Title and a Contents variable from a textbox and a textarea. The form will send its data to a file called add-post.php. However, I am looking for a way to alert the user that either the textbox or the textarea has invalid data (is empty) in case they click the submission button.
I was thinking that an alert() popup box would be the best idea because it doesn't redirect to any other page and the user never loses their data (imagine they entered a whole lot of text but forgot a title. Sending the data to add-post.php and performing the check there will result in loss of data for the user).
However, I'm not sure how to actually implement the alert() popup. How would I make it so that the check is done AFTER they have clicked the submit button but BEFORE the data is sent off to the next file. Any advice is appreciated.
On your form add something like this
<form name="frm1" onsubmit="InputChecker()">
Then in javascript
<script type="text/javascript">
function InputChecker()
{
if(document.getElementById({formElement}) != '') { // not empty
alert("This element needs data"); // Pop an alert
return false; // Prevent form from submitting
}
}
</script>
Also as others have said jQuery makes this a little bit easier. I highly recommend the jQuery Validate Plugin
Some people do find the alert box "annoying", so it may be better to append a message into the DOM to let the user know what needs to be fixed. This is useful if there are numerous errors as the errors will be more persistent allowing the user to see all the things they need to be fixed. Again, the jQuery Validate plugin has this functionality built in.
Attach an onsubmit event to the form, and return false; to stop the submission if checks fail.
Form validation with Javascript. Or easier with jQuery.
Basically, validate the form when the submit button is clicked (with an onsubmit handler), and then use an alert() box if needed. By the way, people usually hate alert boxes.
You have a number of options when it comes to client side validation. This is just one.
<form id="tehForm" method="post">
<input type="text" id="data2check" >
<input type="button" id="btnSubmit" />
</form>
<script type="text/javascript">
function submit_form(){
if(document.getElementById("data2check").value!="correct value"){
alert("this is wrong");
}else{
document.getElementById("tehForm").submit();
}
}
</script>
For a more indepth example check out this link
I am using the project 'ModalBox' from http://okonet.ru/projects/modalbox/index.html in order to generate my modal.
I am also using this overall script that persists e-mails submitted via form into a basic text file as a simple/quick solution. http://www.knowledgesutra.com/forums/topic/25586-php-simple-newsletter-script/
I have a dilemma though.
In order to keep the modal and display my 'mailing_thankyou.php' my form has to have 'onsubmit="return false"' but in order for my php script to work, I have to remove that return false, but then it changes to a new page in order to persist that information.
Does anyone have any ideas?
This is the main part in question:
myModal.html
<div id="signUp">
<form action="mailer/mailing.php" id="myForm" method="post" class="style16">
<input type="text" name="email" size="30" value="your email here!">
<input type="submit" value="Send link" name="submit" onclick="Modalbox.show('mailer/mailing_thankyou.php', {title: 'Form sending status', width: 500, params:Form.serialize('myForm') }); return false;">
or Cancel & close
<!-- ><input type="submit" value="GO!" name="submit"> -->
</form>
</div>
You may pull my files from my git repo:
https://github.com/jwmann/Modal-Sign-up
I'm not good at Mootools, so I will give you an example in jQuery - if you get the idea, I'm pretty sure you will find the right syntax for Mootools too.
The idea is to use AJAX call for form submission (and keep the onsubmit="return false;" so that browser window isn't reloaded):
var $form = $('#myForm');
$.post($form.attr('action'), $form.serialize(), function(response) {
$('div#signUp').html(response);
});
What this does is:
Stores jQuery wrapped form element into $form
Uses form's action attribute value as a request target address
Serializes and transfers all form elements' values
Executes callback function, which takes returned HTML code and replaces contents of <div id='signUp'>...</div> with this HTML.
Note: make sure that the script at forms action only returns html for the contents of the sign up box (meaning no <head>, <body>, etc. - only what should be in the box afterwards)
EDIT/AMENDMENT
This is what I've just found out on MooTools Docs page for Ajax/Request:
The equivalent of my jQuery snippet in MooTools would be
new Request.HTML({ // Creates an AJAX request
'url': $('myForm').get('action'), // Sets request address to the form's action
'update': $('signUp') // Indicates that results should be auto-loaded into element with id='signUp'
}).post($('myForm')); // Indicates that this form has to be serialized and transferred; also starts the request process
This requires that the form's action returns the result to display (a thank you message). One could achieve that by making redirect from the server-side after form data has been successfully processed, e.g. in PHP header('Location: mailer/mailing_thankyou.php'); exit;
After looking longer at your code I realized, that this is not entirely what you want (as I see you don't want the form replaced with the thank-you message - you want it to be shown in the modal). Hence the updated solution for your case:
new Request.HTML({ // Creates an AJAX request
'url': $('myForm').get('action'), // Sets request address to the form's action
'onSuccess': function() { // Defines what to do when request is successful (similarly you should take care of error cases with onFailure declaration
Modalbox.show('mailer/mailing_thankyou.php', {
title: 'Form sending status',
width: 500
// I have removed params from here, because they are handled in the .post() below
});
}
}).post($('myForm')); // Indicates that this form has to be serialized and transferred; also starts the request process
Pardon me if any of this doesn't work (as I said, I'm more of a jQuery guy - just trying to help here)
Have the form submit to a hidden iframe on the page. Give the iframe a name value and then set a target propery on the form. You can make the iframe 1x1 pixel and set the visibility to hidden (if you hide via display: none it might not work in all browsers.)
See this question for details:
How do you post to an iframe?
I removed the 'return false' from the input submit's 'onsubmit' (duhhh facepalm) because it was trying to serialize it in the first palce with prototype.js
Then I changed the php script so it would grab with $_GET instead of $_POST
no added functionality or hacks needed. Thank you for all the help though.
My problem is, that the browsers' (IE&FF) autocomplete does not work for my login form.
I have a webapp with CakePHP & jQuery. To allow visitors to login/register unobtrusively. The login form is inside a div, which is loaded via AJAX. (This enables logging in without a page reload.)
The browsers do recognize it as a login field, as they prompt me to save the credentials when clicking login. And they really do save the username/password, as they appear between the saved ones in the browser settings. But the saved username/password is never entered automatically. They do not appear pre-entered when the page loads. When I start typing in the username, the username appears as a suggestion, but even when you select it, the password is not entered next to it. Why? How can I get this working?
That you can test it yourself, here is a simple AJAX login form:
http://gablog.eu/test/ajaxlogin.html
It loads the following login form, if you go to the url below, autocomplete will work for just the plain form, so it is not a problem with the form itself, but rather that it is AJAX loaded:
http://gablog.eu/test/loginform.html
The layout:
<div id="user-bar">
<script type="text/javascript">
$(function() {
$("#user-bar").load('loginform.html').html();
});
</script>
</div>
The view loaded (when not logged in):
<form id="form-login" action="" onsubmit="login(); return false;">
<input type="text" id="username" name="username"/>
<input type="password" id="password" name="password"/>
<input type="submit" value="Login"/>
<div id="login-error" class="error-message"></div>
</form>
<script type="text/javascript">
function login() {
$.post('/ajax/login', $("#form-login").serialize(), function(data) {
if (data.success) {
$("#user-bar").load('userbar.html').html();
} else {
$("#login-error").html(data.message);
}
}, "json");
}
</script>
To clarify: I do not want to use AJAX autocomplete, I want the browser's autocomplete to work for my login form. This is an issue between my form and the browser. jQuery submission seems to play a minor role, as the usernames/passwords are saved. They are just not auto-entered for ajax loaded HTML elements! (The test site does not use jQuery submission.) Related question: browser autocomplete/saved form not work in ajax request
Autocomplete, in Firefox at least, triggers during page load. Adding the content afterwards would miss the window of opportunity.
A login form is tiny. I'd include it in the page from the outset and consider hiding it with CSS until it is wanted.
In case it helps, msdn says (towards the bottom of the page):
Note: if both of the following
conditions are true:
The page was delivered over HTTPS
The page was delivered with headers or a META tag that prevents
caching
...the Autocomplete feature is
disabled, regardless of the existence
or value of the Autocomplete
attribute. This remark applies to IE5,
IE6, IE7, and IE8.
I've emboldened the interesting bit.
.
I don't think you can get the form autocomplete to work if you load the form via ajax (security-wise I don't know if it can be really be abused or not, but the fact that a script could start loading fields into the page to see what data gets inserted doesn't look too good to me).
If you can, the best option would be to add a conditional block to the php file and include the form or not depending on whether the user is logged or not. If for some reason you can't do that, you might want to try to do a document.write() instead of the ajax call (and yes, using document.write is ugly :)
I see case when login form has to be pulled with ajax - if rest of the website loads as static html (cache). Login form (or authed user info) cant be displayed statically.
So your solution is to pull the form right after declaration (end tag) of the DOM element that serves as parent element for ajax-pulled loginform's html, ex:
<div id="loginforms_parent"></div>
<script language="javascript">
/* ajax request and insert into DOM */
</script>
And browser has the form in DOM onLoad. Tested, firefox does autocomplete in that case.
I'm not happy with loading the login form into my page at load time so I filed a issue with Chrome instead;
http://code.google.com/p/chromium/issues/detail?id=123955&thanks=123955&ts=1334713139
there is answer given : http://www.webmasterworld.com/javascript/4532397.htm . it does something with submit method and then uses click method. as i know values are not saved if form is not submitted. i think author of that solution just makes it submitted though submit button is not clicked by user.