Simple form submit without page refresh issue - javascript

I have simple application whose functionality works fine, I'm just having trouble making it user friendly. Basically it is a form where the users enters his name (required) and his request (also required).
When the form is submitted, his entry is stored in a MySQL database and on the same page all other requests from all users are shown, including the users request. All this should be done without page refresh (which is basically my problem).
My HTML code structure is as follows:
<div id="main">
<form action="" method="post">
Name: <input type="text" name="name" />
Request: <textarea name="request"></textarea>
</form>
</div>
<div id="totalRequest">
<!-- All requests fetched from database, including user's input -->
</div>
And the PHP:
<?php
if(!empty($_POST)) {
//form validation code
//if validation successful, execute code and send to MySQL
}
?>
To summarize, the user journey should be as follows:
User visits the page and sees the form, and other requests made by other people in the (#totalRequests) div. He then enters his own input (both fields required), and when validated, he should see his request displayed on top of the other requests.
I am not good with JavaScript or AJAX (at all). I know there are many tutorials online that offer similar projects, but all of them were either too complicated, or just not functioning the way I want them too.
I am not asking for a very big or advanced thing, I want the simplest solution possible. It doesn't need to be pretty or appealing to the eye as long as it gets the job done.
Sorry for taking so long, and thank you in advance.

You will not be able to submit data to the webserver without refreshing the page unless you use Jquery or AJAX.

Related

Is it possible to pass data to html form through a link to html file?

Here is an html form page
https://www.amazon.in/gp/help/customer/ces/phone-popup.html
which has input fields phone number and time to call.
Is it possible to pass the input data through link, so that it automatically submits the form with the data present in the link.
Can the link be modified to something like:
https://www.amazon.in/gp/help/customer/ces/phone-popup.html?num=9846098460&time=now
Simple and drastic answer: NO.
If YOU were the owner of the target site, you could foresee this kind of use...
Pretty rare uses for common people.
If not:
Are you trying some kind of an automatic query hack ??
Do you really think you will get such an answer on a public forum?
Think about it.
SO reviewers: CLOSE THIS QUESTION!
I wouldn't say so... The way the form data is sent to the remote server is probably through a HTTP POST request triggered from Javascript (when you click the "Call me" button). Therefore, it's not possible for you to automatically submit the form by passing the arguments in the URL.
You need to show code so we better help you but here's a thought.
Yoursite?date=jaz&id=2323;
In your form, you do something like
<input type="text" value="<?php if(isset($_GET['jaz']{echo $_GET['jaz']})) ?>"
Then in you Javascript
You can just submit the form when the page is loaded.
This is just a basic framework but you may want to consider security and check for emptiness when the actual form is submitted

Fail-safe way to validate forms in Javascript/Ajax rather than PHP?

Ok, so currently I handle all HTML form submissions in PHP. I submit the form to a PHP file which:
Checks against a cookie created at page load to prevent CSRF.
Contains a require_once() that handles validation.
Runs other logic.
If any of these steps fail, the user is redirected in PHP to the page they came from with an error message.
How I submit the form:
<form method="post" action="filename.php">
This system is fail-safe; as if anything goes wrong, the user is returned to the page they came from even with Javascript disabled.
So my question is; can I create a fail-safe system using just Ajax (an Ajax request to the server on form submission)? So that I don't need this PHP system at all? Is there a recommended procedure/tutorial for this?
I've avoided this so far as the overhead of having both a PHP form handling system as a fail-safe for potential hackers, as well as Ajax, can take several hours per form.
Just to clarify, I don't require support for users that have Javascript disabled. I just want to make sure my system if fail-safe in that situation. I've had a good look around, but it's proving difficult to find clarification on this.
The short answer for the most part is: no.
It is unwise to consider anything client-side as reliable or fail-safe, this is especially true when it comes to validating user input. A rule of thumb is: never trust the user.
Currently, per the description, your form is being submitted to a PHP script that validates form data. This way is going to be your best line of defense since you have a large amount of control on the data you are working with.
It sounds like you want to cut out the form submission and not force another page load. You can use AJAX to pass form information for validation to your script, but your PHP code is still going to be crucial to the validation process.
Basically you want to make your PHP validation solid. Next, start adding some AJAX calls that pass information from forms to your PHP code, but be prepared to fall back to standard form submission if AJAX is unavailable. If there are no problems with AJAX, you can still submit the data, have PHP do its processing, then return a payload indicating success or failure. Keep in mind though, in this context AJAX is just some sugar for the validation. You are only sweetening the deal by saving yourself having to reload a page and transfer the entire document again.
But remember: it is not reliable, and it is not fail-safe. Server side validation is the light at the end of the tunnel.

How do I execute php function on submit button in a FORM similar to onsubmit=" return javascript function"?

My goal: To process three objectives:
(1) Make insertion in a staging table before processing payment.
(2) Go to third party payment processing site like paypal using my form action attribute.
(3) Read the $_POST data from the payment landing page to determine if payment was successful and then take the data from the staging table and insert into real table.
My desired implementation would sth like:
<form name="demo" method="post" onsubmit="<?php insertStagingData() ?>" action="3rdpartyPaymentProcessingLink">
<input name ="Submit" type"submit" value"Submit">
</form>
I know that the web browser executes the onsubmit handler and when the handler completes, the browser proceeds with the form submit. I have used this concept for java script client side validation before forwarding the form to web server for php processing.
I dont know if this can be done when both handlers require server side processing, one on my webserver and the second on a 3rd party site.
Thanks in advance for suggestions and help!
The theory of a no-js solution would be something like this:
<form name="demo" method="post" action="/scriptOnYourServer.php">
<input name ="Submit" type"submit" value"Submit">
</form>
And then completely within scriptOnYourServer.php you would do any validation you want first, then do the staging table insert, then use the 3rd party payment PHP API (or restful service or soap service - whatever is available) to process payment - which you should then get a success/fail from, and you either display errors/offer retry or move from staging to a real table - all within this one request to your script.
If your goal is to avoid writing payment API integration code in PHP, then your basic outline will only work with javascript/AJAX if you must perform server side actions and still have the form action go to the payment processor, and typically a payment vendor that offers a form post solution will allow a "return URL" they can send the success/fail to where you do further processing which I think you are describing in your step 3.
So that is more like:
<form name="demo" method="post" onsubmit="jsFunctionName()" action="3rdpartyPaymentProcessingLink">
<input name ="Submit" type"submit" value"Submit">
</form>
<script type="text/javascript">
function jsFunctionName() {
// js ajax code, probably easiest to use a lib like jQuery for this
// You tell it the url on your server you will post vars to / generate a success/fail response, probably in json is best.
// based on your servers "insert into staging table" success/fail json response you decide whether to proceed or not (allow the submit to 3rd party), because you would not want to proceed if your staging table insert failed I presume
// so this implies you have a way to display errors in JS on this page, or you will be redirecting to a script of yours which would reload the page but display any errors - or you just completely ignore the possibility your staging data insert could fail and let the payment processor deal with it
}
</script>
See http://api.jquery.com/jQuery.ajax/
So with this a few moving parts -
your script - insertStagingData.php - it's job is to read the post data, you should do validation of some sort, then insert into your staging database (make sure you are using parametrized queries or sanitizing data since you are dumping user data into a database), then it generates a json response like:
{"success":true}
or
{"success":false}
And you need to have PHP use a JSON header - so at the end of this script you need to do something like this:
$response = array("success" => true); // or false depending on if your db insert was successful
header("HTTP/1.1 200 OK");
header('Content-type: application/json');
echo json_encode($response);
Then after that in the script block above in jsFunctionName, you will read the "success" variable from your json response and either display an error and return false or use preventDefault() to stop the submit to the 3rd party script, or if it is a success you allow the form submit to post.
Then you can setup a separate script for the payment processor to post back to where their docs will tell you what data they will post to you, and based on their success/fail you can display an error, or success and then move the data to the real table.
You may also want to consider the staging/real table should be the SAME table, with a column like payment_success = 0 or 1 where it is 0 by default and if the payment processor posts back success, you just update the record to payment_success=1. There are very few good reasons this should be a completely separate table.
This should hopefully help point you in the right direction. Good luck
PHP is a server-side scripting language. which means it executes code when a page request is made. Thing like onclick browser events can not cause a webserver to run code.
To facilitate this in PHP you will need to initiate the PHP function on the target form page.
Look into Paypal APIs in order to have a more advanced implementation.

Pass form data onto next page as text

I have an email sign up form generated by our ESP plugged into a webpage. When the user clicks submit, it takes them to a custom confirmation page we have created. I would like to display the email address they submitted on the confirmation page, so it says something like, 'Thanks for joining, you will now receive emails at [email address]'. Our ESP does not provide a way to do this. Is there is a simple way I can grab the email address from the form and pass it to the next page with JavaScript?
I've tried the solutions presented here, but if I try to update the form tag, the form breaks: http://www.webdeveloper.com/forum/showthread.php?232612-Pass-Variables-from-one-page-to-another-JAVASCRIPT-HTML
I found this article online but I don't understand how the cookie will record only the email address or how to retrieve this information on the next page: http://webdesign.about.com/od/cookies/a/aa083198.htm
Here is the current form code on my page:
<script type="text/javascript" src="https://app.e2ma.net/app2/audience/tts_signup/1723547/4d1180e592869543e75486faa4eb9d23/37406/?v=a"></script>
<div id="load_check" class="signup_form_message">
This form needs Javascript to display, which your browser doesn't support. Sign up here instead
</div>
<script type="text/javascript">signupFormObj.drawForm();</script>
I have very limited understanding of JavaScript and no understanding of PHP so the more specific reply you could give, the better. Any help is greatly appreciated. Thank you.
since you are submitting a form, hence have access to the email adress on the server side, why don't you just output it?
Javascript looses connection between pages as soon as it unloads. Your attempt to do this with javascript is WAYYYYYY to complicated for something HTML1 was able to do.

Spam Prevention/Reduction - Contact Form?

I want to add a simple Contact form to my web site so that customers can contact me easily.
<form>
NAME
<input type='text' name='name' />
EMAIL
<input type='text' name='email' />
MESSAGE
<textarea name='message' />
<input type='submit' />
</form>
This form would simply email me the customers message.
But, I also want to reduce (not, I'm not saying eliminate but at least reduce), SPAM.
I've looked into using CAPTCHAs but, ultimately, I don't want to hinder the customer with having to fill out extra information.
Any ideas of a good simple spam prevention/reduction method I could use for my Contact form.
A very simple trick I've been using with a surprisingly good success rate is this: Provide a text field that is hidden from human users with style="display: none", but with an enticing name like email. Most bots will fill in something in this field, but humans can't see it so they wont. At the server, just make sure the field is empty, else treat the submission as spam.
If you want to do a completely front-end solution I have had success recently by leaving the form action attribute blank, and populating it via a $(document).ready function. Most spambots use a browser that has javascript disabled, or are looking for hidden fields to avoid detection.
Example:
Your html would be:
<form method="POST" action="" id="contact-form">
and anywhere in that page you can use this to populate it.
<script>
$(document).ready(function(){
$("#contact-form").attr("action", "/yourMailScript.cgi");
});
</script>
A bot browser with no javascript will not get a form action, and they will get a 404 upon submission. Anyone with a normal browser (unless they have JS disabled for paranoid reasons) will get the normal behavior.
The only (client-side) way other than a CAPTCHA type user confirmation would be to write the whole thing dynamically. A lot (but not all) of robots would probably ignore the dynamic content. Eg
document.write("<"+"form>"
+" NAME "
+" <"+"input type='text' name='name' /> "
+"EMAIL "
+"<"+"input type='text' name='email' /> "
+"MESSAGE "
+"<"+"textarea name='message' /> "
+"<"+"input type='submit' /> "
+"<\/form> ");
Use Google or Yahoo mail account. They have good anti-SPAM filters.
Hidden fields, silly questions (what is 3+4?), etc, are not very effective at blocking spam on forms, IMHO.
I researched this several years ago, and came up with a solution I call "FormSpammerTrap". It uses JavaScript code to 'watch' for focus/onclick on required fields. Automated processes, unless highly customized for a specific site (which takes more time than spambot owners want to take), can't 'focus/onclick' a required field. (And there are some other techniques I use.)
I have a free solution at my www.FormSpammerTrap.com site. And there's a form there that spambots can try to spam...and they haven't, for more than 3 years. You are welcome to try it out...it's all open source, so you can see how it works. (And, if you use the form, I don't harvest your email. I reply once, then delete your email.)
My technique is much more effective in blocking spambots, IMHO. They haven't been able to spambot the contact form on that site.
**Added 12 Jul 2018 **
The trick is to add an on-click/on-focus event that changes the action parameter to the actual processing page. Otherwise, the default value I use is a honeytrap-type site. I think it's hard for a spammer to simulate those events, although possible perhaps. The technique blocks a lot of bot-spammers.
And still, after a couple of years using the technique on that site, the form hasn't been spammed by bots. (I define a bot spammer that sends multiple submits via the attack, not just one submit.)
Works for me.
You can add simple question, each serious person who wants to contact you, can easily answer. For example a field where he should enter the first letter of the domain. Most bots don't understand the question and will enter nothing or something random.
You could also try to track the time how long the user needs to input data. If he tries to send the form earlier than 5 seconds before typing the first word just don't allow to send it. Bots usually just parse the site, fill out everything and then post it and go to the next website.
#sec {
visibility: hidden;
padding: 0;
margin: 0;
height: 1;
}
<form method="POST" action="www.google.com">
NAME
<input type='text' name='name' />
<br /> EMAIL
<input type='text' name='email' />
<br /> MESSAGE
<textarea name='message' /></textarea>
<br />
<input type='text' name='security' id='sec' placeholder="Do not enter anything here" />
<input type='submit' formaction="" />
</form>
**Here, only a user who clicks on the submit button actually could submit the form. using auto submit simply redirects the bot to google.com.
**
*Also the input 'security' is an input field that is hidden to users, and visible to certain bots, known commonly as HoneyPot Captcha. On the server side, you can simply skip all the requests that has the 'security' field filled. Not every bot can be tricked this way, and this is where the attribute formaction comes into play *
grep for URI methods, urlencoded characters, or the two HTML markup characters, seems to work.
Use an anti-spam API like Akismet or Cleantalk. You can use the traditional checks for less sophisticated bots before hitting the API. An anti-spam API is the only way to catch spam submitted by a human.
I think that nowadays, most of the solutions posted are either inefficient or outdated.
reCAPTCHA is not a hassle for users any more
google documentation
reCAPTCHA v3 returns a score for each request without user friction.
The score is based on interactions with your site and enables you to
take an appropriate action for your site.
OP states that he needs an alternative to CAPTCHA, in order to avoid hassle for his users (up to v.2, reCAPTCHA requires user interaction). However, as of v.3, reCAPTCHA can detect bots "silently", without requiring user interaction.
Front-end-only solutions are inefficient
The honeypot (hidden input that only a bot could fill) and simple questions methods, as well as other front-end implementations, are still vulnerable to spam attacks. First of all, the spammer can bypass all front-end and post directly to the server. Therefore, a server-side check is required.
In addition, if someone wants to spam your site, specifically, he can easily read your source-code and build a script that is "clever" enough to not be caught by the front-end protection.
On the other side, reCAPTCHA v.3 tracks data and works behind the scenes, in Google's back-end, to determine if the user is actually human. Its logic is hidden, therefore, the attacker can not easily develop a "smarter" bot. In addition, the attacker can not just bypass the front-end; a token is created, is passed server-side and then to Google's back-end to be validated.
TL;DR
Nowadays, reCAPTCHA seems to be the best solution in all aspects. No user friction and the most secure.
Use JS technology. Like if a user comes on your contact page then javascript will generate a string or anything like that you prefer and put the information on a hidden text field. But it is not the actual solution, smart bot can easily crack it.
Another way is, You can also use email verification after contact form submission. And store the data on your database. If customer verifies the url through email then the contact information will mailed to you from database.
And also use delay to prevent continuous robot attack. Like sleep() in PHP code. This will add few delay in your code. By this way you can reduce random attacks but this is not the prevention method.
I found a nice idea on this page:
http://www.evengrounds.com/developers/alternatives-to-captcha
You can make your SUBMIT button display a confirmation page, on which you explain to user that he has to hit CONFIRM button to actually send a message. Spambots would usually only submit first form and skip the second step.
If you dont want to use recaptcha then you can use a service like Real Email and validate the emails server side before processing. Keep in mind that your probably want a way to report to the user if there is something wrong with the input.

Categories

Resources