I want to insert data in a database with Ajax but I am facing error:
Uncaught ReferenceError: insertData is not defined at HTMLInputElement.onclick (Modal.php:105)
Screen shot of error page.
In Modal.php file contain my html and js.
My Modal.php file
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<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>
<style>
.modal-header, h4, .close {
background-color: #5cb85c;
color:white !important;
text-align: center;
font-size: 30px;
}
.modal-footer {
background-color: #f9f9f9;
}
</style>
<script>
$(document).ready(function(){
$("#myBtn").click(function(){
$("#myModal").modal();
function insertData(){
//$("#signup").click(function(){
var Fname = $("#Fname").val(); debugger;
var Lname = $("#Lname").val();
var age = $("#age").val();
var email = $("#email").val();
var password = $("#password").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "Insert.php",
data: {Fname:Fname,Lname:Lname,age:age,email:email,password:password},
dataType: "JSON",
success: function(data) {
alert(data.message);
},
error:function(err){
console.log(err.responseText);
}
});
//});
}
});
});
</script>
</head>
<body>
<div class="container">
<h2>Modal Sign Up Example</h2>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-default btn-lg" id="myBtn">Sign Up</button>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header" style="padding:35px 50px;">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4><span class="glyphicon glyphicon-lock"></span> Sign Up</h4>
</div>
<div class="modal-body" style="padding:40px 50px;">
<form role="form" action="">
<div class="form-group">
<label for="Fname"><span class="glyphicon glyphicon-user"></span> First Name</label>
<input type="text" class="form-control" id="Fname" placeholder="First Name">
</div>
<div class="form-group">
<label for="Lname"><span class="glyphicon glyphicon-user"></span> Last Name</label>
<input type="text" class="form-control" id="Lname" placeholder="Last Name">
</div>
<div class="form-group">
<label for="age"><span class="glyphicon glyphicon-user"></span> Age</label>
<input type="number" class="form-control" id="age" placeholder="Enter Age">
</div>
<div class="form-group">
<label for="email"><span class="glyphicon glyphicon-eye-open"> </span> Email</label>
<input type="email" class="form-control" id="email" placeholder="Enter Email">
</div>
<div class="form-group">
<label for="psw"><span class="glyphicon glyphicon-eye-open"> </span> Password</label>
<input type="text" class="form-control" id="password" placeholder="Enter password">
</div>
<!--<div class="checkbox">
<label><input type="checkbox" value="" checked>Remember me</label>
</div>-->
<input type="button" id="signup" onclick="insertData()" class="btn btn-success btn-block" value="Sign Up"/>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger btn-default pull-left" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cancel</button>
<p>Log In</p>
<!--<p>Password?</p>-->
</div>
</div>
</div>
</div>
</div>
</body>
</html>
This is my Insert.php file. In Insert.php file I have coded all PHP code related to inserting data in a database.
<?php
include("connection.php");
//if(isset($_POST['submit']))
// {
$Fname=$_POST["Fname"];
$Lname=$_POST["Lname"];
$Age=$_POST["age"];
$EmailId=$_POST["email"];
$Password=$_POST["password"];
$Insert = "INSERT INTO simpleform (First_Name, Last_Name, Age, Email_Id, Password) VALUES ('".$Fname."', ".$Lname."', '".$Age."', '".$EmailId."', '".$Password."')";
$Query=mysqli_query($con, $Insert);
//print_r($Insert);
if(!$Query)
{
echo mysqli_error();
$successArr = array('status'=>'false','message'=>'Data not inserted');
$successJson = json_encode($successArr);
}
else
{
$successArr = array('status'=>'true','message'=>'Data inserted successfully');
$successJson = json_encode($successArr);
//echo "Successfully Inserted";
}
echo $successJson;
// }
header('Location: http://localhost/javascript/Modal.php');
?>
Put your insertData() javascript function out of the click event of id #myBtn as well as document.ready function. Cause its is inside the click event, code isn't able to find your function insertData();
Your script should be like this -
function insertData(){
//$("#signup").click(function(){
var Fname = $("#Fname").val(); debugger;
var Lname = $("#Lname").val();
var age = $("#age").val();
var email = $("#email").val();
var password = $("#password").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "Insert.php",
data: {Fname:Fname,Lname:Lname,age:age,email:email,password:password},
dataType: "JSON",
success: function(data) {
alert(data.message);
},
error:function(err){
console.log(err.responseText);
}
});
//});
}
$(document).ready(function(){
$("#myBtn").click(function(){
$("#myModal").modal();
});
});
You haven't closed this event call maybe that's why it is showing the error. Try closing it after the modal open command instead at the bottom after ajax call
$("#myBtn").click(function(){
$("#myModal").modal();
}
I hope this will help
Related
I'm validating fields inside modal popup,for single field it is working but if more than one field are appended at a time then validation does not takes place on those fields. Here we can see we add new field by adding add field button but those newly field did'nt get validated.
$(function() {
$("#newModalForm").validate();
$('.form-control').each(function() {
required($(this))
});
$(document).on('click', '#add_field', function(e) {
$('#dynamic_div').html("<div class=form-group><label class=control-label col-md-3 for=email>Dynamic field 1:</label> <inputname=sfs type=text class=form-control></div> <div class=form-group><label class=control-label col-md-3 for=email>Dynamic field 2:</label><input name=ssf type=text class=form-control></div>");
required($(this))
});
function required(el) {
el.rules("add", {
required: true,
messages: {
required: "This field is required",
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#addMyModal">Open Modal</button>
<div class="modal fade" id="addMyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Stuff</h4>
</div>
<div class="modal-body">
<form role="form" id="newModalForm">
<div class="form-group">
<label class="control-label col-md-3" for="email">A p Name:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="pName" name="pName" placeholder="Enter a p name"/>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3" for="email">Action:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="action" name="action" placeholder="Enter and action">
</div>
</div>
<div class="col-md-9" id="dynamic_div">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="btnSaveIt">Save</button>
<button type="button" id="add_field" class="btn btn-default">Add Field</button>
<button type="button" class="btn btn-default" id="btnCloseIt" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
You need call .each() on the dynamically added elements as well.
Dynamically added elements are not in DOM onload so ideally you need to do wrap .each() in a function when you add more fields to your modal just call that function again to check for empty inputs
To handle submit and store data we can .submit on your modal form. Get all the data via .serialize method and send all your form data to the backend file via ajax request.
Run Snippet below to see it working.
$(function() {
//Validate Data
var validate = $("#newModalForm").validate()
checkInput()
//Add dynamic inputs
$(document).on('click', '#add_field', function(e) {
$('#dynamic_div').html("<div class=form-group><label class=control-label col-md-3 for=email>Dynamic field 1:</label> <input name=sfs type=text class=form-control></div> <div class=form-group><label class=control-label col-md-3 for=email>Dynamic field 2:</label><input name=ssf type=text class=form-control></div>");
//Required Dynamic Input
checkInput()
});
//Validate all inputs
function checkInput() {
$('.form-control').each(function() {
required($(this))
});
}
//Required field message
function required(el) {
el.rules("add", {
required: true,
messages: {
required: "This field is required",
}
});
}
//Submit form modal
$('#newModalForm').on('submit', function(e) {
//Prevent default submit behaviour
e.preventDefault()
//Store all the form modal form data
var data = $(this).serialize()
//Check all fieild have data
if (validate.errorList.length == 0) {
alert('All fields have value - Form will submit now')
//Request to backend
$.ajax({
url: 'your_url',
type: 'POST',
data: data,
success: function(response) {
//do something on success
},
error: function(xhr) {
//Handle errors
}
});
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.14.0/jquery.validate.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#addMyModal">Open Modal</button>
<div class="modal fade" id="addMyModal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add Stuff</h4>
</div>
<div class="modal-body">
<form role="form" method="post" id="newModalForm">
<div class="form-group">
<label class="control-label col-md-3" for="email">A p Name:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="pName" name="pName" placeholder="Enter a p name" />
</div>
</div>
<div class="form-group">
<label class="control-label col-md-3" for="email">Action:</label>
<div class="col-md-9">
<input type="text" class="form-control" id="action" name="action" placeholder="Enter and action">
</div>
</div>
<div class="col-md-9" id="dynamic_div">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" id="btnSaveIt">Save</button>
<button type="button" id="add_field" class="btn btn-default">Add Field</button>
<button type="button" class="btn btn-default" id="btnCloseIt" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
I am trying to call the code behind method RegisterUser() on the click event of an html button control, which is present inside a bootstrap modal. And for that I used jquery (the code snippet is given below). But I am not able to call the method every time the error callback method is getting invoked.
This is the Bootstrap Modal Code
<div id="loginModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4>Login</h4>
</div>
<div class="modal-body">
<form class="form-inline" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>
<div class="form-group">
<label class="sr-only" for="email">Email</label>
<input type="text" class="form-control input-sm" placeholder="Email" id="email" name="email">
</div>
<div class="form-group">
<label class="sr-only" for="password">Password</label>
<input type="password" class="form-control input-sm" placeholder="Password" id="password" name="password">
</div>
<div class="checkbox">
<label>
<input type="checkbox">
Remember me
</label>
</div>
</form>
</div>
<div class="modal-body" style="padding-top: 0;">
<button type="submit" id="btnSubmit" class="btn btn-info btn-xs">Sign in</button>
<button type="button" class="btn btn-default btn-xs" data-dismiss="modal">Cancel</button>
Forgot Your Password?
</div>
<!--
<div class="modal-footer">
<div style="padding:10px"></div>
</div>
-->
</div>
</div>
</div>
this is the ajax code that I am using to call the back end method
<head runat="server">
<title>Master Page</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet" type="text/css">
<link href="https://fonts.googleapis.com/css?family=Montserrat" rel="stylesheet" type="text/css">
<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>
<script type="text/javascript">
$(document).ready(function () {
$('#btnSubmit').click(function () {
var mail = $('#email').val();
var pass = $('#password').val();
$.ajax({
url: 'Site.Master/RegisterUser',
method: 'post',
contentType: 'application/jason',
data: '{email:' + mail + 'password:' + pass+ '}',
dataType: 'jason',
success: function (data) {
aler(data.d);
},
error: function (error) {
alert(error);
}
});
});
});
</script>
This is the back end method
public partial class Site1 : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
}
[System.Web.Services.WebMethod]
public static string RegisterUser(string email, string password)
{
string result = "Congratulations!!! your account has been created.";
if (email.Length == 0)//Zero length check
{
result = "Email Address cannot be blank";
}
else if (password.Length == 0)
{
result = "Password cannot be blank";
}
return result; ;
}
}
I validated my form Using AJAX
Here is my form
<p class="login-box-msg">
<?php
echo "<span id='error'>Sign in to start your session</span>";
?>
</p>
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Employee ID" name="empid">
<span class="glyphicon glyphicon-envelope form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="password" class="form-control" placeholder="Password" name="pw">
<span class="glyphicon glyphicon-lock form-control-feedback"></span>
</div>
<div class="row">
<div class="col-xs-4 col-xs-offset-8">
<button type="button" class="btn btn-primary btn-block btn-flat" id="submit">Sign In</button>
</div>
<!-- /.col -->
</div>
</div>
<!-- /.login-box-body -->
<form>
Then I validated this using my ajax code
$("#submit").click(function(){
var form = $("form").serialize();
$.ajax({
url:'verify',
data: form,
dataType:'json',
type:'post',
success: function(e)
{
console.log(e.length);
if(e.length < 1)
{
$("#error").text("Invalid Login Credentials!");
$("#error").css("color","red");
setTimeout(function(){
$("#error").text("Sign in to start your session!");
$("#error").css("color","black");
},3000);
}
else
{
"What shoud I do"
// I tried $("form").submit() but it just repeat
//$("#submit").click(function())
}
}
});
On else bracket, I want to redirect to Controller on codeigniter called setCredentials() wherein it would set the credentials needed and redirect me to another page when the validation is completed (without error).
In else part enter the below code with the url you want to redirect to:
window.location = "<?php echo 'your/url'; ?>";
On button click, i want to post the contents of the email text box. When i click the login button nothing happens.
My File dir:
Model/ <-- configuration.php is inside Model dir.
View/
Controller/
index.php <-- calls the header, body, and footer php classes that are in the view dir
<!-- Modal body -->
<div class="modal-body" style="padding:40px 50px;">
<form>
<div class="form-group">
<label for="usrname"><span class="glyphicon glyphicon-user"></span> Username</label>
<input type="text" class="form-control" name="email" id="email" placeholder="Enter email">
</div>
<div class="form-group">
<label for="psw"><span class="glyphicon glyphicon-eye-open"></span> Password</label>
<input type="text" class="form-control" id="password" placeholder="Enter password">
</div>
<div class="checkbox">
<label><input type="checkbox" value="" checked>Remember me</label>
</div>
<button type="button" name="loginButton" id="loginButton" name="loginButton" class="btn btn-success btn-block">Login</button>
</form>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<p>Not a member? Sign Up</p>
</div>
</div>
</div>
</div>
</div>
<script>
$(document).ready(function() {
$("#loginButton").click(function() {
$.ajax({
type: "POST",
url: "Model/configuration.php?action=login",
data: "email=" + $("#email").val(),
success: function (result) {
alert("result");
}
})
})
})
</script>
PHP file
<?php
if($_GET['action'] == "login") {
print_r($_POST);
}
?>
The problem seems to be that your if condition had an extra parentheses.
Try this:
<?php
if($_GET['action'] == "login") {
print_r($_POST);
}
?>
$("#loginButton").click(function() {
$.ajax({
type: "POST",
url: "Model/configuration.php?action=login",
data: {email:$("#email").val()},
success: function (result) {
alert("result");
}
})
})
You should serialize your form and pass to data.
data: $("#FormId").serialize()
See also https://api.jquery.com/serialize/
I'm doing some testing with AJAX form submissions and I keep getting ReferenceError: submit_ajax is not defined from the code below. However, you can see that it IS defined.
<script type="javascript">
function submit_ajax(){
data = {'email':$('#email2').val(),'password':$('#pwd2').val()}
$.ajax({
url: 'ajax_testing.php',
data: data,
success: function() {
//AJAX success
$('#success_fail').html('success!');
window.setTimeout(function() { $('#success_fail').hide(); }, 3000);
$('#myModal2').hide();
},
error: function() {
//Ajax failure
$('#success_fail').html('failed!');
window.setTimeout(function() { $('#success_fail').hide(); }, 3000);
$('#myModal2').hide();
}
});
}
</script>
<div>
<div id="success_fail"></div>
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-info btn-lg" id="button_for_modal2" data-toggle="modal" data-target="#myModal2">Form Submitted via AJAX and No Parent Refresh</button>
<!-- Modal -->
<div class="modal fade" id="myModal2" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Title of Form</h4>
</div>
<div class="modal-body">
<h2>Vertical (basic) form</h2>
<!--<form action="<?PHP echo $_SERVER['PHP_SELF']; ?>" method="post">*******************************AJAX*********************************-->
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email2" placeholder="Enter email (ajax)" name="email2">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd2" placeholder="Enter password (ajax)" name="pwd2">
</div>
<button onclick="submit_ajax()" class="btn btn-default">Submit</button>
<!--</form>-->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
I've tried running the function directly in the console and I get the same thing.
Any idea about what's going wrong here?
Instead of using <script type="javascript"> use <script type="text/javascript"> which is valid type for JS code.
change your script tag, either dont include type or set it as type="text/javascript"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
function submit_ajax(){
alert('submit_ajax working')
data = {'email':$('#email2').val(),'password':$('#pwd2').val()}
$.ajax({
url: 'ajax_testing.php',
data: data,
success: function() {
//AJAX success
$('#success_fail').html('success!');
window.setTimeout(function() { $('#success_fail').hide(); }, 3000);
$('#myModal2').hide();
},
error: function() {
//Ajax failure
$('#success_fail').html('failed!');
window.setTimeout(function() { $('#success_fail').hide(); }, 3000);
$('#myModal2').hide();
}
});
}
</script>
<button onclick="submit_ajax()" class="btn btn-default">Submit</button>