How to pass API Key with a PHP Wrapper - php

I have a HTML form that send a request to API with AJAX. But i would not leave the api key in the JS file. So, i thinked to do a PHP wrapper but i'm at start and i don't know how can i do. Can you give me some exemples for understand this process?
I have this form that redirect to the url:
<form action="www.mysite.com/subscribe" method="POST" accept-charset="utf-8" id="signup-form" name="signup-form">
<div class="form-group">
<input type="text" class="form-control" name="name" id="name" placeholder="Nome"/>
</div>
<div class="form-group">
<input type="text" class="form-control" name="cognome" id="cognome" placeholder="Cognome"/>
</div>
<div class="form-group">
<input type="email" class="form-control" name="email" id="email" placeholder="Email"//>
</div>
<?php include('countries.php'); ?>
<div class="form-group">
<select class="form-control" id="list" name="list">
<option value="" disabled="disabled">Seleziona un interesse</option>
<option value="aVD3PdrkiaVJhVU9yN9nMQ">lista 3</option>
<option value="spd7cktddsPGTgoDuu892f763Q">lista 2</option>
<option value="yCQHvcGxKvBFTeoSp892UxZA">lista 1</option>
</select>
</div>
<div class="form-group form-check">
<input type="checkbox" class="form-check-input" name="gdpr" id="gdpr" >
<label class="form-check-label" for="gdpr">Accetta il gdpr</label>
</div>
<input type="submit" value="Sign up" id="submit-btn"/>
<p id="status"></p>
</form>
And my JS file with AJAX call (Miss some elements)
$(document).ready(function() {
$("#signup-form").submit(function(e) {
console.log('submitting');
e.preventDefault();
var $form = $(this),
url = $form.attr('action');
url = 'https://sendy.exnovostudio.eu/subscribe';
var e = document.getElementById("list");
var list = e.value;
params = {
name: $form.find('input[name="name"]').val(),
email: $form.find('input[name="email"]').val(),
list: list,
api_key: <---I WANT HIDE THIS BUT IT DOESN T WORK IF I DELETE
gdpr : gdpr,
boolean: true
}
window.message = function(text, color){
$("#status").css("color", color).text(text);
}
$form.find('input').attr("disabled", "disabled");
message('iscrizione in corso...', 'blue');
What is the best practice to share the api key in the AJAX call?

Related

How to submit form on one page to a different page using ajax call in jquery

I have a page called page2.php. It has a form that allows you to search via jquery ajax call. The code is below. My question is, I have a different form on page1.php. How can I submit the form on page1.php to go to page2.php and have it execute the page2.php code below using the data from the form on page1.php? I know this is most likely simple, having a brain fart right now.
$(function() {
$.validate({
form: '#form_search',
validateOnBlur: false,
errorMessagePosition: 'top',
onSuccess: function(form) {
var formval = $(form).serialize();
var formurl = '/page2.php?a=search';
$('#form_results').html('<div class="form_wait_search">Searching, please wait...<br><img src="/images/search-loader.gif"></div>');
$.ajax({
type: 'POST',
url: formurl,
data: formval,
success: function(data){
var json = $.parseJSON(data);
$('#form_errors').html(json.message);
$('#form_results').html(json.results);
}
});
return false;
}
});
});
UPDATE
Here is the forms Im referring to.
On page1.php this is like a module on the right side bar. Just a form that I want to post to page2.php
<div class="scontent_box1">
<strong class="box_title"><i class="fa fa-search fa-flip-horizontal"></i> Find Locations</strong>
<form method="post" action="/page2.php">
<div class="form-group">
<label>Street Address</label>
<input type="text" class="form-control" name="ad" placeholder="Enter Street Address...">
</div>
<div class="form-group">
<label>City, State or Zip Code</label>
<input type="text" class="form-control" name="ct" placeholder="Enter City, State or Zip Code...">
</div>
<button type="submit" class="btn btn-default blue_btn">Search</button>
</form>
</div>
Now here is the form on page2.php that executes the ajax code above. I want page1.php to submit to page2.php and envoke the same jquery code above.
<div class="row no_gutters">
<div class="search_page">
<div id="form_errors"></div>
<form method="post" id="form_search">
<div class="form-group">
<label for="ad">Street Address<span class="reqfld">*</span></label>
<input type="text" class="form-control" data-validation="required" id="ad" name="ad" placeholder="Enter Street Address..." value="">
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label for="ct">City, State or Zip Code<span class="reqfld">*</span></label>
<input type="text" class="form-control input-sm" data-validation="required" id="ct" name="ct" placeholder="Enter City Name..." value="">
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 col-xs-12">
<button type="submit" class="btn btn-default blue_btn btn-block">Search Locations</button>
</div>
<div class="col-md-8"></div>
</div>
</form>
</div>
<div id="form_results"></div>
</div>

jQuery multiple select show hide not applying to all select elements

To keep it simple I have 2 form multiple select elements. Depending on the dropdown selected, it will auto hide or show additional input fields.
This is achieved like such:
$(document).ready(function(){
$("#find-replace1 select").change(function(){
$( "select option:selected").each(function(){
if($(this).attr("value")=="Find/Replace"){
$(".rep1").hide();
$(".find1").show();
$(".replace1").show();
} else {
$(".rep1").show();
$(".find1").hide();
$(".replace1").hide();
}
});
}).change();
});
$(document).ready(function(){
$("#find-replace2 select").change(function(){
$( "select option:selected").each(function(){
if($(this).attr("value")=="Find/Replace"){
$(".rep2").hide();
$(".find2").show();
$(".replace2").show();
} else {
$(".rep2").show();
$(".find2").hide();
$(".replace2").hide();
}
});
}).change();
});
My html is:
<p>
<form method="POST" action="#" accept-charset="UTF-8">
<div id="find-replace1" class="form-group-a">
<select class="form-control" name="priceaction">
<option value="Append">Append</option>
<option value="Prepend">Prepend</option>
<option value="Replace">Replace</option>
<option value="Find/Replace">Find/Replace</option>
</select>
</div>
<div class="form-group-a">
<input class="form-control formwidth rep1" autocomplete="off" name="value" type="text" style="display: block;">
</div>
<div class="form-group-a">
<input class="form-control formwidth find1" autocomplete="off" placeholder="find this" name="find" type="text" style="display: none;">
</div>
<div class="form-group-a">
<input class="form-control formwidth replace1" autocomplete="off" placeholder="replace with" name="replace" type="text" style="display: none;">
</div>
<div class="clear"></div>
<input type="submit" value="Update">
</form>
</p>
<hr>
<p>
<form method="POST" action="#" accept-charset="UTF-8">
<div id="find-replace2" class="form-group-a">
<select class="form-control" name="priceaction">
<option value="Append">Append</option>
<option value="Prepend">Prepend</option>
<option value="Replace">Replace</option>
<option value="Find/Replace">Find/Replace</option>
</select>
</div>
<div class="form-group-a">
<input class="form-control formwidth rep2" autocomplete="off" name="value" type="text" style="display: block;">
</div>
<div class="form-group-a">
<input class="form-control formwidth find2" autocomplete="off" placeholder="find this" name="find" type="text" style="display: none;">
</div>
<div class="form-group-a">
<input class="form-control formwidth replace2" autocomplete="off" placeholder="replace with" name="replace" type="text" style="display: none;">
</div>
<div class="clear"></div>
<input type="submit" value="Update">
</form>
</p>
Here is the jsfiddle: https://jsfiddle.net/kqjkprc1/
On my live site I actually have more than one form element but I kept it simple with 2 for this example. I notice it only applies the jQuery to the last form element on the page no matter what. Not sure why the first form element is unaffected and won't show/hide the hidden input fields.
On the one hand you can add different form actions like this
<form method="POST" action="update_1.php" >
</form>
<form method="POST" action="update_2.php">
</form>
on the other hand you can define differnt submit names
<form method="POST" action="#" >
<input type="submit" name="form1">
</form>
<form method="POST" action="#" >
<input type="submit" name="form2">
</form>
and get in in the php file like that
if (!empty($_POST['form1'])) {
//do something here for form 1;
}
if (!empty($_POST['form2'])) {
//do something here for form 2;
}
--- UPDATE ---
ahh ok i think i have a solution for you (first line changes)
$( "option:selected", this).each(function(){
if($(this).attr("value")=="Find/Replace"){
$(".rep1").hide();
$(".find1").show();
$(".replace1").show();
} else {
$(".rep1").show();
$(".find1").hide();
$(".replace1").hide();
}
});
https://jsfiddle.net/kqjkprc1/1/

HTML/PHP How do I generate new text-fields on a form based upon a select option field value?

When the user picks either phone or email I want the form to then generate a box to enter the details of which they selected. How do I do this? Thanks.
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix">
<label class="required">Phone</label>
<input type="text" name="fields[phone]" value="<?= (isset($fields['phone']) ? $fields['phone'] : '' )?>"/>
</div>
<div class="field-container full clearfix">
<label class="required">E-mail Address</label>
<input type="text" name="fields[email]" value="<?= (isset($fields['email']) ? $fields['email'] : '' )?>"/>
</div>
Here's a snippet that shows you how to do that with javascript:
document.getElementById('selection').addEventListener('change',function(){
var inputs = document.querySelectorAll('.hideAndShowInput > input');
for (var i = 0; i<inputs.length;i++) {
inputs[i].setAttribute('type','hidden');
inputs[i].parentNode.style.display= 'none';
}
document.getElementById(this.value).parentNode.style.display='block';
document.getElementById(this.value).setAttribute('type',this.value);
});
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select id="selection" name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">Phone</label>
<input type="hidden" id="phone" name="fields[phone]" value="">
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">E-mail Address</label>
<input type="hidden" id="email" name="fields[email]" value=""/>
</div>
<div class="field-container full clearfix">
<label class="required">otherField1</label>
<input type="text" id="other" name="fields[p]" value="otherField">
</div>
<div class="field-container full clearfix">
<label class="required">otherField2</label>
<input type="text" id="lsd" name="fields[em]" value="otherField2"/>
</div>
Please note that I added a Id to the select element and to the input elements.
EDIT | USAGE
Create a file, call it script.js or whatever you like and put this in it:
document.getElementById('selection').addEventListener('change',function(){
var inputs = document.querySelectorAll('.hideAndShowInput > input');
for (var i = 0; i<inputs.length;i++) {
inputs[i].setAttribute('type','hidden');
inputs[i].parentNode.style.display= 'none';
}
document.getElementById(this.value).parentNode.style.display='block';
document.getElementById(this.value).setAttribute('type',this.value);
});
Save the file to a folder on your server that is accesible. For example /public/js/script.js
In your html, add
<script src="/public/js/script.js"></script> <!-- or however your path is -->
to the very end of your file, directly before the closing </body> tag So that it looks like this
<div class="field-container full clearfix">
<label class="required">What is your prefered method of contact? </label>
<select id="selection" name="fields[contact]">
<option value="blank"></option>
<option value="phone">Phone</option>
<option value="email">E-mail</option>
</select>
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">Phone</label>
<input type="hidden" id="phone" name="fields[phone]" value="">
</div>
<div class="field-container full clearfix hideAndShowInput" style="display:none;">
<label class="required">E-mail Address</label>
<input type="hidden" id="email" name="fields[email]" value=""/>
</div>
<div class="field-container full clearfix">
<label class="required">otherField1</label>
<input type="text" id="other" name="fields[p]" value="otherField">
</div>
<div class="field-container full clearfix">
<label class="required">otherField2</label>
<input type="text" id="lsd" name="fields[em]" value="otherField2"/>
</div>
<script src="/public/js/script.js"></script> <!-- here is the script included -->
</body>
That's it.
This worked for me:
Add an id to your select: select name="fields[contact]" id="contact"
Set phone and email fields to hidden by using a class or inline style: div class="field-container full clearfix hide-this" id="phone-container"
--or just set style: display:none;
Javascript:
$('#contact').change(function(){
if(this.selectedOptions[0].text == 'phone') {
$('#phone-container').show().focus();
}else{$('#phone-container').hide();}
});
This should do the trick... let me know?
//CODE
<!DOCTYPE html>
<html>
<head>
<style>
.field-hide{
display: none;
}
</style>
<script>
function valChange(ele){
var fields = document.getElementById("container").children;
for(var i=0; i < fields.length; i++){
fields[i].classList.add("field-hide");
}
switch(ele.value){
case "phone":
document.getElementById("phone").classList.remove("field-hide");
break;
case "email":
document.getElementById("email").classList.remove("field-hide");
break;
}
}
</script>
</head>
<body>
<div class="field-container full clearfix">
<label class="required">What is your preferred method of contact?</label>
<select type="text" name="fields[contact]" onchange="valChange(this)">
<option value="blank" selected disabled>Choose</option>
<option value="phone">Quoted</option>
<option value="email">Labour Only</option>
</select>
</div>
<div id="container">
<div class="field-container full clearfix field-hide" id="phone">
<label class="required">Phone</label>
<input type="text" name="fields[phone]" placeholder="enter phone number">
</div>
<div class="field-container full clearfix field-hide" id="email">
<label class="required">E-mail Address</label>
<input type="text" name="fields[email]" placeholder="enter email">
</div>
</div>
</body>
</html>

post multiple fields with same name

I have a form by multiple field. In this form i can add multiple group field by prese a button via javascript. To understand exactly what I mean please see fiddle:
https://jsfiddle.net/alihesari/060ym890/2/
How to get all added fields by php and insert theme in mysql after submit?
<fomr action="">
<button type="button" id="add_hotel" class="btn btn-primary">
Add Hotel</button>
<button type="button" id="remove_hotel" class="btn btn-warning">Remove Hotel</button>
<ul class="hotels_ul">
<li class="hotel_li">
<div class="row">
<div class="col-md-10">
<div class="form-group">
<label for="hotel_name[]">Hotel Name:</label>
<input type="text" name="hotel_name[]" id="hotel_name[]" class="form-control" placeholder="Hotel Name">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="hotelRate[]">Hotel Rate: </label>
<select name="hotelRate[]" id="hotelRate[]" class="form-control">
<option value=""></option>
<option value="متل">متل</option>
<option value="یک ستاره">یک ستاره</option>
<option value="دو ستاره">دو ستاره</option>
<option value="سه ستاره">سه ستاره</option>
<option value="سه ستاره تاپ">سه ستاره تاپ</option>
<option value="چهار ستاره">چهار ستاره</option>
<option value="چهار ستاره تاپ">چهار ستاره تاپ</option>
<option value="پنج ستاره">پنج ستاره</option>
<option value="پنج ستاره تاپ">پنج ستاره تاپ</option>
<option value="هفت ستاره">هفت ستاره</option>
<option value="هتل آپارتمان">هتل آپارتمان</option>
</select>
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room1[]">Room 1</label>
<input name="room1[]" id="room1[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room2[]">Room 2</label>
<input name="room2[]" id="room2[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room3[]">Room 3</label>
<input name="room3[]" id="room3[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-10">
<div class="form-group">
<label for="room4[]">Room 4</label>
<input name="room4[]" id="room4[]" value="" class="form-control" placeholder="Price">
</div>
</div>
<div class="col-md-20">
<div class="form-group">
<label for="desc[]">Description</label>
<textarea class="form-control" name="desc[]" id="desc[]" placeholder="Description"></textarea>
</div>
</div>
</div>
</li>
</ul>
<input type="submit" value="submit">
</form>
Here's an example of how you can handle the forms with both JS and PHP.
(if the JS example here doesn't work, see https://jsfiddle.net/n6kzxj4m/)
$(function() {
$(".add").on('click', function(e) {
$($(".hotel").last().clone(true, true)).insertAfter($(".hotel").last());
// reset new items
$(".hotel").last().find(':input:not(select)').not(':button, :submit, :reset, :hidden, :checkbox, :radio').val('');
$(".hotel").last().find('[select]').prop('selectedIndex', 0);
$(".hotel").last().find(':checkbox, :radio').prop('checked', false);
});
$(".remove").on('click', function(e) {
$(this).parents(".hotel").remove();
});
$("form").on('submit', function(e) {
e.preventDefault();
var $form = $(this);
$("#output").html($form.serializeJSON());
});
});
// plugin below only for debug on jsfiddle
/**
* jQuery serializeObject
* #copyright 2014, macek <paulmacek#gmail.com>
* #link https://github.com/macek/jquery-serialize-object
* #license BSD
* #version 2.4.5
*/
!function(e,r){if("function"==typeof define&&define.amd)define(["exports","jquery"],function(e,i){return r(e,i)});else if("undefined"!=typeof exports){var i=require("jquery");r(exports,i)}else r(e,e.jQuery||e.Zepto||e.ender||e.$)}(this,function(e,r){function i(e,i){function n(e,r,i){return e[r]=i,e}function a(e,r){for(var i,a=e.match(t.key);void 0!==(i=a.pop());)if(t.push.test(i)){var o=s(e.replace(/\[\]$/,""));r=n([],o,r)}else t.fixed.test(i)?r=n([],i,r):t.named.test(i)&&(r=n({},i,r));return r}function s(e){return void 0===h[e]&&(h[e]=0),h[e]++}function o(e){switch(r('[name="'+e.name+'"]',i).attr("type")){case"checkbox":return"on"===e.value?!0:e.value;default:return e.value}}function u(r){if(!t.validate.test(r.name))return this;var i=a(r.name,o(r));return c=e.extend(!0,c,i),this}function f(r){if(!e.isArray(r))throw new Error("formSerializer.addPairs expects an Array");for(var i=0,t=r.length;t>i;i++)this.addPair(r[i]);return this}function d(){return c}function l(){return JSON.stringify(d())}var c={},h={};this.addPair=u,this.addPairs=f,this.serialize=d,this.serializeJSON=l}var t={validate:/^[a-z_][a-z0-9_]*(?:\[(?:\d*|[a-z0-9_]+)\])*$/i,key:/[a-z0-9_]+|(?=\[\])/gi,push:/^$/,fixed:/^\d+$/,named:/^[a-z0-9_]+$/i};return i.patterns=t,i.serializeObject=function(){return this.length>1?new Error("jquery-serialize-object can only serialize one form at a time"):new i(r,this).addPairs(this.serializeArray()).serialize()},i.serializeJSON=function(){return this.length>1?new Error("jquery-serialize-object can only serialize one form at a time"):new i(r,this).addPairs(this.serializeArray()).serializeJSON()},"undefined"!=typeof r.fn&&(r.fn.serializeObject=i.serializeObject,r.fn.serializeJSON=i.serializeJSON),e.FormSerializer=i,i});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="#">
<fieldset class="hotel">
<legend>Add a hotel</legend>
<p><label>Hotel: <input type="text" name="hotel[name][]" /></label></p>
<p><label>Rate: <select name="hotel[rate][]"><option>123</option><option>456</option></select></label></p>
<p><input type="button" class="add" value="Add hotel" /> <input type="button" class="remove" value="Remove this hotel" /></p>
</fieldset>
<p><input type="submit" value="Search!" /></p>
</form>
<pre id="output"></pre>
Then, for the PHP handling, you can do:
<?php
if(!empty($_POST)) {
// handle items. $key is the index.
foreach($_POST['hotel']['name'] as $key => $hotel) {
$name = $hotel;
$rate = $_POST['hotel']['rate'][$key];
echo "Name: $name<br>Rate: $rate<hr>";
}
}
NOTE: You may want to check to ensure the number of items in $_POST['hotel']['name'] match the number of items in $_POST['hotel']['rate']. This method may not be ideal, and you may want to assign an ID per hotel row item via JS. But this is a basic approach to your question.

Form validation before Submit

I have the following form that needs to feed into the database but I would like it to be validated before it can be saved into the database :
<form name="add_walkin_patient_form" class="add_walkin_patient_form" id="add_walkin_patient_form" autocomplete="off" >
<div class="form-line">
<div class="control-group">
<label class="control-label">
Patient Name
</label>
<div class="controls">
<input type="text" name="patientname" id="patientname" required="" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">
Patient Phone Number
</label>
<div class="controls">
<input type="text" name="patient_phone" id="patient_phone" required="" value=""/>
</div>
</div>
<div class="control-group">
<label class="control-label">
Department
</label>
<div class="controls">
<select name="department" required="" class="department" id="department">
<option value="">Please select : </option>
<option value="Pharmacy">Pharmacy</option>
<option value="Laboratory">Laboratory</option>
<option value="Nurse">Nurse</option>
</select>
</div>
</div>
</div>
<button name="add_walkin_patient_button" type="submit" id="add_walkin_patient_button" class="btn add_walkin_patient_button btn-info pull-right">
Add Walk In Patient
</button>
</form>
And the submit is done by a jquery script using the following script :
<script type="text/javascript">
$(document).ready(function () {
//delegated submit handlers for the forms inside the table
$('#add_walkin_patient_button').on('click', function (e) {
e.preventDefault();
//read the form data ans submit it to someurl
$.post('<?php echo base_url() ?>index.php/reception/add_walkin', $('#add_walkin_patient_form').serialize(), function () {
//success do something
// $.notify("New Patient Added Succesfully", "success",{ position:"left" });
$(".add_walkin_patient_form").notify(
"New Walkin Patient Added Successfully",
"success",
{position: "center"}
);
setInterval(function () {
var url = "<?php echo base_url() ?>index.php/reception/";
$(location).attr('href', url);
}, 3000);
}).fail(function () {
//error do something
$(".add_walkin_patient_form").notify(
"There was an error please try again later or contact the system support desk for assistance",
"error",
{position: "center"}
);
})
})
});
</script>
How can I put form validation to check if input is empty before submitting it into the script?
I am using javascript to do the validations.
Following is the form code:
<form action="upload.php" method="post" onSubmit="return validateForm()">
<input type="text" id="username">
<input type="text" password="password">
<input type="submit" value='Login' name='login'>
</form>
To perform validation write a javascript function:
<script>
function checkform(){
var uname= document.getElementById("username").value.trim().toUpperCase();
if(uname=== '' || uname=== null) {
alert("Username is blank");
document.getElementById("username").backgroundColor = "#ff6666";
return false;
}else document.getElementById("username").backgroundColor = "white";
var pass= document.getElementById("password").value.trim().toUpperCase();
if(pass=== '' || pass=== null) {
alert("Password is blank");
document.getElementById("password").backgroundColor = "#ff6666";
return false;
}else document.getElementById("password").backgroundColor = "white";
return true;
}
</script>
You are using,
<button name="add_walkin_patient_button" type="submit" id="add_walkin_patient_button" class="btn add_walkin_patient_button btn-info pull-right">
Add Walk In Patient
</button>
Here, submit button is used for submitting a form and will never trigger click event. Because, submit will be triggered first thus causing the click event skip.
$('#add_walkin_patient_button').on('click', function (e) {
This would have worked if you have used normal button instead of submit button
<input type="button">Submit</button>
Now to the problem. There are two solution for it ,
If you use click event, then you should manually trigger submit on correct validation case,
<input type="button" id="add_walkin_patient_button">Submit</button>
//JS :
$("#add_walkin_patient_button").click(function() {
if(valid){
$("#form-id").submit();
}
Another option is to use submit event;which is triggered just after you click submit button. Here you need to either allow form submit or halt it based on your validation criteria,
$("#form-id").submit(function(){
if(invalid){
//Suppress form submit
return false;
}else{
return true;
}
});
P.S
And i would recommend you to use jQuery Validate as suggested by #sherin-mathew
make a javascript validation method (say, validateForm(), with bool return type). add [onsubmit="return validateForm()"] attribute to your form and you are done.
You need to prevent default action.
$('#add_walkin_patient_form').on('submit', function(e) {
e.preventDefault();
//Validate form and submit
});
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<style>
#first{
display: none;
}
</style>
<div class="container"><br>
<div class="col-lg-6 m-auto d-block">
<form action="" method="" onsubmit="return validation()" class="bg-light">
<div class="form-group">
<label for="">Title</label>
<span class="text-danger">*</span>
<!-- <input class="form-control" type="text" > -->
<select name="title" id="title" class="form-control" >
<option value=""class="form-control" >Select</option>
<option value="Mr" class="form-control">Mr</option>
<option value="Mrs" class="form-control">Mrs</option>
</select>
<span id="tit" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<div class="row">
<div class="col">
<label for="firstName">FirstName</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="First name" id="firstName" >
<span id="first" class="text-danger font-weight-bold"> </span>
</div>
<div class="col">
<label for="lastName">LastName</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Last name" id="lastName">
<span id="last" class="text-danger font-weight-bold"> </span>
</div>
</div>
</div>
<div class="form-group">
<label for="email">Your Email</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Email" id="email">
<span id="fillemail" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="contact">Your Contact</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Contact Number" id="contact">
<span id="con" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="password">Your Password</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Password" id="password">
<span id="pass" class="text-danger font-weight-bold"> </span>
</div>
<div class="form-group">
<label for="conPassword">Confirm Password</label>
<span class="text-danger">*</span>
<input type="text" class="form-control" placeholder="Password" id="conPassword">
<span id="conPass" class="text-danger font-weight-bold"> </span>
</div>
<div class="checkbox">
<label><input type="checkbox"> I accept Terms and Conditions</label>
</div>
<div class="checkbox">
<label><input type="checkbox"> I agree to recieve Email Terms and Conditions</label>
</div>
<div class="checkbox">
<label><input type="checkbox"> I agree to recieve SMS Terms and Conditions</label>
</div>
<input type="submit" name="submit" value="SignUp" id="signUp" class="btn btn-success" autocomplete="off">
</form><br><br>
</div>
</div>
<script type="text/javascript">
function validation(){
var title = document.getElementById('title').value;
var firstName = document.getElementById('firstName').value;
var email=document.getElementById('email').value;
var contact=document.getElementById('contact').value;
var password=document.getElementById('password').value;
var conPassword=document.getElementById('conPassword').value;
var signBut=document.getElementById('signUp');
console.log(firstName);
if(title == ""){
document.getElementById("tit").innerHTML =" Please select the title feild first field";
return false;
}
// if(firstName == "" & firstName.length<=3){
// document.getElementById("first").innerHTML =" Please Enter First Name";
// return false;
// document.getElementById("signUp").addEventListener("click", function(event){
// event.preventDefault()
// });
// }
signBut.addEventListener('click',function(e){
if(firstName=="" & firstName<3)
{
document.getElementById("first").innerHTML="Please Enter proper Name";
e.preventDefault();
}
},false);
if(lastName == ""){
document.getElementById("last").innerHTML =" Please Enter Last Name";
return false;
}
else if(email ==""){
document.getElementById("fillemail").innerHTML="Please Enter Email";
}
else if(contact ==""){
document.getElementById("con").innerHTML="Please Enter Your Contact";
}
else if(password ==""){
document.getElementById("pass").innerHTML="Please Enter Your Password";
}
else if(conPassword ==""){
document.getElementById("conPass").innerHTML="Please Confirm Password";
}
}
</script>
</body>
</html>
I think you should use type button
and then eventClick function of jquery

Categories