Javascript function undefined, but IT IS - javascript

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>

Related

Multiple fields not validated inside modal that are dynamically generated

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>

Pass id to form using ajax in laravel

I try to pass id to form in modal, but i got error The POST method is not supported for this route. Supported methods: GET, HEAD. Although I use it.
this is a web route:
Route::post('bill/{id}', 'MemberController#addBill')->name('bill');
this is the view :
<button type="button" data-toggle="modal" data-target="#message" class="btn btn-info btn-lg" data-id="{{ $r->id }}" ></button>
this is a modal
<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">اثبات الدفع</h4>
</div>
<div class="modal-body">
<p>من فضلك قم بادخال صوره التحويل البنكى</p>
<form action="" method="post" id="upload_form" enctype="multipart/form-data">
#csrf
<div class="form-group">
<input type="file" name="select_file" id="select_file">
</div>
<div class="modal-footer">
<button type="submit" name="upload" id="upload" class="btn btn-primary" value="Upload">jj</button>
</div>
</form>
</div>
</div>
</div>
</div>
this is a ajax request :
<script type="text/javascript">
$('#upload').click(function(e){
e.preventDefault();
var button = $(event.relatedTarget);
var id = button.data('id');
var formData = new FormData($('upload_form')[0]);
$.ajax({
type: 'POST',
url : '/member/bill/'.id,
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function(d){
console.log(d.message);
}
});
</script>
please help me!
01. check your MemberController, addBill() method
public function addBill(Request $request) {
// your code here...
}

jquery redirect on button click

I'm trying to redirect on button click based on visitor location and I have modal with two windows. As well as using freegeoip.net:
I'm using this with Wordpress: script correctly hooked to wordpress and running but redirect doesnt work.
I'd equally want this modal to appear only once per visit and across all navigations through the site not upon every page reload. Thanks in advance.
Below is the jQuery:
jQuery(document).ready(function(){
jQuery("#myModal").modal('show');
jQuery.ajax({
url: 'https://freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(location) {
// If the visitor is browsing from Canada.
if (location.country_code === 'CA') {
jQuery('#subscriber-ca').on('click', function(){
window.location.replace('http://www.google.com');
});
jQuery('#subscriber-us').on('click', function(){
// Redirect visitor to the USA.
window.location.replace('http://www.facebook.com');
});
} else if(location.country_code === 'US') {
jQuery('#subscriber-ca').on('click', function(){
window.location.replace('http://www.google.com');
});
jQuery('#subscriber-us').on('click', function(){
// Redirect visitor to the USA.
window.location.replace('http://www.facebook.com');
});
}
}
});
});
this is the modal:
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Subscribe our Newsletter</h4>
</div>
<div class="modal-body">
<p>Subscribe to our mailing list to get the latest updates straight in your inbox.</p>
<form>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email Address">
</div>
<button id="subscribe-us" type="submit" class="btn btn-primary pull-left">US Subscriber</button>
<button id="subscribe-ca" type="submit" class="btn btn-primary pull-right">Canada Subscriber</button>
</form>
</div>
</div>
</div>
</div>
Try this code
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Subscribe our Newsletter</h4>
</div>
<div class="modal-body">
<p>Subscribe to our mailing list to get the latest updates straight in your inbox.</p>
<form>
<div class="form-group">
<input type="text" class="form-control" placeholder="Name">
</div>
<div class="form-group">
<input type="email" class="form-control" placeholder="Email Address">
</div>
<button id="ussubscribe" type="button" class="btn btn-primary pull-left">US Subscriber</button>
<button id="casubscribe" type="button" class="btn btn-primary pull-right">Canada Subscriber</button>
</form>
</div>
</div>
</div>
</div>
<script>
var locationstatus = false;
var userlocation = '';
jQuery(document).ready(function(){
jQuery.ajax({
url: 'https://freegeoip.net/json/',
type: 'POST',
dataType: 'jsonp',
success: function(locationresponse) {
userlocation = locationresponse.country_code;
locationstatus = true;
console.log(userlocation);
}
});
});
$('#ussubscribe').on('click', function(){
alert();
console.log(userlocation);
if (locationstatus) {
if(locationstatus=='CA'){
window.location.replace('http://www.google.com');
}
}
});
$('#casubscribe').on('click', function(){
console.log(userlocation);
if (locationstatus) {
if(locationstatus=='US'){
window.location.replace('http://www.facebook.com');
}
}
});
</script>
</body>
</html>
US Subscriber
change type="submit" to type="button" //also make sure
jQuery('#subscriber-us').on('click', function(){ //check the spelling which is subscribe-us
and add onclick events outside the ajax call
inside if else clause only hide/show modal and buttons
Replace your code:
<button id="subscribe-us" type="submit" class="btn btn-primary pull left">US Subscriber</button>
<button id="subscribe-ca" type="submit" class="btn btn-primary pull-right">Canada Subscriber</button>
With:
<button id="subscriber-us" type="button" class="btn btn-primary pull left">US Subscriber</button>
<button id="subscriber-ca" type="button" class="btn btn-primary pull-right">Canada Subscriber</button>
And Bind click events outside the ajax if buttons are not dynamically created upon ajax request.
To check whether this is the first visit by the user, you can store value in session storage:
window.sessionStorage.setItem("first_visit", "Y");
While loading check for the session storage. If it is not present then open modal dialog.
Hope it helps.

How to send form data including a file to ajax via onclick() function?

My Modal has a form:
<div class="modal fade bs-example-modal-lg" id="myMODALTWO" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" id="form-content">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myMODALTWOLabel"></h4>
</div>
<div class="modal-body">
<form role="form" method="POST" action="" id="stuff">
<div class="col-md-12">
<div class="box box-info">
<div class="box-header">
<h3 class="box-title">Update History</h3>
<input type="hidden" class="form-control" id="IDu" disabled="">
</div>
<!-- /.box-header -->
<div class="box-body table-responsive no-padding" id="output">
<table class="table table-bordered table-hover" id="updatetable" >
</table>
</div>
<!-- /.box-body -->
</div>
<div class="box box-primary">
<div class="box-header">
<h3 class="box-title">Insert your update here...</h3>
</div>
<div class="box-body">
<!-- <label>Update Content</label> -->
<textarea class="form-control" rows="3" placeholder="Enter Update..." id="updatecontent"></textarea>
<input class="form-control" type="text" placeholder="Name" id="updateuser">
<label><input type="checkbox" class="flat-red" id="closed">To be Closed</label>
<div class="form-group">
<label for="exampleInputFile">Evidence Upload</label>
<input type="file" id="exampleInputFile">
<p class="help-block">Please upload evidence here</p>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" onclick="update()" >Update</button>
</div>
</div>
</div>
</div>
With this, I would like to submit some data to the ajax function via the onlick function (update()). My problem is I m not sure on how to get the File submitted to the ajax function below. The data functions are correctly submitted.
function update()
{
setTimeout(function(){$('#myMODALTWO').modal('hide')}, 3)
var updatecontent = document.getElementById("updatecontent").value;
var updateuser = document.getElementById("updateuser").value;
var IDU = document.getElementById("IDu").value;
var uploaded = document.getElementById("exampleInputFile");
alert(uploaded);
if(document.getElementById('closed').checked)
{
var status="CLOSED";
} else
{
var status ="OPEN";
}
var dataStringro = 'id=' + IDU + '&updatecontent=' + updatecontent + '&updateuser=' + updateuser + '&status=' + status;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "insertupdate.php",
data: dataStringro,
cache: false,
success: function(html)
{
$('html').scrollTop(0);
setTimeout(function(){$('#submitting').modal('hide')}, 3)
$('#submitting').show();
$("#submitting").fadeTo(3000, 500).slideUp(500, function()
{
$("#submitting").alert('close');
});
/* setTimeout(function(){$('#exampleModal').modal('hide')}, 6) */
$('#successmodel').delay(3200).fadeIn(500);
$('#successmodel').delay(3000).fadeOut(500);
/* $("#successmodel").fadeTo(3000, 500).slideUp(500, function()
{
$("#successmodel").alert('close');
});
*/
setTimeout(function(){location.reload();}, 7150);
/* setTimeout(function(){$('#exampleModal').modal('hide')}, 3)
$('#successmodel').show();
$("#successmodel").fadeTo(3000, 500).slideUp(500, function()
{
$("#successmodel").alert('close');
});
setTimeout(function(){location.reload();}, 4000); */
},
error: function (html)
{
$('html').scrollTop(0);
setTimeout(function(){$('#submitting').modal('hide')}, 3)
$('#submitting').show();
$("#submitting").fadeTo(3000, 500).slideUp(500, function()
{
$("#submitting").alert('close');
});
$('#verybadmodel').delay(3200).fadeIn(500);
$('#verybadmodel').delay(3000).fadeOut(500);
}
/* var dataTable = $('#example1').dataTable();
var oSettings = dataTable.fnSettings();
dataTable.fnClearTable(this);
for (var i=0; i<json.aaData.length; i++)
{
dataTable.oApi._fnAddData(oSettings, json.aaData[i]);
}
oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
dataTable.fnDraw(); */
});
return false;
}
You can use form serialize function.
$.ajax({
type: "POST",
url: "insertupdate.php",
data: $('#stuff').serialize(),
cache: false,
Try the below link with JQuery.
https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax

onclick returns function is not defined

I've a Bootstrap modal for changing a user's password. The problem, however, is that no matter what I try I cannot get the event to fire, be it via onclick or by attaching the button to an event using .on. It simply will not recognise it.
I've tried putting the <script> tags above the modal, below the modal, and even inside the modal, only to always have onclick return Uncaught ReferenceError: updatePassword is not defined. I then removed the onclick, assigned an ID to the submit button, and tried $('#update-password').on('click', function() { ... }); but this wasn't recognised at all.
The culprit in all of this is almost definitely the Bootstrap modal, and I'm guessing it's got something to do with how the browser handles it upon page load.
--
Modal
<!-- Modal -->
<div class="modal fade" id="changePasswordModal" tabindex="-1" role="dialog" aria-labelledby="changePassModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title" id="changePassModalLabel">Change Password</h4>
</div>
<div class="modal-body">
<div class="col-md-12">
<div class="alert alert-password" style="display: none;">
<p></p>
</div>
</div>
<form role="form" action="#" method="post">
<div class="form-group">
<label for="password-current">Current Password<span>*</span></label>
<input type="password" class="form-control" id="password-current" name="pass-curr" placeholder="Current password...">
</div>
<hr>
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label for="password-new">New Password<span>*</span></label>
<input type="password" class="form-control" id="password-new" name="pass-new" placeholder="New password...">
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="password-new-conf">Confirm New Password<span>*</span></label>
<input type="password" class="form-control" id="password-new-conf" name="pass-new-c" placeholder="Confirm new password...">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary" onclick="updatePassword()">Update Password</button>
</div>
</div>
</div>
</div>
Script
<script>
function updatePassword(){
console.log('foo');
/*$.ajax({
url: url+"ajax/update_password",
data: {pass-curr : pass-curr, pass-new : pass-new, pass-new-c : pass-new-c},
async: false,
success: function(data) {
},
error: function(data) {
$('#alert-password').removeClass('alert-success').addClass('alert-danger').html('<p><strong>Sorry, an error occurred!</strong></p><p>'+data.additional+'</p>').slideDown(200, function() {
$('#alert-password').delay(4000).slideUp(200);
});
}
})*/
};
</script>
My apologies if this has been asked before. The only questions I could seem to find were those asking how to launch a modal through onclick.
The problem is that your event is not getting binded with button
Please find the JSFIDDLE here
In your HTML - do the following in the script tag
<head>
<script>
function updatePassword(){
console.log('updatePassword');
}
$(document).ready(function(){
// $('.btn-primary').on('click',function(){ - This too works
// console.log('foo');
//});
$('.btn-primary').on('click',updatePassword);
});
</script>
</head>

Categories

Resources