how can I get the result from second code? - php

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.

Related

How to send data with ajax when pressing enter [duplicate]

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) {
}
});
}

Checking user availability in registration form. Already an AJAX request is present in the current html file. How can i add another one?

Hey guys i've done a registration where the user registers himself and after submitting the data gets stored automatically. Already in the present html file, i've given an ajax request and the operation for register.php. Now i would like to implement a criteria of "Checking the user availability". Here is where i'm confused. If i give this ajax request, then how will i be able to do the register.php? Please help me out. Thanks.
<body>
<div class="app-block">
<div class="cube"><img src="images/cube.png" class="img-responsive" alt="" /></div>
<form method="post">
<div id="reg-data"></div>
<input type="text" name="username" required="required" placeholder="Enter your name" id="username" />
<input type="password" name="password" required="required" placeholder="Enter your password" id="password" />
<input type="text" name="location" placeholder="Please give your location" id="location" />
<input type="text" name="company" placeholder="Where do you work?" id="company" />
<input type="text" name="designation" placeholder="Provide your designation" id="designation" />
<label for="gender">Gender </label>
<input type="radio" name="gender" required="required" id="gender" value="Male" />Male
<input type="radio" name="gender" required="required" id="gender" value="Female"/>Female
<br/><br/>
<label for="qualification">Qualification</label>
<select name="qualification" value="Qualification" id="qualification">
<option value="SSLC">SSLC</option>
<option value="HSC">HSC</option>
<option value="UG">UG</option>
<option value="PG">PG</option>
</select><br/><br/>
<label for="hobbies">Hobbies </label>
<input type="checkbox" name="hobbies" id="hobbies" value="Cricket" />Cricket
<input type="checkbox" name="hobbies" id="hobbies" value="Music" />Music
<input type="checkbox" name="hobbies" id="hobbies" value="Swimming" />Swimming
<div class="submit"><input type="submit" name="register" value="Register" id="reg" /></div>
<div class="clear"></div>
</form>
<p class="sign">Already Registered? Login</p>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#reg').click(function(e) {
e.preventDefault();
var username = $("#username").val();
if( username == '') {
alert('Enter the username');
header('location: register.html');
} else {
var password = $("#password").val();
if( password == '') {
alert('Enter the password');
header('location: register.html');
} else {
var gender = $("#gender").val();
var qualification = $("#qualification").val();
var hobbies = $("#hobbies").val();
var location = $("#location").val();
var company = $("#company").val();
var designation = $("#designation").val();
}}
$.ajax({
url: "register.php",
type: "POST",
data: "username="+username+"& password="+password+"& gender="+gender+"& qualification="+qualification+"& hobbies="+hobbies+"& location="+location+"& company="+company+"& designation="+designation,
success: function(data, status, xhr) {
$('#reg-data').html(data);
$('#username').val('');
$('#password').val('');
$('#gender').val('');
$('#qualification').val('');
$('#hobbies').val('');
$('#location').val('');
$('#company').val('');
$('#designation').val('');
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message); }
});
});
});
</script>
</body>
Now i've another ajax request, but confused of where to put that.
<script src="jquery-1.8.0.min.js"></script>
<script>
$(document).ready(function(){
$('#username').keyup(check_username);
});
function check_username(){
var username = $('#username').val();
$.ajax({
type: 'POST',
url: 'check_username.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 0){
alert('Username available')
}
else {
alert('Username not available')
}
}
});
}
</script>
You can keep it one after another
there is no harm in concecutive Ajax request in one file
<script>
$(document).ready(function() {
// for user registration
$('#reg').click(function(e) {
e.preventDefault();
var username = $("#username").val();
if( username == '') {
alert('Enter the username');
header('location: register.html');
} else {
var password = $("#password").val();
if( password == '') {
alert('Enter the password');
header('location: register.html');
} else {
var gender = $("#gender").val();
var qualification = $("#qualification").val();
var hobbies = $("#hobbies").val();
var location = $("#location").val();
var company = $("#company").val();
var designation = $("#designation").val();
}}
$.ajax({
url: "register.php",
type: "POST",
data: "username="+username+"& password="+password+"& gender="+gender+"& qualification="+qualification+"& hobbies="+hobbies+"& location="+location+"& company="+company+"& designation="+designation,
success: function(data, status, xhr) {
$('#reg-data').html(data);
$('#username').val('');
$('#password').val('');
$('#gender').val('');
$('#qualification').val('');
$('#hobbies').val('');
$('#location').val('');
$('#company').val('');
$('#designation').val('');
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
alert(err.Message); }
});
});
// check username
$('#username').keyup(function(){
var username = $(this).val();
$.ajax({
type: 'POST',
url: 'check_username.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 0){
alert('Username available')
}
else {
alert('Username not available')
}
}
});
});
});
</script>
OR
Create a file registration.js and paste the whole code in it without script tag and include it in your file
<script src='path/to/registration.js'></script>
try with this...
function check_username(){
$.ajax({
type: 'POST',
url: 'check_username.php',
data: 'username='+ $('#username').val(),
cache: false,
success: function(response){
return response;
}
});
}
and in validation
var successStatus = check_username();
if(successStatus != 1){
alert('username already Exist');
return false;
}

hide div after inserting data in database

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();
});
});

Get the textbox Text using ajax on button click

I want a code for get textbox value when submit button is clicked. It must be Ajax.Here is the code I tried so far.But I culdent get to work....
<form action="" method="post">
<p>Route No :
<input type="text" name="route_no" required="required" />
<input type="submit" value="Search" name="search" />
</form>
Ajax Code
<script type="text/javascript">
$(document).ready(function() {
$("#sub").click(function() {
var textboxvalue = $('name or id of textfield').val();
$.ajax({
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result) {
$("div").html(result);
}
});
});
});​
</script>
PHP code
$txt = null;
if((isset($_POST)) && (isset($_POST['txt1'])))
{
echo $txt = $_POST['txt1'];
}
HTML:
<label for="route_no">Route No:</label><input type="text" id="route_no" name="route_no" required="required" />
<input type="button" value="Search" id="search" />
<div id="result"></div>
JavaScript:
$(document).ready(function()
{
$("#search").click(function()
{
var textboxvalue = $('input[name="route_no"]').val();
$.ajax(
{
type: "POST",
url: 'ajaxPage.php',
data: {txt1: textboxvalue},
success: function(result)
{
$("#result").html(result);
}
});
});
});​
ajaxPage.php:
if(isset($_POST) && isset($_POST['txt1']))
{
echo $_POST['txt1'];
}
You have problem here
$("#sub").click(function() {
you are using id ="sub" for submit button but you are not assigning id to that button so give id to submit button as id="sub".
To get the value of the textbox you can use:
$('#elementid').val()

Passing form array data through jQuery AJAX

I have a form that allows you to add multiple listings at one time.
I also have to pass through an md5check.
I.E.)
<select name="master_id"></select>
<select name="id2[]"></select>
<select name="id3[]"></select>
<input name="text[]"></input>
<input name="text2[]"></text>
<input name="text3[]"></text>
<input name="check[]" type="checkbox"></input>
<select name="id2[]"></select>
<select name="id3[]"></select>
<input name="text[]"></input>
<input name="text2[]"></text>
<input name="text3[]"></text>
<input name="check[]" type="checkbox"></input>
<select name="id2[]"></select>
<select name="id3[]"></select>
<input name="text[]"></input>
<input name="text2[]"></text>
<input name="text3[]"></text>
<input name="check[]" type="checkbox"></input>
jQuery.ajax({
type: "POST",
url: ipb.vars['base_url'] + "app=main&module=ajax&section=upload&do=upload",
data: {
'md5check': ipb.vars['secure_hash'],
}
}).done(function() {
alert( "Data Saved:");
});
I want to pass in the master ID and the arrays through AJAX so that they then can be $_REQUEST'ed in PHP. The 'md5check' must be there.
data can also take a string so, you can used
jQuery.ajax({
type: "POST",
url: ipb.vars['base_url'] + "app=main&module=ajax&section=upload&do=upload",
data: $('input[name="username[]"],input[name="password[]"],input[name="rawtext[]"]').serialize()
+ '&md5check='+ipb.vars['secure_hash'],
}).done(function() {
alert( "Data Saved:");
});
HTML Form:
<form action="" method="POST" id="myform">
<input name="username[]">
<input name="password[]">
<input name="rawtext[]">
<input name="username[]">
<input name="password[]">
<input name="rawtext[]">
<input name="username[]">
<input name="password[]">
<input name="rawtext[]">
<input name="submit" type="submit" value="submit">
</form>
jQuery:
$('#myform').submit(function(event) {
event.preventDefault();
//comment this line out
alert($(this).serialize());
$.post(ipb.vars['base_url'] + "app=main&module=ajax&section=upload&do=upload&", {
$(this).serialize() })
.done(function(data) {
alert("Data Loaded: " + data);
});
return false;
});
You can use the following.
$('#myform').submit(function(e) {
e.preventDefault();
e.stopPropagation();
var formData = $(this).serializeObject();
var postData = $.extend({}, formData, {
app: main,
module: ajax,
section: upload,
do: upload
});
$.post(ipb.vars['base_url'], postData,
function(data) {
alert(data);
}
);
});
$.fn.serializeObject = function() {
var objectData = {};
var serializeArr = this.serializeArray();
$.each(serializeArr, function() {
if(objectData[this.name] !== undefined) {
if(!objectData[this.name].push) {
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push($.trim(this.value) || '');
} else {
objectData[this.name] = $.trim(this.value) || '';
}
});
return objectData;
};

Categories