First, let's wrap up the HTML data.
<div class="message"></div>
<form action="subscribe.php" name="subscribeForm">
<input type="email" name="emailsub" minlength="7" size="40" placeholder="Enter your email here.."><br><br>
<select name="medium">
<option value="">Select Medium</option>
<option value="english">English</option>
<option value="hindi">Hindi</option>
<option value="japanese">Japanese</option>
</select>
<br><br>
<select name="country">
<option value="">Select Country</option>
<option value="India">India</option>
<option value="USA">USA</option>
<option value="Japan">Japan</option>
</select><br><br>
<input type="submit" id="action">
</form>
AJAX code below takes the form details and sends to subscribe.php. Note that document.subscribeForm below takes your form field variables and stores in the form. For this only name value in HTML part is enough. Hence, I have not added any id field in the HTML form fields.
$('#action').click(function() {
var form = document.subscribeForm;
var dataString = $(form).serialize();
$.ajax({
type: 'POST',
url: $(form).attr("action"),
data: dataString,
beforeSend: function(){
$('.message').hide();
$("#action").val('Please wait...');
},
success: function(data){
$('.message').html(data).fadeIn();
}
});
return false;
});
Once the data is sent to subscribe.php, it's now time to process it.
// Storing data in variables
$email = (!empty($_POST['emailsub'])?$_POST['emailsub']:null;
$medium = (!empty($_POST['medium'])?$_POST['medium']:null;
$country = (!empty($_POST['country'])?$_POST['country']:null;
if($_POST){
// Check if email submitted is empty or not. If yes, script will stop executing further.
if($email == null){
echo "Email is required";
exit();
}
// Check if medium submitted is empty or not. If yes, script will stop executing further.
if($medium == null){
echo "Medium is required";
exit();
}
// Check if country submitted is empty or not. If yes, script will stop executing further.
if($country == null){
echo "Country is required";
exit();
}
// All checks cleared. Process the data.
//Using MySQLi
$stmt = $con->prepare("INSERT INTO emailsubscribe(email, medium, country)VAlUES(?,?,?)"); // Use prepared statements.
$stmt-> bind_param($email, $medium, $country);
$stmt-> execute();
// Using PDO (Better: A big bonus is that you can use a readable `:name` instead of confusing `?`)
$stmt = $con->prepare("INSERT INTO emailsubscribe(email, medium, country)VAlUES(:email, :medium, :country)"); // Use prepared statements.
$stmt-> bindValue(':email', $email);
$stmt-> bindValue(':medium', $medium);
$stmt-> bindValue(':country', $country);
$stmt-> execute();
// Echo Message
if($stmt){
echo "Success";
}else{
echo "Error";
}
}
This is the proper way how you should process your forms.