Simple Validation with PHP using AJAX and JQuery - php

I am new to AJAX, and I want to learn how to validate a form. Suppose, I have a form with two input fields. When I click in submit I want to check the page with a php script. When the validation is succesfull I want to redirect to the action="submitForm.php". When one or more fields are not valid according to the validation.php I want to stay on the page and gives a error message next to the field.
What is the best way to do that?
<html>
<head>
</head>
<body>
<form action="submitForm.php" action="POST">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" name="submit" />
</form>
</body>
</html>
submitForm.php:
<?php
echo $_POST["username"];
echo "<br />";
echo $_POST["password"];
?>

In order to process the fields before actually submitting the form, you can catch its submit event:
<form action="submitForm.php" action="post" onsubmit="return MyValidation()">
Then, in your javascript:
function MyValidation() {
var valid = false;
$.ajax({
type: "POST",
url: "validation.php",
async: false,
data: { name: $('#username').val(), password : $('#password').val() }
})
.done(function( data ) {
if(data == 'true') {
valid = true;
}
});
// not valid, return false and show some hidden message
return valid;
}
(you need to add an ID to the <input> fields in order for the jquery selectors to work...)

There is two solutions who might help you
http://www.w3resource.com/ajax/working-with-PHP-and-MySQL.php
http://code.tutsplus.com/tutorials/submit-a-form-without-page-refresh-using-jquery--net-59

Related

keeping PHP form values after Submitting with false inputs [duplicate]

I have a classifieds website, and on the page where ads are showed, I am creating a "Send a tip to a friend" form...
So anybody who wants can send a tip of the ad to some friends email-adress.
I am guessing the form must be submitted to a php page right?
<form name="tip" method="post" action="tip.php">
Tip somebody:
<input
name="tip_email"
type="text"
size="30"
onfocus="tip_div(1);"
onblur="tip_div(2);"
/>
<input type="submit" value="Skicka Tips" />
<input type="hidden" name="ad_id" />
</form>
When submitting the form, the page gets reloaded... I don't want that...
Is there any way to make it not reload and still send the mail?
Preferrably without ajax or jquery...
I've found what I think is an easier way.
If you put an Iframe in the page, you can redirect the exit of the action there and make it show up.
You can do nothing, of course. In that case, you can set the iframe display to none.
<iframe name="votar" style="display:none;"></iframe>
<form action="tip.php" method="post" target="votar">
<input type="submit" value="Skicka Tips">
<input type="hidden" name="ad_id" value="2">
</form>
You'll need to submit an ajax request to send the email without reloading the page. Take a look at http://api.jquery.com/jQuery.ajax/
Your code should be something along the lines of:
$('#submit').click(function() {
$.ajax({
url: 'send_email.php',
type: 'POST',
data: {
email: 'email#example.com',
message: 'hello world!'
},
success: function(msg) {
alert('Email Sent');
}
});
});
The form will submit in the background to the send_email.php page which will need to handle the request and send the email.
You either use AJAX or you
create and append an iframe to the document
set the iframes name to 'foo'
set the forms target to 'foo'
submit
have the forms action render javascript with 'parent.notify(...)' to give feedback
optionally you can remove the iframe
Fastest and easiest way is to use an iframe.
Put a frame at the bottom of your page.
<iframe name="frame"></iframe>
And in your form do this.
<form target="frame">
</form>
and to make the frame invisible in your css.
iframe{
display: none;
}
SUBMITTING THE FORM WITHOUT RELOADING THE PAGE AND GET THE RESULT OF SUBMITTED DATA ON THE SAME PAGE.
Here's some of the code I found on the internet that solves this problem :
1.) IFRAME
When the form is submitted, The action will be executed and target the specific iframe to reload.
index.php
<iframe name="content" style="">
</iframe>
<form action="iframe_content.php" method="post" target="content">
<input type="text" name="Name" value="">
<input type="submit" name="Submit" value="Submit">
</form>
iframe_content.php
<?php
$Submit = isset($_POST['Submit']) ? $_POST['Submit'] : false;
$Name = isset($_POST['Name']) ? $_POST['Name'] : '';
if($Submit){
echo $Name;
}
?>
2.) AJAX
Index.php:
<form >
<input type="" name="name" id="name">
<input type="" name="descr" id="descr">
<input type="submit" name="" value="submit" onclick="return clickButton();">
</form>
<p id="msg"></p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
function clickButton(){
var name=document.getElementById('name').value;
var descr=document.getElementById('descr').value;
$.ajax({
type:"post",
url:"server_action.php",
data:
{
'name' :name,
'descr' :descr
},
cache:false,
success: function (html)
{
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
server_action.php
<?php
$name = isset($_POST['name']) ? $_POST['name'] : '';
$descr = isset($_POST['descr']) ? $_POST['descr'] : '';
echo $name;
echo $descr;
?>
Tags: phpajaxjqueryserversidehtml
A further possibility is to make a direct javascript link to your function:
<form action="javascript:your_function();" method="post">
...
It's a must to take help of jquery-ajax in this case. Without ajax, there is currently no solution.
First, call a JavaScript function when the form is submitted. Just set onsubmit="func()". Even if the function is called, the default action of the submission would be performed. If it is performed there would be no way of stoping the page from refreshing or redirecting. So, next task is to prevent the default action. Insert the following line at the start of func().
event.preventDefault()
Now, there will be no redirecting or refreshing. So, you simply make an ajax call from func() and do whatever you want to do when call ends.
Example:
Form:
<form id="form-id" onsubmit="func()">
<input id="input-id" type="text">
</form>
Javascript:
function func(){
event.preventDefault();
var newValue = $('#input-field-id').val();
$.ajax({
type: 'POST',
url: '...',
data: {...},
datatype: 'JSON',
success: function(data){...},
error: function(){...},
});
}
this is exactly how it CAN work without jQuery and AJAX and it's working very well using a simple iFrame. I LOVE IT, works in Opera10, FF3 and IE6. Thanks to some of the above posters pointing me the right direction, that's the only reason I am posting here:
<select name="aAddToPage[65654]"
onchange="
if (bCanAddMore) {
addToPage(65654,this);
}
else {
alert('Could not add another, wait until previous is added.');
this.options[0].selected = true;
};
" />
<option value="">Add to page..</option>
[more options with values here]</select>
<script type="text/javascript">
function addToPage(iProduct, oSelect){
iPage = oSelect.options[oSelect.selectedIndex].value;
if (iPage != "") {
bCanAddMore = false;
window.hiddenFrame.document.formFrame.iProduct.value = iProduct;
window.hiddenFrame.document.formFrame.iAddToPage.value = iPage;
window.hiddenFrame.document.formFrame.submit();
}
}
var bCanAddMore = true;</script>
<iframe name="hiddenFrame" style="display:none;" src="frame.php?p=addProductToPage" onload="bCanAddMore = true;"></iframe>
the php code generating the page that is being called above:
if( $_GET['p'] == 'addProductToPage' ){ // hidden form processing
if(!empty($_POST['iAddToPage'])) {
//.. do something with it..
}
print('
<html>
<body>
<form name="formFrame" id="formFrameId" style="display:none;" method="POST" action="frame.php?p=addProductToPage" >
<input type="hidden" name="iProduct" value="" />
<input type="hidden" name="iAddToPage" value="" />
</form>
</body>
</html>
');
}
This should solve your problem.In this code after submit button click we call jquery ajax and we pass url to posttype POST/GET
data: data information you can select input fields or any other.
sucess: callback if everything is ok from server
function parameter text, html or json, response from server
in sucess you can write write warnings if data you got is in some kind of state and so on. or execute your code what to do next.
<form id='tip'>
Tip somebody: <input name="tip_email" id="tip_email" type="text" size="30" onfocus="tip_div(1);" onblur="tip_div(2);"/>
<input type="submit" id="submit" value="Skicka Tips"/>
<input type="hidden" id="ad_id" name="ad_id" />
</form>
<script>
$( "#tip" ).submit(function( e ) {
e.preventDefault();
$.ajax({
url: tip.php,
type:'POST',
data:
{
tip_email: $('#tip_email').val(),
ad_id: $('#ad_id').val()
},
success: function(msg)
{
alert('Email Sent');
}
});
});
</script>
You can try setting the target attribute of your form to a hidden iframe, so the page containing the form won't get reloaded.
I tried it with file uploads (which we know can't be done via AJAX), and it worked beautifully.
Have you tried using an iFrame? No ajax, and the original page will not load.
You can display the submit form as a separate page inside the iframe, and when it gets submitted the outer/container page will not reload. This solution will not make use of any kind of ajax.
function Foo(){
event.preventDefault();
$.ajax( {
url:"<?php echo base_url();?>Controllername/ctlr_function",
type:"POST",
data:'email='+$("#email").val(),
success:function(msg) {
alert('You are subscribed');
}
} );
}
I tried many times for a good solution and answer by #taufique helped me to arrive at this answer.
NB : Don't forget to put event.preventDefault(); at the beginning of the body of the function .
I did something similar to the jquery above, but I needed to reset my form data and graphic attachment canvases.
So here is what I came up with:
<script>
$(document).ready(function(){
$("#text_only_radio_button_id").click(function(){
$("#single_pic_div").hide();
$("#multi_pic_div").hide();
});
$("#pic_radio_button_id").click(function(){
$("#single_pic_div").show();
$("#multi_pic_div").hide();
});
$("#gallery_radio_button_id").click(function(){
$("#single_pic_div").hide();
$("#multi_pic_div").show();
});
$("#my_Submit_button_ID").click(function() {
$("#single_pic_div").hide();
$("#multi_pic_div").hide();
var url = "script_the_form_gets_posted_to.php";
$.ajax({
type: "POST",
url: url,
data: $("#html_form_id").serialize(),
success: function(){
document.getElementById("html_form_id").reset();
var canvas=document.getElementById("canvas");
var canvasA=document.getElementById("canvasA");
var canvasB=document.getElementById("canvasB");
var canvasC=document.getElementById("canvasC");
var canvasD=document.getElementById("canvasD");
var ctx=canvas.getContext("2d");
var ctxA=canvasA.getContext("2d");
var ctxB=canvasB.getContext("2d");
var ctxC=canvasC.getContext("2d");
var ctxD=canvasD.getContext("2d");
ctx.clearRect(0, 0,480,480);
ctxA.clearRect(0, 0,480,480);
ctxB.clearRect(0, 0,480,480);
ctxC.clearRect(0, 0,480,480);
ctxD.clearRect(0, 0,480,480);
} });
return false;
}); });
</script>
That works well for me, for your application of just an html form, we can simplify this jquery code like this:
<script>
$(document).ready(function(){
$("#my_Submit_button_ID").click(function() {
var url = "script_the_form_gets_posted_to.php";
$.ajax({
type: "POST",
url: url,
data: $("#html_form_id").serialize(),
success: function(){
document.getElementById("html_form_id").reset();
} });
return false;
}); });
</script>
I don't know JavaScript and I just started to learn PHP, so what helped for me from all those responses was:
Create inedx.php and insert:
<iframe name="email" style=""></iframe>
<form action="email.php" method="post" target="email">
<input type="email" name="email" >
<input type="submit" name="Submit" value="Submit">
</form>
Create email.php and insert this code to check if you are getting the data (you should see it on index.php in the iframe):
<?php
if (isset($_POST['Submit'])){
$email = $_POST['email'];
echo $email;
}
?>
If everything is ok, change the code on email.php to:
<?php
if (isset($_POST['Submit'])){
$to = $_POST['email'];
$subject = "Test email";
$message = "Test message";
$headers = "From: test#test.com \r\n";
$headers .= "Reply-To: test#test.com \r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($to, $subject, $message, $headers);
}
?>
Hope this helps for all other rookies like me :)
Modern Answer without XHR or jQuery
It's 2022, we don't need to use old tools like XHR or jQuery when we have the Fetch API and the FormData API!
The first thing we need to do is prevent the default form submission behavior from occurring with event.preventDefault():
form.addEventListener("submit", function(event){
event.preventDefault();
// ...
});
Now we need to replace the submission behavior with our own AJAX request. The Fetch API makes it pretty simple to post form data - just create a new FormData object, populating it with the form's values, and use it as the body of a fetch request:
fetch(form.action, {
method: "post",
body: new URLSearchParams(new FormData(form))
});
Note that this submits an HTTP request using the multipart/form-data format. If you need to post the data using application/x-www-form-urlencoded, create a new URLSearchParams object from the FormData object and use that as the fetch's body.
fetch(form.action, {
method: "post",
body: new URLSearchParams(new FormData(form))
});
Here's a full code example:
let form = document.querySelector("form");
form.addEventListener("submit", function(event){
event.preventDefault();
fetch(form.action, {
method: "post",
body: //new FormData(form) // for multipart/form-data
new URLSearchParams(new FormData(form)) //for application/x-www-form-urlencoded
});
});
<form method="POST">
<input name="name" placeholder="Name" />
<input name="phone" type="tel" placeholder="Phone" />
<input name="email" type="email" placeholder="Email" />
<input name="submit" type="submit" />
</form>
The page will get reloaded if you don't want to use javascript
You will need to use JavaScript without resulting to an iframe (ugly approach).
You can do it in JavaScript; using jQuery will make it painless.
I suggest you check out AJAX and Posting.
if you're submitting to the same page where the form is you could write the form tags with out an action and it will submit, like this
<form method='post'> <!-- you can see there is no action here-->
Here is some jQuery for posting to a php page and getting html back:
$('form').submit(function() {
$.post('tip.php', function(html) {
// do what you need in your success callback
}
return false;
});

validate form before submition

I want to submit a form with php variables to input into javascript, the problem is that the variables are only set after posting, which is too late for them to be echoed into the javascript. Of course, if I then submit again, the variables have been implemented into the javascript and it works as it should. However, I would prefer just to submit once.
Is there any way to validate the form before submission ? Here is an example of my dilemma:
<?php
if(isset($_POST['submit'])){$name=$_POST['name'];}
?>
<html>
<div id="message"></div>
<form action="home.html" method="POST">
<input type="text" name="name">
<input type="submit" name="submit" value="conditions-met"
onclick=<?php if($name=="bob"){echo"start();";}?>>
</form>
</html>
<script type="text/javascript">
function start(){
document.getElementById('message').innerHTML = 'hello bob';
return true;
}
</script>
Man people are mean to you!!
Basically you should validate the fields using JavaScript.
When the submit button is clicked do the checks. Continue on success, show an error message on failure.
example
<form id="myForm" onsubmit="return ValidateFields(this)" name="myForm" accept-charset="UTF-8" enctype="multipart/form-data"" action="myPhpScript.php" method="POST">
// html fields
</form>
<script>
function ValidateFields(formObject)
{
var FieldsValid = true;
//Validate the fields and if one of them is not valid set FieldsValid to false
if(!FieldsValid )
{
//show an error message
return false; // Returing false will prevent the form from submitting
}
return true;// the form will be submitted
}
</script>
In order to become a ninja please read the following:
http://www.script-tutorials.com/form-validation-with-javascript-and-php/
http://www.webcredible.co.uk/user-friendly-resources/dom-scripting/validate-forms-javascript.shtml
http://www.w3schools.com/js/js_form_validation.asp
<html>
<div id="message"></div>
<form action="home.html" method="POST" onsubmit="return validate()">
<input type="text" name="name" id="name">
<input type="submit" name="submit" value="conditions-met" >
</form>
</html>
<script type="text/javascript">
function validate(){
name=document.getElementById('name').value;
if(name == "")
{
document.getElementById('message').innerHTML = 'Please Fill Name';
return false;
}
return true;
}
</script>
You can do it with Ajax and beforeSubmit function with Jquery You have:
$.ajax({
url: "your async page in php",
cache: true,
data: $("#formID").serialize(),
type: 'POST',
beforeSend: function(){
/* You can validate your input here*/
},
success: function(response){
/* Based on the response from php you can handle the message to the user*/
},
error: function(response){/*Error Handler*/},
complete: function(){/*If it's complete than you can reset the form*/}
});
I think it's easy and more clear if you use cross Ajax/PHP request
The function bound to the onclick-event must return true if validation is correct, or false otherwise.
The same function must be in javascript. You cannot call a php function in it. If you want php, try ajax.
<input type="submit" onsubmit="return validate();" />
<script>
function validate() {
// do validation in javascript
// or make an ajax request e.g. to
// /validate.php?name=somename&surname=someothername
// and let this request answer with true or false
// return true if valid, otherwise false
}
</script>

On form validation jquery updates the div

I`m trying to make somethig like login with jquery. There should be a validation on text fields to echo error message. If the form is completely validated then function in jquery should update the div, where there is the input form and change it to the session name. But There is a problem, when posted form is validated then div remains empty, there is no session name.
HTML:
<html>
<head>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
jQuery(function(){
jQuery('#form').submit(function(){
jQuery.ajax({
type: 'POST',
url: jQuery('#form').attr('action'),
data: jQuery('#form').serialize(),
success: function(data){
if(data == 'success'){
jQuery('#user').load(location.href+' #user>*');
}else{
jQuery('#info').html(data);
}
}
});
return false;
});
});
</script>
</head>
<body>
<div id="user">
<div id="info"></div>
<?php
session_start();
if(isset($_SESSION['user'])){
echo $_SESSION['user'];
}else{
echo '
<form method="post" action="session.php" id="form">
<input type="text" name="user" />
<input type="submit" name="do" value="ok" />
</form>
';
}
?>
</div>
</body>
</html>
PHP:
<?php
$user = mysql_real_escape_string($_POST['user']);
if(empty($user)){
echo 'psc';
}else{
echo 'success';
session_start();
$_SESSION['user'] = $user;
}
?>
I think type: 'POST' in your ajax call is usually done in lower case: type: 'post'. I am not sure if this is the issue, but you may want to try it.
Aside from that, the other problem with your code is that you are not preventing the form from being submitted. So basically you are sending an ajax message, but then immediately loading a new page with the default submit that occurs when clicking the submit button. I would think that this has the effect of loading a blank page?
To fix this you could add to your submit handler the following lines:
jQuery('#form').submit(function(event){
event.preventDefault();
Notice I have added event to the handlers arguments, and then called the preventDefault() method to stop the form from actually submitting. Returning false in the handler does not do this for you.

form submit inside div with empty action

Simply my problem is that i want to submit a form in a div with empty action as the php script in the same page,
a simple example to illustrate as my page is too long
<html>
<head>
<script>
$(document).ready(function() {
$("#myDiv").delegate("form", "submit", function(event) {
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function(response) {
$("#myDiv").slideUp(500, function() {
$("#myDiv").html(response);
$("#myDiv").slideDown(500);
});
}
});
return false;
});
});
</script>
<head>
<form method="post" action="">
<p> enter your name</p> <input type="text" name="name" />
<input type="submit" name="save" />
</form>
<?php
if (isset($_POST['save'])) {
echo $_POST['name'];
}
?>
</html>
the problem that the action of the form is empty and so when i click submit button nothing happen, so anyone knows how to solve the problem?
PS: it's too hard to extract the php script in extrnak file, i am searching for alternative solution.
For .delegate to work you have to wrap #myDiv around the selector you wish to target, because the targeting is equivalent to:
$('#myDiv').find('form').on('submit', ...
In other words, your form must be wrapped inside #myDiv.
tried like this?
<?php
if (isset($_POST)) {
echo $_POST['name'];
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
This will put the current script address in the action field.
try using a hash symbol. action="#"

why does this text input not cache?

I have two web pages which work basically the same, code-wise, but one of them does not seem to cache information. By 'cache', I mean on the client/browser side. The text field does not retain previously entered information. In the first example below, if you register and then log in, the next time you log in, your username will be cached in the the browser to be selected; while in the second example, it does not retain that info.
http://www.dixieandtheninjas.net/hunter/ has a login prompt. once you've logged in once from a browser, when you revisit the page it has cached your username.
http://www.dixieandtheninjas.net/dynasties/ also has a login prompt, but it does not cache! And I cannot figure out why.
Perhaps because the second one is not within FORM tags? Maybe there's some other tiny coding mistake I've made which causes this.
Here's the code from the first example:
<form method = "post"
action = "">
Username: <input type="text" name="login_name" value="" />
<br><br>
Password: <input type="password" name="password" value="" />
<br><br>
<input type="submit" value="Login" />
</form>
Here is code from the second example: Note that the clicks are handled by jquery in the second example, while the first just uses pure html and php
<p>
Email address: <input type="text" id="logininfo" value="" />
<br>
Password: <input type="password" id="password" value="" />
<br>
<input type="button" id="loginbutton" value="Login" />
</p>
Here is the jquery used in the second example:
<script type ="text/javascript">
$(function(){
$('#loginbutton').click(function(){
var loginvar = $('#logininfo').val();
var passvar = $('#password').val();
//alert(loginvar + ", " + passvar);
if (loginvar != '' && passvar != '') {
var subdata = {
logindata : loginvar,
passdata : passvar
};
$.ajax({
url: "index_backend.php",
type: 'POST',
data: subdata,
success: function(result) {
//alert(result);
if (result == '1') {
// success
window.location.replace("http://www.dixieandtheninjas.net/dynasties/playermenu.php")
} else if (result == '2') {
//$('#logininfo').empty();
$('#logininfo').attr('value', '')
$('#password').attr('value', '')
alert("Login failed. Please try again, or register if you have not already created an account.");
} else {
alert("Something has gone wrong!");
alert (result);
}
} // end success
}); // end ajax
} else {
alert ("Please enter a username and password.");
}
}); /// end click function for button
}); //// end
</script>
Since you aren't truly submitting the form in the jQuery one, the browser doesn't know that the user has attempted to use this as input vs just typed something in and then went to another page. Because of that, you won't be seeing it in the stored form data.

Categories