ajax request of registration bootstrap form doesn't work - php

the register function inside file name signup.php capture values of fields with ajax send them to register.php then display a toast reply */
// js code inside signup.php
<script type="text/javascript">
function register(){
var name=$('#form2').val();
var email=$('#form3').val();
var password=$('#form4').val();
var question=$('#question').val();
var repsec=$('#form5').val();
if((email!="")&&(password!="")&&(name!="")&&(repsec!="")&&(quest!="")) {
$.ajax({
var data = $("#reg").serialize();
url:'register.php',
type:'POST',
data:data,
success: function(data){
if(data=='success'){
toastr.clear(); toastr.success('user: '+name+' registred'); } else {toastr.clear(); toastr.error(email+' already exists') } } }); } }; </script>
<!-- registration form-->
<form id="reg" method="post">
<div class="md-form" style="top: 25px;">
<i class="fa fa-user prefix" style="top: 15px;"></i>
<input type="text" name="name" id="form2" class="form-control">
<label for="form2">Your name</label> </div> <div class="md-form" style="top: 25px;">
<i class="fa fa-envelope prefix" style="top: 14px;right: 500px;"></i>
<input type="email" name="email" id="form3" class="form-control" style="margin-top: 30px;" required> <label for="form3">Your email</label> </div>
<div class="md-form" style="top: 28px;">
<i class="fa fa-lock prefix" style="top: 14px;"></i>
<input type="password" name="password" id="form4" class="form-control" required>
<label for="form4">Your password</label> </div> <i class="fa fa-question-circle" style="top: 14px;margin-top: 40px;font-size:1.6rem;"></i>
<select name="quest" id="question" style="margin-top: -25;margin-left: 38px;width: 497px;">
<option>What is the name of my best childhood friend?</option> <option>What is the best place I have visited?</option> <option>What is the best gift I received?</option>
</select>
<div class="md-form" style="top: 25px;left:40;">
<input type="password" name="repsec" id="form5" class="form-control" style="font-size: 1.4rem;font-weight: bold;color: #000;width: 480px;" required>
<label for="form5">Answer of secret question </label> </div>
<div class="text-xs-center">
<button class="btn btn-indigo" onclick="register()" style="margin-top: 25px;" type="submit">Sign up</button> </div></form>
The problem while submitting form the page reload without ajax reply and without inserting the new user on the database. I included all bootstrap files(css & js) and jquery library correctly, I even coded a login form similar to signup.php in which the ajax request work with toast reply correctly
i tried to add preventDefault, changing type of submit to input type=button then verifying PHP code,database parameters but I have never find solution for 3 weeks
//register.php code

Instead of using onclick="register()" , try using javascript to submit the form instead.
document.getElementById("reg").onsubmit = function() {register()};
And remove the onclick="register()" event from the submit button.
I usually do this with jquery, but if you don't use that, I think the above will work. I have not tested it.
Here is a way with Jquery:
$(function() {
// register user
$("button.btn-indigo").click(function(){
register();
});

Related

Login page using php,ajax,jquery

Hello i am trying to build login page.
There are two pages login.php and login2.php
login.php has a form which accepts email and password from the user which are sent to login2.php using $.post()
login2.php checks email and password in DB and a message is sent to login.php which is supposed to be displayed in having id="msg"
Problem is that message is printed but after that the page is refreshed and the message is gone
login.php
<form>
<input type="radio" name="role" value="tbl_staff_details" checked>Institute/Branch
<input type="radio" name="role" value="tbl_student_details">Student/Parent
</br></br>
<div id="msg" style="color: red"></div>
<div class="form-group has-feedback">
<input type="email" class="form-control" placeholder="Email" id="mail">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" id="pwd">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-8">
<div class="checkbox icheck">
<label>
<input type="checkbox"> Remember Me
</label>
</div>
</div>
<!-- /.col -->
<div class="col-xs-4">
<button type="submit" class="btn btn-primary btn-block btn-flat" id="signin">Sign In</button>
</div>
<!-- /.col -->
</div>
</form>
<script>
$(function(){
$("#signin").click(function(){
var mail = $("#mail").val();
var pwd = $("#pwd").val();
var role = $("input[name='role']:checked").val();
$.post("login2.php",
{
mail: mail,
pwd: pwd,
role: role
},
function(data,status){
$("#msg").text(data);
});
});
});
</script>
login2.php
<?php
$email=$_POST['mail'];
$pwd=$_POST['pwd'];
$table=$_POST['role'];
include_once 'conf.php';
if ($table=="tbl_staff_details") {
$q="select * from ".$table." where email=".$email." and pwd=".$pwd;
}
else{
$q="select * from ".$table." where stud_email='".$email."' and stud_pwd='".$pwd."' or stud_email='".$email."' and parent_pwd='".$pwd."'";
}
$r=mysqli_query($con,$q);
$ro=mysqli_num_rows($r);
if ($ro>0) {
echo "Success";
//header('location:test.php');
}
else{
echo "Email or password is wrong";
}
?>
Make sure to take into account what the comments are saying about vulnerabilities like plain text passwords and sql injections. But it looks like the issue you are having is related to the fact that the button you click to submit the form is type='submit'
Because of this when you click the button the browser will try to make a new request to the page specified in your form or if not specified, the page you are currently on to submit your request.
There are two ways to get around this:
Change the button to type='button' since you are already handling the on click event with jquery you don't need to submit
use preventDefault(); to stop the submit event from happening

dont refresh the page when you submit the form

hii guys im new to web programing and im creating a website
in this website i want to add a contact us form in the footer of the page like this
<form action="footer_contactus1.php" method="post">
<div class="row">
<div class="form-grope col-lg-4">
<label><span class="glyphicon glyphicon-user"></span>Name</label><br>
<input name="cuname" type="text" class="form-cotrol">
</div>
<div class="form-grope col-lg-4">
<label><samp class="glyphicon glyphicon-envelope"></samp>Email</label><br>
<input name="cuemail" type="email" class="form-cotrol">
</div>
<div class="form-grope col-lg-4">
<label><i class="glyphicon glyphicon-earphone"></i>Phone Number</label><br>
<input name="cutele" type="tel" class="form-cotrol">
</div>
<div class="form-grope col-lg-12">
<br>
<label><span class="glyphicon glyphicon-paste"></span>Message</label><br>
<textarea name="cumessage" class="form-cotrol" rows="6" style="width: 100%;" ></textarea>
</div>
<div class="form-grope col-lg-12">
<br>
<input type="hidden" name="save" value="contact">
<button type="submit" class="btn btn-info">Submit</button>
</div>
</div>
</form>
and when i click the submit button i want the php file to get executed so the inputs got inserted into the database
the php file
<?php
$pdo = new PDO('mysql:host=localhost;dbname=mywsite_db', 'root', '');
$req = $pdo->prepare('INSERT INTO message (id_message,nom,email,tele,message)
VALUES(null,?,?,?,?)');
$req->execute(array($_POST['cuname'],$_POST['cuemail'],$_POST['cutele'],$_POST['cumessage']));
header('Location: HomePage.php');
?>
i wanted this form to get submited without refreshing the page by ajax
i tried different tutorials and nothing worked can you plzz gives me the correct ajax script for my form so i can submit it to the php file and insert the data on the database then a message (alert) pop up telling me that the data has been inderted without refreshing the page plzz
<form action="footer_contactus1.php" method="post" id="myForm1">
...
</form>
<script type="text/javascript">
var frm = $('#myForm1');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
alert('The data has been inserted');
}
});
ev.preventDefault();
});
</script>

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>

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

jquery append() function not working

I am creating my own custom chat bar all the related coding i have done, database and all the php functions working fine but when after submit the chat input message i am trying to append the input box data with jquery append function its not working at all.
html:
<div class="chat-bar-wrapper">
<div class="chat-bar-head">
<div class="chat-bar-icons-top">
<i class="fa fa-minus"></i>
</div>
<div class="chat-bar-title">
<p>Chat Online</p>
</div>
</div>
<div class="chat-bar-form">
<div class="chat-bar-text-display" id="messages_output"></div>
<form class="message-box" id="chat-form">
<div class="chat-bar-text-inputs">
<div class="chat-bar-text-input">
<input type="text" class="form-control" name="messages_input" placeholder="Enter your text here">
</div>
<div class="chat-bar-text-enter">
<input type="submit" class="btn btn-warning form-control" value="#">
</div>
</div>
</form>
</div>
</div>
js:
$(function(){
$("#messages_output").load('ChatMsgLoad.php');
$("#chat-form").submit(function(){
$.post('chatMsgPost.php', $('#chat-form').serialize(), function(data){
$('#messages_output').append(data);
});
return false;
});
});
Try this appendTo() instead of append().
$( data ).appendTo( "#messages_output");
And check in the console whether data variable contains something.
Read more here appendTo() in jQuery

Categories