I have a form
<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>
<fieldset>
<legend>User Details</legend>
<div><label for="post[uname]">Username <em>*</em></label> <input id="post[uname]" type="text" name="uname" value="" /></div>
<p class='note' id='err[Name]'></p>
</fieldset>
<div class="buttonrow">
<input type="submit" value="Submit This Form via AJAX" class="button" />
<input type="button" value="Start Again" class="button" />
Refresh this Page
</div>
</form>
I have two arrays post and err. I'm trying to send them to php and then in php it will json_encode the array and print it on the screen like so:
{
"err": {
"uname": "Please enter a user name"
}
"post": {
"uname": ""
}
}
or this is if the user did enter a name:
{
"post": {
"uname": "Bob Ross"
}
}
There could be multiple fields for post and err but it should still follow the same suite.
How do I send the data to php, I understand it's some sort of serializeArray but it doesn't format it properly when I do:
JSON.stringify($("#ajax-form").serializeArray())
A jsfiddle to full html:
https://jsfiddle.net/dzv8ttjn/1/
Your best bet is to call .serialize(); on the form which will give you something like: user-name=some%20name&email=some%20emale&gender=Female&interests=Software
Send that to the PHP script, and have the script create the format of the response while looping over the $_POST array. Something like the below would work:
(note that I've changed your id's to be more sensible and updated the jQuery version used)
<?php
if(count($_POST)>0){
$response = ['err'=>[], 'post'=>[]];
foreach($_POST as $key => $value)
{
$response['post'][$key]=$value;
if(trim($value) == '') $response['err'][$key]='Please enter a '.$key;
}
echo json_encode($response);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Lab4: Form Validation with AJAX,JQuery,JSON and PHP</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script type="text/javascript">
$("#ajax-form").on('submit', function(event) {
event.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
// url: "page.php", // add this line to send to some page other than the this one
data: dataString,
success: function(response) {
if (response) {
alert('test worked');
}
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
</script>
</head>
<body>
<div id="wrapper">
<h2>Form Validation with AJAX,JQuery,JSON and PHP</h2>
<div class="form-container">
<span id="ajax-message"></span>
<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>
<fieldset>
<legend>User Details</legend>
<div>
<label for="uname">Username <em>*</em></label>
<input id="uname" type="text" name="user-name" value="" />
<p class='note' id='name-error'></p>
</div>
<div>
<label for="password">Email Address <em>*</em></label>
<input id="password" type="text" name="email" value="" />
<p class='note' id='password-error'></p>
</div>
<div>
<label for="post[gender]">Gender <em>*</em></label>
<input type="radio" name="gender" value="Male" class="form-check-input" id="Male" required> Male
<input type="radio" name="gender" value="Female" class="form-check-input" id="Female" required> Female
<p class='note' id='gender-error'></p>
</div>
<div>
<label for="interests">Interests<em>*</em></label>
<input type="checkbox" name="interests" value="Music" class="form-check-input" id="Music"> Music
<input type="checkbox" name="interests" value="Software" class="form-check-input" id="Software"> Software
<input type="checkbox" name="interests" value="Hardware" class="form-check-input" id="Hardware"> Hardware</div>
</fieldset>
<div class="buttonrow">
<input type="submit" value="Submit This Form via AJAX" class="button" />
<input type="button" value="Start Again" class="button" />
Refresh this Page
</div>
</form>
</div>
<h3>JSON Array</h3>
<pre id='debug'></pre>
</div>
</body>
</html>
Related
I'm using the script below to automatically add new lines in a form, but I do not see how to retrieve the values of each field under PHP with $_POST.
If someone has already had this problem with a table in a form, thank you for helping me!
what procedure to retrieve in test5.php the values of the fields.
I do not know how to get an array in a $_POST
thank you in advance
Here is my script
<html>
<head>
</head>
<body>
<form action="test5.php" method="post">
<div id="address">
<div id="1" name="address[]">
<input id="mail" type="text" />
<input id="type" type="text" />
<input id="comment" type="text" />
×
</div>
</div>
<input id="add_address" type="button" value="Ajouter" />
<input type="submit" value="Create PDF" />
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$('#add_address').click(function(event) {
var lastDiv = $('#address > div').last();
var id = parseInt(lastDiv.attr("id")) + 1;
(lastDiv.clone(true).attr("id", id)).insertAfter(lastDiv).find(".removeclass").show();
return false;
});
$('body').on('click', '.removeclass', function(event) {
$(this).parent().remove();
return false;
})
</script>
</body>
</html>
1.) Remove the name-attribute from the div-element
2.) Build your input-elements like:
<div id="..">
<input type="..." name="address[1][mail]" />
<input type="..." name="address[1][type]" />
<input type="..." name="address[1][comment]" />
</div>
<div id="..">
<input type="..." name="address[2][mail]" />
<input type="..." name="address[2][type]" />
<input type="..." name="address[2][comment]" />
</div>
I modified my script as below and in test5.php, I can view the data with this script.
<? Php
// print_r ($ _ POST);
echo $ _POST ['mail'] [2];
?>
Thanks
-------------test5.php-------------
<div id="address">
<div id="1">
<input type="text" name="mail[]" />
<input type="text" name="type[]" />
<input type="text" name="comment[]" />
</div>
</div>
I have the below form, and after the form the PHP requests a Curl which can take a while. Because of this they keep pressing the submit button thinking that nothing has happened. This causes multiple entries in the database. Could someone help me and let me know what to put in to stop this.
I tried the Javascript solution in the first answer but it stopped the PHP script that followed. Not what I wanted. Sorry
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="css2/style.css" rel='stylesheet' type='text/css' />
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="application/x-javascript"> addEventListener("load", function() { setTimeout(hideURLbar, 0); }, false); function hideURLbar(){ window.scrollTo(0,1); } </script>
<!--webfonts-->
<link href='//fonts.googleapis.com/css?family=Open+Sans:400,300,600,700,800' rel='stylesheet' type='text.css'/>
<!--//webfonts-->
<center><img class="displayed" src="images/logo.jpg" alt="Logo" style="width:128px;height:128px;"></center>
</head>
<body>
<div class="main">
<form action="" method="POST" enctype="multipart/form-data" id="contactform" >
<input type="hidden" name="action" value="submit">
<h1><span>Sign Up</span> <lable> The Brook on Sneydes</lable> </h1>
<div class="inset">
<p>
<center><label ><?php echo $text; ?></label></center>
<label for="first">First Name</label>
<input type="text" name="first" id="first" value="" placeholder="" required/>
</p>
<p>
<label for="last">Surname</label>
<input type="text" name="last" id="last" value="" placeholder="" required/>
</p>
<p>
<label for="mobile">Mobile Number</label>
<input type="text" name="mobile" id="mobile" value="" placeholder="" required/>
</p>
<p>
<label for="email">Email Address</label>
<input type="text" name="email" id="email" value="" placeholder="" required/>
</p>
</div>
<p class="p-container">
<input type="submit" name="submit" id="submit" value="Submit">
</p>
</form>
</div>
<!-----start-copyright---->
<div class="copy-right">
<p> © 2016 Spearhead Digital. All rights reserved.</p>
</div>
<!-----//end-copyright---->
</body>
</html>
<?php
if(isset($_POST['submit']) && !empty($_POST) ){
$first = $_POST['first'];
$last = $_POST['last'];
$mobile = $_POST['mobile'];
$email = $_POST['email'];
// Other Code
}
You can disable the submit button when submitting the form.
An example using jQuery:
<script type="text/javascript">
$(document).ready(function() {
$('#contactform').submit(function() {
$('input[type=submit]', this).prop("disabled", true);
});
});
</script>
So I doing simple edit/delete/new for mysql DB update.I am using ajax as I need it to in a single page.
So when I check New button, a new form shows up(from ajax call to php file). I get html form. I am trying to validate this.
But I am not able. Code seems right. My code here
trail.php
<?php include( 'connect.php'); ?>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
<script>
$(document).ready(function() {
$("#form1").validate({
debug: false,
rules: {
plid: "required",
},
messages: {
plid: "Please select a pack list id..",
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: "aa.php",
data: $('#form1').serialize(),
cache: false,
success: function(response) {
$('#result1').html(response);
}
});
}
});
});
</script>
</head>
<body>
<div id="result1"></div>Packing List</br>
<form id="form1" name="form1" action="" method="post">
<?php echo '<select name="plid" id="plid">'; echo '<option value="" selected="selected">--Select the Pack List Id--</option>'; $tempholder=a rray(); $sql="SELECT `pl_id`
FROM (
SELECT `pl_id`
FROM packlist
ORDER BY `pl_id` DESC
LIMIT 30
) AS t" ; $query=m ysql_query($sql) or die(mysql_error()); $nr=m ysql_num_rows($query); for ($i=0; $i<$nr; $i++){ $r=m ysql_fetch_array($query); if (!in_array($r[ 'pl_id'], $tempholder)){ $tempholder[$i]=$ r[ 'pl_id']; echo "<option>".$r[ "pl_id"]. "</option>"; } } echo '</select>'; ?>
<br/>
<input type="submit" name="new" id="new" value="New" />
<br/>
<input type="submit" name="delete" value="Delete" />
<br/>
<input type="submit" name="edit" id="edit" value="Edit" />
<br/>
</form>
</body>
And my ajax called php file
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.min.js"></script>
<script>
$(document).ready(function() {
$("#form2").validate({
debug: false,
rules: {
plidnew: "required",
},
messages: {
plidnew: "Please select a pack list id..",
}
});
});
</script>
</head>
<body>
<?php $a=isset($_POST[ 'plid']) && $_POST[ 'plid']; $b=isset($_POST[ 'new']) && $_POST[ 'new']; if($a&&$b) { ?>
<form name="form2" id="form2" method="post" action="">
<P>
<LABEL for="plidnew">PackList No
<INPUT type="text" id="plidnew">
</LABEL>
<BR>
<BR>
<LABEL for="itemidnew">Item Id
<INPUT type="text" id="itemidnew">
</LABEL>
<BR>
<BR>
<LABEL for="quannew">Quantity
<INPUT type="text" id="quannew">
</LABEL>
<BR>
<BR>
<LABEL for="potnew">Potency
<INPUT type="text" id="potnew">
</LABEL>
<BR>
<BR>
<LABEL for="sizenew">Size
<INPUT type="text" id="sizenew">
</LABEL>
<BR>
<BR>
<INPUT type="submit" id="newsubmit" name="newsubmit" value="Submit">
<INPUT type="reset">
</P>
</form>
<?php }
$c=isset($_POST[ 'plid']) && $_POST[ 'plid'];
$d=isset($_POST[ 'delete']) && $_POST[ 'delete'];
if($c&&$d) {
echo "delete!!";
}
$e=isset($_POST[ 'plid']) && $_POST[ 'plid'];
$f=isset($_POST[ 'edit']) && $_POST[ 'edit'];
if($e&&$f) {
?>
<form name="form3" id="form3" method="post" action="aa.php">
<P>
<LABEL for="plidedit">PackList No
<INPUT type="text" id="plidedit">
</LABEL>
<BR>
<BR>
<LABEL for="itemidedit">Item Id
<INPUT type="text" id="itemidedit">
</LABEL>
<BR>
<BR>
<LABEL for="quanedit">Quantity
<INPUT type="text" id="quanedit">
</LABEL>
<BR>
<BR>
<LABEL for="potedit">Potency
<INPUT type="text" id="potedit">
</LABEL>
<BR>
<BR>
<LABEL for="sizeedit">Size
<INPUT type="text" id="sizeedit">
</LABEL>
<BR>
<BR>
<INPUT type="submit" id="editsubmit" name="editsubmit" value="Submit">
<INPUT type="reset">
</P>
</form>
<?php } ?>
</body>
I had doubts about validating the form. I tried the validation codes in both page.
But no ajax effect as shown in firebug. Any help appreciated..Thanks a lot..
while using ajax with type "post", you should be careful in passing data
data and data1 are the parameter of the webmethod or service. Try this
var d1="asd";
$.ajax({
type: "POST",
url: "aa.php",
data: "{data:'"+d1+"',data1:'"+d2+"'}",
cache: false,
success: function(response) {
$('#result1').html(response);
}
});
In my htm page i want to use a button which submit my form by using function. I use validations on my fields and when i press submit button it displays error message but doesnot retain last values it refresh my form. I just want that the values that i entered will be exist there and just the field that has only error message will be disappear. all other fields remain there.
Here is my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<!--<meta http-equiv="refresh" content="text/html; charset=iso-8859-1" />-->
<!--
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
-->
<title>Phone Registration</title>
<link rel="stylesheet" type="text/css" href="file:///C|/xampp/htdocs/track/css/view.css" media="all"/>
<script type="text/javascript" src="file:///C|/xampp/htdocs/track/javascript/view.js"></script>
<script type="text/javascript" src="file:///C|/xampp/htdocs/track/javascript/external.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body id="main_body" >
<img id="top" src="file:///C|/xampp/htdocs/track/images/top.png" alt=""/>
<div id="form_container">
<h3>
Phone Registration
Officer Registration
Customer Registration
Task Entry
</h3>
<form name="order" id="form_532698" class="appnitro" method="post" action="" >
<div class="form_description">
<h2>Phone Registration</h2>
</div>
<ul >
<li>
<span>
<label class="description">IMEI # : </label>
<input name="imei" id="imeinum" class="element text medium" type="text" maxlength="15" value=""/>
</span>
</li>
<li>
<span>
<label class="description" >Phone Number </label>
<input name="phone" id="phnum" class="element text medium" type="text" maxlength="11" value="" onblur="validate(this)"/>
</span>
</li>
<li>
<span>
<label class="description" >From Date </label>
<input id="datepicker" name="fdate" class="element text medium" maxlength="10" value="" type="text"/>
</span>
</li>
<li>
<span>
<label class="description" for="element_4">Active </label>
<input name="r1" id="rad" class="element radio" type="radio" value="Yes" checked="checked" />
<label class="choice">Yes</label>
<input name="r1" id="rad" class="element radio" type="radio" value="No" />
<label class="choice">No</label>
</span>
</li>
<li>
<input type="button" name="save" value="Save" />
</li>
<!--
<li class="buttons">
<input type="hidden" name="form_id" value="532698" />
<input class="button_text" type="submit" name="save" value="Save" id="" />
<input class="button_text" type="reset" name="cancel" value="Cancel" />
<input class="button_text" type="submit" name="search" value="Search" id="" />
<input class="button_text" type="submit" name="up" value="Update" id="" />
<input class="button_text" type="submit" name="del" value="Delete" id="" />
</li>
-->
</ul>
</form>
</div>
<img id="bottom" src="file:///C|/xampp/htdocs/track/images/bottom.png" alt=""/>
<script type="text/javascript" language="JavaScript">
//submit form
document.order.submit();
</script>
</body>
</html>
Kindly guide me how can i do this?? I'll be thankful to you
You can use this code to prevent form from submiting to server if validation fails:
$("form").on("submit", function(event){
if(!isValidForm($(this)){
event.preventDefault();
}
});
supposingly isValidForm() method takes form selector and returns true if form is valid and false if it's not.
use e.preventDefault(); or return false;
Check the validation is success or not in $(function()) if not then return false in that.. else return true...
<script>
$(function() {
$( "#datepicker" ).datepicker();
if(!validation) {
return false;
}
return true;
});
</script>
There are 2 major ways of doing this: PHP(server-side) and javascript(client-side).
The PHP solution isn't that clean, you need to refresh the page, check the values there and set the correct value in every input (removing the ones you want to delete)
The javascript/jQuery solution is cleaner: instead of a <input type='submit' /> use a button that calls a javascript function, checks every input (if you need server information to check them you can use Ajax) and displays the errors, setting only the ones that were wrong to blank.
Both ways are ok, but the javascript method is much easier to control/update, and it's more user-friendly since it doesn't refresh the page.
In a facebook iframe page (not tab), I'd like to post data to an external API using cURL, but I would prefer if my form page didn't reload.
I'd like to have some jquery ajax happening ("submitting data" message on submission of the form and a success message on success of the curl_exec). I was thinking of creating a hidden iframe with a duplicate form and update values in that form on change events, but i don't know quite how I'd implement that exchange between PHP and jquery.
Is there a better way? Here's the code I'm working on:
UPDATED CODE TO RETURN FALSE --
Does not submit form data.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body class="fb_canvas-resizable <?php print $body_classes; ?>">
<?php echo $message; ?>
<div class="container">
<div class="header"></div>
<div class="wrapper">
<div class="content">
<div class="left">
<h1>Sign Up to Sign Off</h1>
<form name="signoff" action="curlsub.php" method="post">
<input id="api" type="hidden" name="API_KEY" value="key">
<div class="innerleft">
<input id="fname" type="text" name="fname" class="inputs" tabindex="1" /></br />
<label for="fname">First</label></br /></br /></br />
<input type="text" name="email" class="inputs" tabindex="3" /></br />
<label id="email" for="email">Email</label></br /></br /></br />
<label for="gender">Gender</label></br /></br />
<label for="gender">Age</label></br /></br /></br />
<label for="gender">Income</label></br /></br /></br />
</div>
<div class="innerright">
<input id="lname" type="text" name="lname" class="inputs" tabindex="2" /></br />
<label for="lname">Last</label></br /></br /></br />
<input id="password" type="password" name="password" class="inputs" tabindex="4" /></br />
<label for="email">Password</label></br /></br /></br />
<input type="radio" name="sex" value="male" selected="selected" tabindex="5" /> Male
<input type="radio" name="sex" value="female" tabindex="6" /> Female</br /></br />
<select name="age" tabindex="7" >
<option value=""></option>
<option value="baby">Baby</option>
<option value="teen">Teen</option>
<option value="young">Young</option>
<option value="old">Old</option>
</select><br /><br />
<select name="income" tabindex="8">
<option value=""></option>
<option value="none">None</option>
<option value="some">Some</option>
<option value="okay">Okay</option>
<option value="tons">Tons</option>
</select><br /><br />
<input id="zip" type="text" name="c5" class="zip" tabindex="9" /></br />
<label for="c5">Zip Code</label></br /></br />
<label for="mformat">Newsletter</label></br /></br />
<input type="checkbox" name="mformat" value="html" selected="selected" tabindex="10" /> HTML (iPhone, iPad, Droid)<br /><br />
<input type="checkbox" name="mformat" value="text" tabindex="11" /> TEXT (Best for Blackberry)
</div>
<div class="button"><input type="image" src="button.jpg" name="submit" value="yes"></div>
</form>
</div>
<div class="right">
<img src="logo.jpg" />
<p>Updating you on today and prepping you for tomorrow.</p>
www.url.com
</div>
<div class="clear">
</div>
<div class="logged clear">
<p>Logged in as Some Guy (not you?)</p>
</div>
</div></div>
<div class="footer"></div>
</div>
<script>
$(document).ready(function() {
//$('div.wrapper').fadeOut(0);
window.fbAsyncInit = function() {
FB.init({appId: 'app', status: true, cookie: true});
FB.Canvas.setSize();
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
});
$('#signoff').submit( function() {
var fname = $("input#fname").val();
var lname = $("input#fname").val();
var email = $("input#email").val();
var password = $("input#password").val();
var dataString = 'fname='+ fname + '&lame=' + lname + '&email=' + email + '&password=' + password;
// alert(dataString);
// return false;
$.ajax({
type: "POST",
url: "curlsub.php",
data: dataString,
success: function() {
//do some stuff
}
});
return false;
});
</script>
</body>
</html>
Currently this will successfully send the data to the external PHP API, but the iframe (or my whole file) reloads on submission (and displays "success" message).
What you want to do is issue an AJAX Post request on the submit event of your form. The success callback of that AJAX Post request should update your UI to alert the user that their post was sucessful.
$('#signoff').submit(
//Ajax post request here
//http://api.jquery.com/jQuery.post/
return false; //this stops your page from refreshing
);
Have you looked at http://api.jquery.com/jQuery.ajax/ or http://api.jquery.com/jQuery.post/
The following code should help you get started.
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
Where
url is a string containing the URL to which the request is sent.
data is a map or string that is sent to the server with the request.
success is a callback function that is executed if the request succeeds. It should take three arguments: (data, textStatus, XMLHttpRequest)
dataType is the type of data expected from the server.