Loading data from form into MySQL with PHP and AJAX - php

I have a standard HTML form, and I'd like to store the data from that form into a MySQL database. I had everything working correctly, but now am wanting to implement AJAX to prevent the page from refreshing, and all of sudden am running into trouble.
Problem: the "success" alert is not being generated, and the data is not being saved into the database.
I have very, very little exposure into Jquery/AJAX, and am learning on-the-go, so please bear with me if I made an elementary mistake.
*UPDATE 1***
This is my new AJAX code. The data from the form is now getting saved into the database, but still no success alerts. In fact, NO pop-up appears.
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('form').bind('submit', function(){
$.ajax({
type: 'post',
url: "InsertNewMentor.php",
data: $("form").serialize(),
success: function() {
alert("Success!");
}
});
return false;
});
});
</script>
This is the form (includes AJAX code at the end). (update: no longer using this code, see above)
<form>
<table cellpadding="10">
<tr>
<td><b>Chapter:</b></td>
<td><input type="text" name="chapter"></td>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" name="first"></td>
<td>Last Name:</td>
<td><input type="text" name="last"></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</td>
<td>Ethnicity:</td>
<td>
<form action="">
<select name="ethnicity">
<option value="white">White/Caucasian</option>
<option value="hispanic">Hispanic</option>
<option value="asian">Asian/Pacific Islander</option>
<option value="native_american">Native American Indian</option>
<option value="other">Other</option>
</form>
</td>
</tr>
<tr>
<td>Year in School</td>
<td>
<form action="">
<select name="year_in_school">
<option value="freshman">Freshman</option>
<option value="sophomore">Sophomore</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
</select>
</form>
</td>
<td>Phone Number:</td>
<td><input type="text" name="phone"></td>
</tr>
<tr>
<td>Email Address:</td>
<td><input type="text" name="email"></td>
<td>Street Address:</td>
<td>
<input type="text" name="address">
</td>
</tr>
<tr>
<td>Apt/Suite:</td>
<td>
<input type="text" name="suite_num">
</td>
<td>City:</td>
<td>
<input type="text" name="city">
</td>
</tr>
<tr>
<td>State:</td>
<td>
<select name="state">
<option value="Alabama">Alabama</option>
<option value="Alaska">Alaska</option>
<option value="Arizona">Arizona</option>
<option value="Arkansas">Arkansas</option>
<option value="California">California</option>
<option value="Colorado">Colorado</option>
<option value="Connecticut">Connecticut</option>
<option value="Delaware">Delaware</option>
<option value="Florida">Florida</option>
<option value="Georgia">Georgia</option>
<option value="Hawaii">Hawaii</option>
<option value="Idaho">Idaho</option>
<option value="Illinois">Illinois</option>
<option value="Indiana">Indiana</option>
<option value="Iowa">Iowa</option>
<option value="Kansas">Kansas</option>
<option value="Kentucky">Kentucky</option>
<option value="Louisiana">Louisiana</option>
<option value="Maine">Maine</option>
<option value="Maryland">Maryland</option>
<option value="Massachusetts">Massachusetts</option>
<option value="Michigan">Michigan</option>
<option value="Minnesota">Minnesota</option>
<option value="Mississippi">Mississippi</option>
<option value="Missouri">Missouri</option>
<option value="Montana">Montana</option>
<option value="Nebraska">Nebraska</option>
<option value="Nevada">Nevada</option>
<option value="New Hampshire">New Hampshire</option>
<option value="New Jersey">New Jersey</option>
<option value="New Mexico">New Mexico</option>
<option value="New York">New York</option>
<option value="North Carolina">North Carolina</option>
<option value="North Dakota">North Dakota</option>
<option value="Ohio">Ohio</option>
<option value="Oklahoma">Oklahoma</option>
<option value="Oregon">Oregon</option>
<option value="Pennsylvania">Pennsylvania</option>
<option value="Rhode Island">Rhode Island</option>
<option value="South Carolina">South Carolina</option>
<option value="South Dakota">South Dakota</option>
<option value="Tennessee">Tennessee</option>
<option value="Texas">Texas</option>
<option value="Utah">Utah</option>
<option value="Vermont">Vermont</option>
<option value="Virginia">Virginia</option>
<option value="Washington">Washington</option>
<option value="West Virginia">West Virginia</option>
<option value="Wisconsin">Wisconsin</option>
<option value="Wyoming">Wyoming</option>
</select>
</td>
<td>Zip Code:</td>
<td>
<input type="text" name="zip_code">
</td>
</tr>
<tr>
<td>Cumulutative GPA:</td>
<td><input type="text" name="gpa"></td>
<td>Major/Area of Study:</td>
<td><input type="text" name="major"></td>
</tr>
<tr>
<td>Twitter handle:</td>
<td>
<input type="text" name="twitter_handle">
</td>
</tr>
<tr>
<td colspan="2">
<p>Please describe any relevant teaching experience:</p>
<textarea rows="6" cols="45" name="teaching_experience">
</textarea>
</td>
<td colspan="2">
<p>Why do you want to join Moneythink?</p>
<textarea rows="6" cols="43" name="why_moneythink">
</textarea>
</td>
</tr>
</table>
<table>
<tr>
<td><input type="submit" value="Apply"></td>
<td><input type="reset" value="Clear"></td>
</tr>
</table>
</form>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('form').bind('submit', function(){
$.ajax({
type: 'post',
url: "/InsertNewMentor.php",
data: $("form").serialize(),
success: function() {
alert("form was submitted");
}
});
return false;
});
});
</script>
And this is InsertNewMentor.hp
<?php
$username="";
$password="";
$database="";
$first = $_POST['first'];
$last = $_POST['last'];
$email = $_POST['email'];
$gpa = $_POST['gpa'];
$year = $_POST['year_in_school'];
$address = $_POST['address'];
$phone = $_POST['phone'];
$gender = $_POST['gender'];
$ethnicity = $_POST['ethnicity'];
$year_in_school = $_POST['year_in_school'];
$suite_number = $_POST['suite_num'];
$city = $_POST['city'];
$state = $_POST['state'];
$zip_code = $_POST['zip_code'];
$major = $_POST['major'];
$twitter_handle = $_POST['twitter_handle'];
$why_moneythink = $_POST['why_moneythink'];
$teaching_experience = $_POST['teaching_experience'];
$date = date("m/d/Y");
mysql_connect(localhost,$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query = "INSERT INTO students VALUES ('','$address','$phone','$first','$last','$gender', '$ethnicity', '$year_in_school', '$email', '$suite_number','$city','$state','$zip_code','$major','$gpa','$twitter_handle','$why_moneythink','$teaching_experience','pending','$date')";
mysql_query($query);
mysql_close();
?>

First of all , the serialize() function returns a text string ,and not an array of values - for further information read jQuery documentaion.
Now for the ajax submittion -
$(function() {
$('form').bind('submit', function(){
$.ajax({
type: 'post',
url: "/InsertNewMentor.php",
**data: {dataString: $("form").serialize()} ,**
success: function() {
alert("form was submitted");
}
});
return false;
});
You have got to send a JSON formatted data , as explanied above ( notice the change in the data field)
In the PHP code , when posting , you only post the field you send through ajax - i.e - dataString.
Furtheremore , in the success function you might use :
success: function(result) {
alert(result);
}
});
so you could debug any errors , if exist.
Good luck.

<form id="formPost" method="POST">
<table cellpadding="10">
<tr>
<td><b>Chapter:</b></td>
<td><input type="text" name="chapter"></td>
</tr>
<tr>
<td>First Name:</td>
<td><input type="text" name="first"></td>
<td>Last Name:</td>
<td><input type="text" name="last"></td>
</tr>
<tr>
<td>Gender:</td>
<td>
<select name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select>
</td>
<td>Ethnicity:</td>
<td>
<select name="ethnicity">
<option value="white">White/Caucasian</option>
<option value="hispanic">Hispanic</option>
<option value="asian">Asian/Pacific Islander</option>
<option value="native_american">Native American Indian</option>
<option value="other">Other</option>
</td>
</tr>
<tr>
<td>Year in School</td>
<td>
<select name="year_in_school">
<option value="freshman">Freshman</option>
<option value="sophomore">Sophomore</option>
<option value="junior">Junior</option>
<option value="senior">Senior</option>
</select>
</td>
<td>Phone Number:</td>
<td><input type="text" name="phone"></td>
</tr>
<tr>
<td>Email Address:</td>
<td><input type="text" name="email"></td>
<td>Street Address:</td>
<td>
<input type="text" name="address">
</td>
</tr>
<tr>
<td>Apt/Suite:</td>
<td>
<input type="text" name="suite_num">
</td>
<td>City:</td>
<td>
<input type="text" name="city">
</td>
</tr>
<tr>
<td>State:</td>
<td>
<select name="state">
<option value="Alabama">Alabama</option>
.....
</select>
</td>
<td>Zip Code:</td>
<td>
<input type="text" name="zip_code">
</td>
</tr>
<tr>
<td>Cumulutative GPA:</td>
<td><input type="text" name="gpa"></td>
<td>Major/Area of Study:</td>
<td><input type="text" name="major"></td>
</tr>
<tr>
<td>Twitter handle:</td>
<td>
<input type="text" name="twitter_handle">
</td>
</tr>
<tr>
<td colspan="2">
<p>Please describe any relevant teaching experience:</p>
<textarea rows="6" cols="45" name="teaching_experience">
</textarea>
</td>
<td colspan="2">
<p>Why do you want to join Moneythink?</p>
<textarea rows="6" cols="43" name="why_moneythink">
</textarea>
</td>
</tr>
</table>
<table>
<tr>
<td><input type="submit" value="Apply"></td>
<td><input type="reset" value="Clear"></td>
</tr>
</table>
</form>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('form').bind('submit', function(){
$.ajax({
type: 'post',
url: "/InsertNewMentor.php",
data: $("#formPost").serialize(),
success: function() {
alert("form was submitted");
}
});
return false;
});
});
</script>
try this

Related

How to make auto scroll Top after submitting error?

How to make auto scroll to Top after submit error and when it scroll up need to be smooth but not straight to the top and when it scroll to the top it need to have like 100px space gap from the header .
This is the code that I try to used but it doesn't seems to work in my code
This is the jquery I have tried :-
$("#submit").click( function() {
$(window).scrollTop(100);
});
And I have tried to insert this in the CSS :-
scroll-behaviour: smooth;
Sometimes it work but sometimes it can't work. But when I insert the scroll behavior the text field required error message doesn't appear.
And this is my php file code :-
<!DOCTYPE HTML>
<html>
<head>
<title>Create New Explore</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Montserrat">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="js/script.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="css/desaru.css" type="text/css">
<link rel="stylesheet" href="css/header.css" type="text/css">
<link rel="stylesheet" href="css/style.css" type="text/css">
<link rel="stylesheet" href="css/footer.css" type="text/css">
</head>
<body>
<br/>
<script src="js/script.js"></script>
<?php include('header.html'); ?>
<br/><br/><br/><br/>
<div id="scrollbox">
<!-- Content Section -->
<div class="container">
<div class="row">
<div class="col-md-12">
<h1><strong>Create New Explore</strong></h1>
</div>
</div>
<br/><br/>
<script>
$(document).ready(function() { // website fully loaded
$('#submit').click(function() { //if button id=submit click trigger function down
var name = $('#foldername').val(); //retrieve input for folder name
var httpvar = 'http://211.25.118.147';
var defaultfolder = '/resource/';
//alert(name); get retrieve test name
if(name==""){ // if foldername input blank
alert("Insert folder name");
}
else {
$.ajax( {
url : "addfolder.php",
type: "POST",
data: {foldername : name}, //pass input foldername = name(variable declare at the top) foldername name base on html that set
success: function(result){ //if success will sent the post data
//alert(result);
if (result=="success") { //based on output echo addfolder.php
alert("File "+name+" has been added");
$("#SelectImageFolder option[value='.."+defaultfolder+name+"']").remove();
$("#SelectImageFolder").append($('<option>', { //add new options
value : ".."+defaultfolder+name ,
text : httpvar+defaultfolder+name
}))
$("#SelectImageFolder option:last").attr("selected", "selected");//auto select the last option
}
else if(result=="fail") {// if the file exist then result will fail to create the file
alert("Something wrong happened");
}
}
}
)
}
})
});
</script>
<form id="createexplore" action="CreateExploreProcess.php" method="post" enctype="multipart/form-data" >
<table class='table table-hover table-responsive table-bordered'>
<!--<tr>
<td>Class</td>
<td colspan="2">
<input type='text' name='Class' readonly class='form-control' value='Explore' maxlength="20"/>
</td>
</tr>-->
<!--<tr>
<td>Placemark</td>
<td colspan="2">
<Input type='number' name="Placemark" class='form-control' >
</td>
</tr>-->
<tr>
<td>Category</td>
<td colspan="2">
<div class="custom-select" style="width:200px;">
<select required>
<option value="" selected disabled hidden>Select Category..</option>
<option value="Stay">Stay</option>
<option value="Dining">Dining</option>
<option value="Facilities">Facilities</option>
<option value="ThingstoDo">Things to Do</option>
<option value="NearbyAttractions">Nearby Attractions</option>
</select>
</div>
</td>
</tr>
<tr>
<td>Sub Category</td>
<td colspan="2">
<div class="custom-select" style="width:200px;">
<select required>
<option value="" selected disabled hidden>Select Sub Category... </option>
<option value="TheWestinDesaruCoastResort"> The Westin Desaru Coast Resort </option>
<option value="Kiosk"> Kiosk </option>
<option value="ShuttlePickupPoints"> Shuttle Pickup Points </option>
<option value="Rides&Attractions"> Rides & Attractions </option>
<option value="ParkingBay"> Parking Bay </option>
<option value="DesaruOstrichFarm"> Desaru Ostrich Farm </option>
<option value="Restroom"> Restroom </option>
<option value="Cafe"> Cafe </option>
<option value="AnataraCoastResort&Villas"> Anatara Coast Resort & Villas </option>
<option value="Kids"> Kids </option>
<option value="DesaruCrocodileFarm"> Desaru Crocodile Farm </option>
<option value="Restaurant"> Restaurant </option>
<option value="Riverside"> Riverside </option>
<option value="InformartionKiosk"> Informartion Kiosk </option>
<option value="Amphitheater"> Amphitheater </option>
<option value="MainAttractions"> Main Attractions </option>
<option value="DesaruCoastAdventureWaterPark"> Desaru Coast Adventure Water Park </option>
<option value="Golf"> Golf </option>
<option value="LuxuryResorts&Villas"> Luxury Resorts & Villas </option>
<option value="HardRockHotelDesaruCoast"> Hard Rock Hotel Desaru Coast </option>
<option value="ConferenceCentre"> Conference Centre </option>
<option value="Shopping"> Shopping </option>
<option value="Spas"> Spas </option>
<option value="BeachActivities"> Beach Activities </option>
<option value="DesaruFruitFarm"> Desaru Fruit Farm </option>
<option value="DisabledToilet"> Disabled Toilet </option>
<option value="FirstAid"> First Aid </option>
<option value="ChangingRoom"> Changing Room </option>
<option value="Locker"> Locker </option>
<option value="BabyChangingRoom"> Baby Changing Room </option>
<option value="LostandFound"> Lost and Found </option>
<option value="MuslimPrayerRoom"> Muslim Prayer Room </option>
</select>
</div>
</td>
</tr>
<tr>
<td>Item</td>
<td colspan="2">
<div class="custom-select" style="width:200px;">
<select required>
<option value="" selected disabled hidden>Select Item... </option>
<option value="Hotel"> Hotel </option>
<option value="Kiosks"> Kiosks </option>
<option value="ShuttlePickup"> Shuttle Pickup </option>
<option value="Rides&Attractions"> Rides & Attractions </option>
<option value="ParkingBay"> Parking Bay </option>
<option value="Sightseeing"> Sightseeing </option>
<option value="Restroom"> Restroom </option>
<option value="Cafe"> Cafe </option>
<option value="Kids"> Kids </option>
<option value="Restaurant"> Restaurant </option>
<option value="Riverside"> Riverside </option>
<option value="InformartionKiosks"> Informartion Kiosks </option>
<option value="Amphitheater"> Amphitheater </option>
<option value="MainAttractions"> Main Attractions </option>
<option value="DesaruCoastAdventureWaterPark"> Desaru Coast Adventure Water Park </option>
<option value="Golf"> Golf </option>
<option value="ConferenceCentre"> Conference Centre </option>
<option value="Shopping"> Shopping </option>
<option value="Spas"> Spas </option>
<option value="BeachActivities"> Beach Activities </option>
<option value="DisabledToilet"> Disabled Toilet </option>
<option value="FirstAid"> First Aid </option>
<option value="ChangingRoom"> Changing Room </option>
<option value="Locker"> Locker </option>
<option value="BabyChangingRoom"> Baby Changing Room </option>
<option value="LostandFound"> Lost and Found </option>
<option value="MuslimPrayerRoom"> Muslim Prayer Room </option>
</select></div>
</td>
</tr>
<tr>
<td>Title</td>
<td colspan="2">
<input type="text" required name='Title' class='form-control' maxlength="150"/>
</td>
</tr>
<tr>
<td>Details Header</td>
<td colspan="2">
<input type="text" required name="DetailsHeader" class='form-control' maxlength="200"/>
</td>
</tr>
<tr>
<td>Details</td>
<td colspan="2">
<textarea required name="Details" rows="8" class='form-control' maxlength="4000"></textarea>
</td>
</tr>
<tr>
<td>Button Promo</td>
<td colspan="2">
<Input required type="text" name="ButtonPromo" class='form-control' maxlength="20"/>
</td>
</tr>
<tr>
<td>Key Features</td>
<td colspan="2">
<Input required type="text" name="KeyFeatures" class='form-control' maxlength="20"/>
</td>
</tr>
<tr>
<td>Features</td>
<td colspan="2">
<textarea required name="FeaturesList" rows="5" class='form-control' maxlength="1000"></textarea>
</td>
</tr>
<tr>
<td>Image Folder</td>
<td colspan="2">
<select name="SelectImageFolder" id="SelectImageFolder" class='form-control'>
<option value="selected" selected="selected">Select a folder</option>
<?php
$dirs = glob("../resource/*", GLOB_ONLYDIR);
// create variable constant url
$httpvar = 'http://211.25.118.147';
foreach($dirs as $val){
$httpcon = str_replace("..",$httpvar,$val);
echo '<option value="'.$val.'">'.$httpcon."</option>\n";
}
?>
</select><br/>
<div class="input-group">
<input type="text" required name="foldername" id="foldername" placeholder="Folder Name" class='form-control' maxlength="100" />
<span class="input-group-btn">
<button type="button" name="submit" id="submit" class="btn"/>Add Folder</button>
</span>
</div></td>
<script="js/script.js">
</script>
</tr>
<tr>
<td>List Images</td>
<td colspan="2">
<input type="file" name="FileListImage" id="FileListImage">
</td>
</tr>
<tr>
<td>Carousel 1</td>
<td colspan="2">
<input required type="file" name="FileCarousel1" id="FileCarousel1">
</td>
</tr>
<tr>
<td>Carousel 2</td>
<td colspan="2">
<input type="file" name="FileCarousel2" id="FileCarousel2">
</td>
</tr>
<tr>
<td>Carousel 3</td>
<td colspan="2">
<input type="file" name="FileCarousel3" id="FileCarousel3">
</td>
</tr>
<tr>
<td>Carousel 4</td>
<td colspan="2">
<input type="file" name="FileCarousel4" id="FileCarousel4">
</td>
</tr>
<tr>
<td>Carousel 5</td>
<td colspan="2">
<input type="file" name="FileCarousel5" id="FileCarousel5">
</td>
</tr>
<tr>
<td>Carousel 6</td>
<td colspan="2">
<input type="file" name="FileCarousel6" id="FileCarousel6">
</td>
</tr>
<tr>
<td>Find On Map</td>
<td colspan="2">
<Input required type="text" name="FindOnMap" class='form-control' maxlength="100"/>
</td>
</tr>
<tr>
<td>Call To Book</td>
<td colspan="2">
<Input type="text" name="CallToBook" class='form-control' maxlength="100"/>
</td>
</tr>
<!--<tr>
<td>Find On Map Ico</td>
<td> <input type="url" name="FindOnMapIco" class='form-control' /> </td>
<td><input type="file" name="FileImage" id="FileImage"></td>
</tr>
<tr>
<td>Call To Book Ico</td>
<td> <input type="url" name="CallToBookIco" class='form-control' /></td>
<td><input type="file" name="FileImage" id="FileImage"></td>
</tr>-->
<tr>
<!--<td >Icon</td>
<td colspan="2">
<input type="url" name="Icon" class='form-control' maxlength="100"/>
</td>
</tr>-->
<tr>
<td>In Park</td>
<td colspan="2">
<div class="custom-select" style="width:200px;">
<select required>
<option value="" selected disabled hidden>Select... </option>
<option value="Yes"> Yes </option>
<option value="No"> No </option>
<option value=""> </option>
</select>
</div>
</td>
</tr>
<tr>
<td>Ticket Entry</td>
<td colspan="2">
<input type="text" name="TicketedEntry" class='form-control' maxlength="100"/>
</td>
</tr>
<tr>
<td>Operation Hours</td>
<td colspan="2">
<textarea name="OperationHours" rows="6" class='form-control'> </textarea>
</td>
</tr>
<tr>
<td>Ride Details</td>
<td colspan="2">
<textarea name="RideDetails" class='form-control' maxlength="255"/></textarea>
</td>
</tr>
<tr>
<td>Listing Details</td>
<td colspan="2">
<textarea name="ListingDetails" class='form-control' maxlength="255"/></textarea>
</td>
</tr>
<tr>
<!--<td>Favourites</td>
<td colspan="2">
<div class="custom-select" style="width:200px;">
<select>
<option value="" selected disabled hidden>Select... </option>
<option value="Yes"> Yes </option>
<option value=""> </option>
</select>
</div>
</td>
</tr>
<tr>
<td>FB Like</td>
<td colspan="2">
<div class="custom-select" style="width:200px;">
<select>
<option value="" selected disabled hidden>Select... </option>
<option value="Yes"> Yes </option>
<option value=""> </option>
</select>
</div>
</td>
</tr>-->
<tr>
<td>More Details</td>
<td colspan="2">
<input type="text" name="MoreDetails" class='form-control' maxlength="100"/>
</td>
</tr>
<tr>
<td>Distance </td>
<td colspan="2">
<input type="text" name="DistanceAway" class='form-control' maxlength="100"/>
</td>
</tr>
<tr>
<td>Status</td>
<td colspan="2">
<div class="custom-select" style="width:200px;">
<select required>
<option value="" selected disabled hidden>Status... </option>
<option value="Active"> Active </option>
<option value="Inactive"> Inactive </option>
</select>
</div>
</td>
</tr>
<tr>
<td>Zoom</td>
<td>
<input type="number" name="ZoomStart" class='form-control' placeholder="Start" min="14" max="19"/>
</td>
<td>
<input type="number" name="ZoomEnd" class='form-control' placeholder="End" min="14" max="19"/>
</td>
</td>
</tr>
<tr>
<td>GPS Coordinate</td>
<td>
<input type="text" id="Lat" name="Lat" class='form-control' placeholder="Latitude" maxlength="12"/>
</td>
<td>
<input type="text" id="Lng" name="numeric" class='form-control' placeholder="Longitude" maxlength="12"/>
</td>
</td>
<script src="js/script.js">
</script>
</tr>
<tr>
<td>Phone</td>
<td colspan="2">
<input required type="text" id="hpno" name="Phone" class='form-control' maxlength="12"/>
</td>
<script src="js/script.js">
</script>
</tr>
<tr>
<td></td>
<td colspan="2">
<input type='submit' id='submit' name='Add' value='Save' class='btn btn-warning'/>
<a href='Explore.php' class='btn btn-danger'>Back</a>
</td>
</tr>
<span id="error_message" class="text-danger"></span>
<span id="success_message" class="text-success"></span>
</table>
</form>
<!-- End Content Section -->
<?php include('footer.html'); ?>
</div> </div>
<script src="js/script.js"></script>
</body>
</html>
And CSS code:-
#scrollbox {
overflow-y:auto;
height: 478px;
width: 100%;
margin-top: -80px;
scroll-behaviour: smooth;
}

How to send dynamic option text and value using jquery and php

I have design a dynamic html table and it contains 2 table columns :
column1: Item Name. It comes from selected option.
column2: Item Price. It comes from selected option value.
Right now I am selecting option in first column and passing value into input field in second column. After adding as many rows I need, I want to pass both their text and value in php.
But php is getting only option value instead of having both text and value.
Here is my code
$('#myTable').on('change', '.mySelect', function() {
// you can use .closest() to find
// particular input on same row with select
$(this).closest('tr').find('.amount').val($(this).val());
//$(this).closest('tr').find('.mySelect').val($(".mySelect option:selected").text());
});
$('#myTable').on('click','.remScnt', function(e) {
e.preventDefault();
// find the tr element of remove link
// which is a parent
$(this).closest('tr').remove()
});
$(".mySelect option").filter(function() {
//may want to use $.trim in here
return $(this).text() == $(this).val();
}).prop('selected', true);
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<style>
table, th, td {
border-collapse: collapse;
margin: 10px auto;
}
</style>
<script>
function addMore() {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(-1);
var cell2 = row.insertCell(-1);
var x = document.getElementById("myTable").rows[1].cells;
cell1.innerHTML = x[0].innerHTML;
cell2.innerHTML = x[1].innerHTML;
}
function removeLast() {
document.getElementById("myTable").deleteRow(-1);
}
function removeRowNo() {
var index = document.getElementById('value').value
document.getElementById("myTable").deleteRow(index);
}
</script>
</head>
<body>
<form action="testlist.php" method="post">
<table>
<tr>
<td>
Month:
</td>
<td>
<select name="SALMT" id="month" onchange="" size="1">
<option value="" disabled selected>Month</option>
<option value="1">January</option>
<option value="2">February</option>
<option value="3">March</option>
<option value="4">April</option>
<option value="5">May</option>
<option value="6">June</option>
<option value="7">July</option>
<option value="8">August</option>
<option value="9">September</option>
<option value="10">October</option>
<option value="11">November</option>
<option value="12">December</option>
</select>
</td>
<td>
Year:
</td>
<td> <input type="text" name="SALYR">
</td>
</tr>
<tr>
<td>
Employee ID:
</td>
<td> <input type="text" name="EMPID">
</td>
<td>
Name:
</td>
<td><input type="text" name="NM">
</td>
</tr>
<tr>
<td>
Department Code:
</td>
<td> <input type="text" name="DPTID">
</td>
<td>
Designation:
</td>
<td><input type="text" name="DSG">
</td>
</tr>
</table>
<table id="myTable">
<tr>
<th>Items</th>
<th>Amount</th>
</tr>
<tr>
<td >
Remove
<select class="mySelect" name="DESCRP[]" >
<option disabled="" selected="">Select</option>
<option value="100">Item-1</option>
<option value="200">Item-2</option>
<option value="300">Item-3</option>
<option value="400">Item-4</option>
<option value="500">Item-5</option>
</select>
</td>
<td> <input type="text" class="amount" name="ALAMT[]"></td>
</tr>
</table>
<table>
<tr>
<td><input type="submit" /> </td>
</tr>
</table>
</form>
<br>
<table>
<tr>
<td><button onclick="addMore()">Add More</button></td>
<td><button onclick="removeLast()">Remove Last Row</button></td>
</tr>
<tr>
<td><input type="text" maxlength="3" name="value" id='value'></td>
<td><button onclick="removeRowNo()">Remove By Row No.</button></td>
</tr>
</table>
</body>
</html>
Here is php code:
<?php
var_dump($_POST);
echo "<br>";
echo count($_POST["DESCRP"]);
foreach ($_POST["DESCRP"] as $d) {
echo "<br>";
echo $d;
}
echo "<br>Amount:";
echo count($amount = $_POST["ALAMT"]);
foreach ($_POST["DESCRP"] as $a) {
echo "<br>";
echo $a;
}
?>
You mean
<td>
<select class="mySelect">
<option value="">Select</option>
<option value="100">Item-1</option>
<option value="200">Item-2</option>
<option value="300">Item-3</option>
<option value="400">Item-4</option>
<option value="500">Item-5</option>
</select>
<input type="hidden" class="descr" name="DESCRP[]" />
</td>
<td> <input type="text" class="amount" name="ALAMT[]"></td>
using
$('#myTable').on('change', '.mySelect', function() {
$(this).closest('tr').find('.amount').val($(this).val());
$(this).closest('tr').find('.descr').val($("option:selected",this).text());
});
For DESCRP[0] = item-1, DESCRP[1] = item-5
modify the select as follows :
<option value="Item-1" data-val="100">Item-1</option>
$('#myTable').on('change', '.mySelect', function() {
$(this).closest('tr').find('.amount').val($(this).attr('data-val'));
});

Value from drop down list html

Trying to pass the value from Drop down list through but couldnt get it.
<tr>
<td>Size <br>
(Only applicable for T-Shirt):</td>
<td><select name=size>
<option value=N>NIL</option>
<option value=S>S</option>
<option value=M>M</option>
<option value=L>L</option>
<option value=XL>XL</option>
</select></td>
</tr>
<tr>
<td></td>
<td><a href= manageProduct.php?size=$_GET[size]>Insert</a></td>
</tr>
Give this a try: (just an example).
<form action="<?php $_SERVER['PHP_SELF']?>" method="GET">
<table>
<tr>
<td nowrap>Size:
(Only applicable for T-Shirt):</td>
<td><select name="size">
<option value="N">NIL</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select></td>
</tr>
<tr>
<td><p align="right"></p></td>
<td><input type="submit" value="Insert" />
</td>
</tr>
</table>
</form>
<?php
$size = $_GET['size'];
if($_GET['size']=="N")
{
echo "you chose NOTHING, make another choice.";
}
else {
echo "Your choice of size is: $size";
}
?>
Html
<form action="manageProduct.php" method="POST">
<table>
<tr>
<td>Size <br>
(Only applicable for T-Shirt):</td>
<td><select name=size>
<option value=N>NIL</option>
<option value=S>S</option>
<option value=M>M</option>
<option value=L>L</option>
<option value=XL>XL</option>
</select></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="Insert" /></td>
</tr>
</table>
</form>
PHP
$size = $_POST['size'];
You need a form using the GET action then you can get your variable.
Assuming this page is the manageProduct.php:
<!--GET your data from the submitted form OR do something depending on what size returns in the url-->
<?php
if($_GET['size']=="SIZE"){ echo whatever or do whatever}
?>
<td>Whatever you're trying to do</td>
<form id="form" method="get" action="manageProduct.php">
<tr>
<td>Size <br>
(Only applicable for T-Shirt):</td>
<td><select name="size">
<option value="N">NIL</option>
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select></td>
</tr>
<tr>
<td></td>
<td><input type="submit" name="Submit" value="Insert" /></td>
<br />
</form>
</tr>

Posting Form Into SQL Database

The very first field named Forte ID posts a value of 0 no matter what selection I choose. Here are my two files:
Index.php(Form)
</head>
<h1> Customer Service Log Form </h1>
<form method="post" action="insert.php">
<table width="625" border="0">
<tr>
<td> Forte ID:</td>
<td><select id="ForteID" name="ForteID">
<option value="0">Select Your ID</option>
<option value="as7326">as7326</option>
<option value="aw8743">aw8743</option>
<option value="bj0920">bj0920</option>
<option value="bs1441">bs1441</option>
<option value="dk7017">dk7017</option>
<option value="dl7686">dl7686</option>
<option value="dm2940">dm2940</option>
<option value="jn2468">jn2468</option>
<option value="jw9598">jw9598</option>
<option value="kp4945">kp4945</option>
<option value="nl2589">nl2589</option>
<option value="rp7021">rp7021</option>
<option value="sh1346">sh1346</option>
</select></td>
</tr>
<tr>
<td> Disposition</td>
<td><select id="disposition" name="disposition">
<option value="0">Select a Disposition</option>
<option value="Save">Save</option>
<option value="Sale">Sale</option>
<option value="LOC">LOC</option>
<option value="Backout">Backout</option>
<option value="Revision">Revision</option>
<option value="Revision">Revision/Save</option>
</select>
</td>
</tr>
</table>
<hr />
<br />
<table width="400" border="0">
<tr>
<td>App Number:</td>
<td></td>
<td><input name="appnumber" type="text" required="required"></td>
</tr>
<tr>
<td>Finance Number:</td>
<td></td>
<td><input type="text" name = "Finance_Num"></td>
</tr>
<tr>
<td>Phone Number:</td>
<td></td>
<td><input type="text" name = "Phone_Num"></td>
</tr>
<tr>
<td># of Payments Collected:</td>
<td></td>
<td><input type="text" name = "num_payments"></td>
</tr>
<tr>
<td>ACH/CC</td>
<td></td>
<td><select id="ForteID" name="ForteID">
<option value="0">Select Payment</option>
<option value="ach">Checking</option>
<option value="cc">Credit Card</option>
</select></td>
</tr>
<tr>
<td>Date:</td>
<td></td>
<td><input name = "date" type="text" id="datepicker" autocomplete="off" required="required"></td>
</tr>
</table>
<br />
Notes:
<br />
<textarea name="notes" id="notes" cols="45" rows="5"></textarea>
</fieldset>
<hr />
<input type="Submit" name="formSubmit" value="Submit">
<input type="Reset" name="formReset" value="Reset">
<input type="button" value="View Logs" onClick="window.location.href='logs.php';">
</form>
</head>
Insert.php (PHP file to insert data from form into SQL Server Database):
$serverName = 'Server\SQLEXPRESS';
$connectionInfo = array('Database'=>'database', 'UID'=>'username', 'PWD'=>'password');
$connection = sqlsrv_connect($serverName, $connectionInfo);
if( $connection === false )
{
echo "Connection could not be established.\n";
die( print_r( sqlsrv_errors(), true));
}
$tsql = "INSERT INTO logs(ForteID, disposition, appnumber, Finance_Num, num_payments, ach_cc, date, notes, Phone_Num) VALUES (?,?,?,?,?,?,?,?,?)";
$parameters = array( $_POST[ForteID], $_POST[disposition], $_POST[appnumber], $_POST[Finance_Num], $_POST[num_payments], $_POST[ach_cc], $_POST[date], $_POST[notes], $_POST[Phone_Num]);
$stmt = sqlsrv_query($connection, $tsql, $parameters);
if( $stmt === false ){
echo "Statement could not be executed.\n";
die( print_r( sqlsrv_errors(), true));
} else {
echo "Rows affected: ".sqlsrv_rows_affected( $stmt )."\n";
}
No matter what option is selected in the index.php field Forte ID, it posts a value of 0. What is wrong. It was working before I added a field named Phone Number. But doesnt make sense why that would screw up the selections.
Let me know if I need to clarify anything and thanks for the help in advance!
You have to fields called ForteID
<select id="ForteID" name="ForteID">
<option value="0">Select Payment</option>
<option value="ach">Checking</option>
<option value="cc">Credit Card</option>
is the 2nd one

Cascading drop down list with ajax in php

I have a cascading dropdown list which is fetched from the database through ajax.
The list loads but its not posting to the database nor is the code seen behind.
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getCity(stateid)
{
//alert(stateid);
var strURL="findCity.php?state="+stateid;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4) // only if "OK"
{
if (req.status == 200)
{
document.getElementById('citydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
and the php file
<? $state=$_GET['state'];
$link = mysql_connect('localhost', '', ''); //change the configuration if required
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('a'); //change this if required
$query="select FOR_CODE,FOR_DESC from maruti_city where FOR_STAT_CODE='{$state}' order by FOR_DESC";
$result=mysql_query($query);?>
<select name="city" onchange="getDealer(this.value)" class="sel" >
<option value="0">Select City</option>
<? while($row=mysql_fetch_array($result)) { ?>
<option value><?=$row['FOR_DESC']?></option>
<?} ?>
</select>
The DDL's Load but these values are not getting posted to the database.
form
<div class="container">
<table width="528" border="0" cellpadding=1 class="formTable" style="width: 515px;font-family:arial;font-size:12px;" >
<form action="form_submit.php" method="POST" name="alto800" id="alto800" onsubmit="return validate();">
<tbody>
<tr>
<td width="52%">Name</td>
<td width="48%" >Mobile/Phone No.</td>
</tr>
<tr>
<td>
<select name="title" id="mr" class="sel">
<option value="mr">Mr.</option>
<option value="mrs">Mrs.</option>
</select>
<input type="text" name="name" id="name" class="formName" />
</td>
<td>
<input type="text" name="mobile" id="mobile"/>
</td>
</tr>
<tr>
<td >State</td>
<td >City</td>
</tr>
<tr>
<td>
<select name="state" id="state" class="sel" onchange="getCity(this.value)">
<option value="0">Select state</option>
<option value="AN">ANDAMAN</option>
<option value="AP">ANDHRA PRADESH</option>
<option value="AR">ARUNANCHAL PRADESH</option>
<option value="AS">ASSAM</option>
<option value="BH">BIHAR</option>
<option value="CG">CHATTISGARH</option>
<option value="CH">CHANDIGARH</option>
<option value="DL">DELHI</option>
<option value="DM">DAMAN</option>
<option value="DN">DADRA & NAGAR HAVELI</option>
<option value="GJ">GUJRAT</option>
<option value="GO">GOA</option>
<option value="HN">HARYANA</option>
<option value="HP">HIMACHAL PRADESH</option>
<option value="JH">JHARKHAND</option>
<option value="JK">JAMMU & KASHMIR</option>
<option value="KL">KERALA</option>
<option value="KT">KARNATAKA</option>
<option value="MH">MAHARASHTRA</option>
<option value="ML">MEGHALAYA</option>
<option value="MN">MANIPUR</option>
<option value="MP">MADHYA PRADESH</option>
<option value="MZ">MIZORAM</option>
<option value="NG">NAGALAND</option>
<option value="OS">ORISSA</option>
<option value="PJ">PUNJAB</option>
<option value="PY">PONDICHERRY</option>
<option value="RJ">RAJASTHAN</option>
<option value="SK">SIKKIM</option>
<option value="TN">TAMIL NADU</option>
<option value="TR">TRIPURA</option>
<option value="UP">UTTAR PRADESH</option>
<option value="UT">UTTARANCHAL</option>
<option value="WB">WEST BENGAL</option>
</select>
</td>
<td><div id="citydiv">
<select name="city" id="city" class="sel" onChange="getDealer(this.value)" >
<option value="0">Select state first</option>
</select>
</div>
</td>
</tr>
<tr>
<td >Preffered Dealer</td>
<td > </td>
</tr>
<tr>
<td colspan="2"><div id="dealerdiv"><select name="dealer" style="width:500px;height:25px;" >
<option value="0">Select city first</option>
</select> </div> </td>
</tr>
<tr>
<td>Email Address</td>
<td> </td>
</tr>
<tr>
<td><input type="text" name="email" id="email" /></td>
<td> </td>
</tr>
<tr>
<td >Your Query</td>
<td rowspan="2" ><br />
<br /> </td>
</tr>
<tr>
<td>
<textarea name="query" id="query"></textarea>
</td>
</tr>
<tr>
<td >
<div style="height:10px"></div>
<input type="image" name="submit" value="submit" src="images/submit.png" />
</td>
<td ></td>
</tr>
</tbody>
</form>
</table>

Categories