This question already has answers here:
jQuery Ajax POST example with PHP
(17 answers)
Closed 7 years ago.
form.php
<form action="#" method="POST" enctype="multipart/form-data" style="textalign: center;">
<label class="label" for="Fromdate">From Date</label>
<input type="text" id="datepicker" class="textBox" name="fromDate" />
<label class="label" for="Todate">To Date</label>
<input type="text" id="datepicker1" class="textBox" name="toDate" />
<input type="submit" name="searchby" id="searchby" value="Search" class="buttonLarge" />
<input type="submit" name="excel" value="Export To Excel" class="buttonLarge" />
</form>
datediff.php
<?php
if(($_POST['searchby'] == 'Search')){
?>
<script type="text/javascript">
var fromDate = $("#datepicker").val();
var toDate = $("#datepicker1").val();
$.ajax({
type: "POST",
url: "datediff.php",
data: { fromDate,toDate },
cache: false,
success: function (html) {
}
});
</script>
<?php
}
?>
Wrong json { fromDate,toDate }.
And yes it will submit if we press enter. For submitting it through ajax we have to prevent default functionality through event.preventDefault().
$(document).keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
search();
}
});
$('#searchby').click(function(e){
e.preventDefault();
search();
});
function search()
{
$.ajax({
type: "POST",
url: "datediff.php",
data: { 'fromDate':$('#datepicker').val(), 'toDate':$('#datepicker1').val() },
cache: false,
success: function (html) {
}
});
}
Related
I am not able to get the response to ajax success call back function. The response form the server is being directly printed on the browser
<body>
<script>
$(document).ready(function() {
$.ajax({
url: $("#form").attr("action"),
type: "POST",
data: $("#form").serialize(),
success: function(data) {
alert(data);
}
});
});
</script>
<form action="a.php" method="post" id="form">
<input type="text" name="name" id="name" placeholder="name" />
<input type="submit" value="submit" />
</form>
</body>
my php code
<?php
echo 'hii';
?>
Can you Replace AJAX script below mentioned.
<form method="post" id="form">
<input type="text" name="name" id="name" placeholder="name" />
<input type="submit" value="submit" />
</form>
$("#form").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: 'a.php',
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
});
I have modified my question. How can I get the result from second form? because I have create two form with similar code, however I can only get the result from the first form and when I press the second one, it still get the result from first form. Can someone help me out?
Code
<div>
<form id="fupForm" name="form1" method="post">
<div class="form-group">
<input type="hidden" class="form-control" id="gp_name" name="gp_name"
value="<?php echo $gp_name;?>">
<input type="hidden" class="form-control" id="date" name="date" value="<?
php
echo $deday;?>">
<input type="hidden" class="form-control" id="type" name="type"
value="Hotel">
</div>
<input type="button" name="save" class="btn btn-primary"
value="Add Hotel" id="butsave">
</form></div>
<div>
<form id="fupForm2" name="form2" method="post">
<div class="form-group">
<input type="hidden" class="form-control" id="gp_name" name="gp_name"
value="<?php echo $gp_name;?>">
<input type="hidden" class="form-control" id="date" name="date" value="<?
php
echo $deday;?>">
<input type="hidden" class="form-control" id="type" name="type"
value="Coach">
</div>
<input type="button" name="save" class="btn btn-primary"
value="Add Coach" id="butsave2">
</form></div>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
$("#butsave").attr("disabled", "disabled");
var gp_name = $('#gp_name').val();
var date = $('#date').val();
var type = $('#type').val();
if(gp_name!="" && date!="" && type!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
gp_name: gp_name,
date: date,
type: type
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
<script>
$(document).ready(function() {
$('#butsave2').on('click', function() {
$("#butsave2").attr("disabled", "disabled");
var gp_name = $('#gp_name').val();
var date = $('#date').val();
var type = $('#type').val();
if(gp_name!="" && date!="" && type!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
gp_name: gp_name,
date: date,
type: type
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave2").removeAttr("disabled");
$('#fupForm2').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
I have try to find on the Google, but can't find the solution for my case.
Add form id before the input element.
Remember ids are always unique and can not be duplicate. So here I change id to class. Please check below code.
<div>
<form id="fupForm" name="form1" method="post">
<div class="form-group">
<input type="hidden" class="form-control gp_name" id="" name="gp_name"
value="<?php echo $gp_name;?>">
<input type="hidden" class="form-control date" id="" name="date" value="<?
php
echo $deday;?>">
<input type="hidden" class="form-control type" id="" name="type"
value="Hotel">
</div>
<input type="button" name="save" class="btn btn-primary"
value="Add Hotel" id="butsave">
</form></div>
<div>
<form id="fupForm2" name="form2" method="post">
<div class="form-group">
<input type="hidden" class="form-control gp_name" id="" name="gp_name"
value="<?php echo $gp_name;?>">
<input type="hidden" class="form-control date" id="" name="date" value="<?
php
echo $deday;?>">
<input type="hidden" class="form-control type" id="" name="type"
value="Coach">
</div>
<input type="button" name="save" class="btn btn-primary"
value="Add Coach" id="butsave2">
</form></div>
<script>
$(document).ready(function() {
$('#butsave').on('click', function() {
$("#butsave").attr("disabled", "disabled");
var gp_name = $('#fupForm .gp_name').val();
var date = $('#fupForm .date').val();
var type = $('#fupForm .type').val();
if(gp_name!="" && date!="" && type!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
gp_name: gp_name,
date: date,
type: type
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave").removeAttr("disabled");
$('#fupForm').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
<script>
$(document).ready(function() {
$('#butsave2').on('click', function() {
$("#butsave2").attr("disabled", "disabled");
var gp_name = $('#fupForm2 .gp_name').val();
var date = $('#fupForm2 .date').val();
var type = $('#fupForm2 .type').val();
if(gp_name!="" && date!="" && type!=""){
$.ajax({
url: "save.php",
type: "POST",
data: {
gp_name: gp_name,
date: date,
type: type
},
cache: false,
success: function(dataResult){
var dataResult = JSON.parse(dataResult);
if(dataResult.statusCode==200){
$("#butsave2").removeAttr("disabled");
$('#fupForm2').find('input:text').val('');
$("#success").show();
$('#success').html('Data added successfully !');
}
else if(dataResult.statusCode==201){
alert("Error occured !");
}
}
});
}
else{
alert('Please fill all the field !');
}
});
});
</script>
An id must be unique in a document. Use a validator.
You get the same data each time, because you are searching using an id selector and error recovery means that you will always get the first one.
Don't use IDs
Do use selectors relative to the form you are dealing with
For example:
$("form").on("submit", function(event) {
event.preventDefault();
const $form = $(this);
const $input = $form.find("[name=type]");
console.log($input.val());
});
form {
padding: 1em
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input type=hidden name=type value=foo>
<button>Submit</button>
</form>
<form>
<input type=hidden name=type value=bar>
<button>Submit</button>
</form>
The function $( document ).ready( function() {} ) and $( function() {} ) are equal. This will overwrite the previous variant. If you merge the code, it should work.
I Have a form in PHP. when I am clicking the submit button I want to take two actions at the same time. how do I do that?
<script>
function myfunction(){
$.ajax({
type: 'post',
url: 'merchants.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
}
</script>
<div class="stdFormHeader"> New Merchant Registration</div>
<form action="" method="POST">
<label class="stdFormLabel">Merchant name : </label><input class="stdFormInput" type="text" name="merchantName" required><br>
<!-- <label class="stdFormLabel">Business Type : </label><select class="stdFormSelect" name="shopMarket" required>-->
<!-- <option value="shop">Shop</option>-->
<!-- <option value="market">Market Place</option>-->
<!-- </select><br>-->
<label class="stdFormLabel">Contact Person : </label><input class="stdFormInput" type="text" name="contactPerson" required><br>
<label class="stdFormLabel">Contact Number : </label><input class="stdFormInput" type="text" name="contactNumber" required><br>
<label class="stdFormLabel">Address : </label><textarea class="stdFormInputBox" name="address"></textarea><br>
<input class="stdFormButton" type="submit" name="submit" onclick="myfunction()" value="Apply">
</form>
Just do a submit again:
function myfunction(){
$.ajax({
type: 'post',
url: 'merchants.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
$.ajax({
type: 'post',
url: 'OtherFunction.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted again');
}
});
}
Hi would you like to help me. im a php newbie. I want to insert employment information in my database and hide da div where the form placed.
HTML:
<div class="toggler">
<div id="effect" class="ui-widget-content ui-corner-all">
<form name="empform" method="post" action="profile.php" autofocus>
<input name="employ" type="text" id="employ" pattern="[A-Za-z ]{3,20}"
placeholder="Who is your employer?">
<input name="position" type="text" id="position" pattern="[A-Za-z ]{3,20}"
placeholder="What is your job description?">
<input name="empadd" type="text" id="empadd" pattern="[A-Za-z0-9##$% ]{5,30}"
placeholder="Where is your work address?">
<input name="empcont" type="text" id="empcont" pattern="[0-9]{11}" title="11-digit number"
placeholder="Contact number">
<input name="btncancel" type="button" class="btncancel" value="Cancel"
style="width:60px; border-radius:3px; float:right">
<input name="btndone" type="submit" class="btndone" value="Done" style="width:60px; border-radius:3px; float:right">
</form>
</div>
</div>
PHP:
if (isset($_POST['btndone'])) {
$employ = $_POST['employ'];
$position = $_POST['position'];
$empadd = $_POST['empadd'];
$empcont = $_POST['empcont'];
$empdate = $_POST['empdate'];
$empID = $alumniID;
$obj - > addEmployment($employ, $position, $empadd, $empcont, $empdate, $empID);
}
JS:
<script>
$(function () {
function runEffect() {
var selectedEffect = "highlight";
$(".toggler").show(selectedEffect);
};
function runDisplay() {
var selectedDisplay = "highlight";
$("#empdisplay").show(selectedDisplay);
};
$(".btncancel").click(function () {
$(".toggler").hide();
return false;
});
$(".btndone").click(function () {
runDisplay();
$(".toggler").hide();
return false;
});
}
</script>
Hi this is what I'll do
var request = $.ajax({
url: "profile.php",
type: "POST",
data: $('#form').serialize()
});
request.done(function(msg) {
$('#form').hide();
});
request.fail(function(jqXHR, textStatus) {
alert( "Form failed" );
});
If you have some doubts with Jquery's Ajax visit this link
If you don't understand what jqXHR is, I suggest you visit this link http://www.jquery4u.com/javascript/jqxhr-object/
Execute on click
$('#form').submit(function(){
var request = $.ajax({
url: "profile.php",
type: "POST",
data: $('#form').serialize()
});
request.done(function(msg) {
$('#form').hide();
});
request.fail(function(jqXHR, textStatus) {
alert( "Form failed" );
});
});
Try This
HTML
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<div class="toggler">
<div id="effect" class="ui-widget-content ui-corner-all">
<form id="empform" name="empform" method="post" action="profile.php" autofocus>
<input name="employ" type="text" id="employ" pattern="[A-Za-z ]{3,20}"
placeholder="Who is your employer?">
<input name="position" type="text" id="position" pattern="[A-Za-z ]{3,20}"
placeholder="What is your job description?">
<input name="empadd" type="text" id="empadd" pattern="[A-Za-z0-9##$% ]{5,30}"
placeholder="Where is your work address?">
<input name="empcont" type="text" id="empcont" pattern="[0-9]{11}" title="11-digit number"
placeholder="Contact number">
<input name="btncancel" type="button" class="btncancel" value="Cancel"
style="width:60px; border-radius:3px; float:right">
<input id="submit"name="btndone" type="submit" class="btndone" value="Done" style="width:60px; border-radius:3px; float:right">
</form>
</div>
</div>
<script>
$(document).ready(function() {
//$("#form").prev
$('#submit').click(function(event) {
//alert (dataString);return false;
event.preventDefault();
$.ajax({
type: "POST",
url: 'profile.php',
dataType:"html",
data: $("#empform").serialize(),
success: function(msg) {
alert("Form Submitted: " + msg);
//alert($('#form').serialize());
$('div.toggler').hide();
}
});
});
});
</script>
</html>
PHP
profile.php
<?php
if (isset($_POST)) {
$employ = $_POST['employ'];
$position = $_POST['position'];
$empadd = $_POST['empadd'];
$empcont = $_POST['empcont'];
$empdate = $_POST['empdate'];
$empID = $alumniID;
$obj - > addEmployment($employ, $position, $empadd, $empcont, $empdate, $empID);
}
?>
Iam not sure about your fields
echo $empdate = $_POST['empdate'];
$empID = $alumniID;
they are not in form but works!...
You should do an ajax call to save your data and then hide the div, someting like this :
$('form[name="empform"]').submit(function(e) {
e.preventDefault();
$.post($(this).attr('action'), $(this).serialize(), function(data) {
$('div.toggler').hide();
});
});
Please I am trying to simultaneously submit and validate my form to my database through the use of Ajax, but it is not working for me.
Here is my jquery
$(document).ready(function(){
$(".button").click(function(){
$("#myform").validate();
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: { firstname: $("#firstname").val()},
success: function(){
$('#message').html(data);
}
});
return false;
});
});
The problem is when I submit the form,the Ajax form submit to itself.
Please What is the right way to use the jquery validate and $.ajax together?
Pass data as a parameter in your success function:
success: function(data){
Your success function won't do anything because you haven't defined data
Try this (working for me as expected):
HTML Form:
<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/css/screen.css" />
<script src="http://jquery.bassistance.de/validate/lib/jquery.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script>
// JQuery Script to submit Form
$(document).ready(function () {
$("#commentForm").validate({
submitHandler : function () {
// your function if, validate is success
$.ajax({
type : "POST",
url : "process.php",
data : $('#commentForm').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
});
});
</script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required />
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required />
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url" />
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</fieldset>
</form>
<div id="message"></div>
PHP Code:
<?php
echo $_POST['email'];
?>
You forget to pass the response
$(document).ready(function() {
$(".button").click(function() {
//check the validation like this
if ($("#myform").valid()) {
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: {
firstname: $("#firstname").val()
},
//you forget to passs the response
success: function(response) {
$('#message').html(response);
}
});
return false;
}
});
});
First of all, why would you submit form if validation is not passed?
Try this, if validate really validates:
$(function(){
$(".button").click(function(){
var myform = $("#myform");
if (myform.validate()) {
$.post("process.php", myform.serialize(), function(data){
$('#message').html(data);
});
}
return false;
});
});