Sending a form to a php script using jQuery dialog - javascript

I am attempting to send an email using a php script which is sent through the jquery dialog box when the user clicks the 'submit' button but I cant get this script to work. I have the dialog box in html:
<div id="join-dialog" class="join-dialog">
<p>Please fill in your details to join the mailing list</p>
<table>
<form action="" method="post">
<tr><td><label for="name">NAME</label></td><td><input id='form-name' type="text" name="name"/></td></tr>
<tr><td><label for="email">EMAIL</label></td><td><input id='form-email' type="email" name="email"/></td></tr>
<tr><td><label for="email">POSTCODE</label></td><td><input id='form-post' type="text" name="postcode"/></td></tr>
</form>
</table>
</div>
and I have this jQuery:
$(function() {
function addUser(){
var name = document.getElementById("#form-name");
var email = document.getElementById('#form-email');
var post = document.getElementById('#form-post');
if(name !==0 || email!==0 || post!==0){
$.ajax({
url: 'sendemail.php',
type: 'POST',
data: ('name, email, post'),
success: function(){
document.getElementById('#join-dialog').innerHTML("<h2>Thank you for joining the mailing list</h2>");
}
});
}else{
document.getElementById('#join-dialog').append = "There was an error with your form details";
}
};
$( ".join-dialog" ).dialog({
dialogClass: "no-close",
autoOpen: false,
show: {
effect: "fade",
duration: 300
},
hide: {
effect: "fade",
duration: 300
},
modal: true,
buttons:{
'SUBMIT': addUser,
'CLOSE': function(){
$(this).dialog('close');
}
}
});
$( "#open1" ).click(function() {
$( ".join-dialog" ).dialog( "open" );
});
});
which adds the dialog buttons and executes code in order to fire off an email using the sendemail.php which is here:
<?php
$name= $_POST['name'];
$postcode = $_POST['post'];
$email = $_POST['email'];
$email_to = 'xyz123#hotmail.com';
$email_subject = 'New mailing list subscriber';
$email_message = "Your new subscriber is: ".$name."\n"."Postcode: ".$postcode."\n"."Email: ".$email."\n";
mail($email_to, $email_subject, $email_message);
echo '<p style=\'font-size: 16px;\'>You have been added to Kaylee\'s mailing list!</p>';
echo '<br />';
echo '<br />';
?>
there seems to be a problem and I can't figure out what it is, if anyone can point me in the right direction that would be great thanks.

Your html and css looks good, but the js has some errors, it might still have some:
function addUser() {
var name = $("#form-name").val(),
email = $('#form-email').val(),
post = $('#form-post').val();
if (name !== 0 || email !==0 || post !== 0) {
$.ajax({
url: 'sendemail.php',
type: 'post',
data: {
'name': name,
'email': email,
'post': post
},
success: function() {
$('#join-dialog').html("<h2>Thank you for joining the mailing list</h2>");
}
});
} else {
$('#join-dialog').append("There was an error with your form details");
}
}
$( ".join-dialog" ).dialog({
'dialogClass': "no-close",
'autoOpen': false,
'show': {
'effect': "fade",
'duration': 300
},
'hide': {
'effect': "fade",
'duration': 300
},
'modal': true,
'buttons': {
'submit': addUser,
'close': function() {
$(this).dialog('close');
}
}
});
$( "#open1" ).click(function() {
$( ".join-dialog" ).dialog("open");
});

Related

How to prevent page from refreshing after ajax submit

I just started using Ajax function in my work and I'm not very familiar with it. I have this problem that when I submit data, it submits without refreshing the page, but on a second time when trying to submit, the page refreshes before submitting. I've used the e.preventDefault() to prevent the page from refreshing but it is not working for me. It just seems there is something I'm not doing right.
This is my Ajax code
<!--AJAX PROCESS TO SUBMIT CHECKED COURSES-->
$(document).ready(function(){
loadNewCourse();
loadDelTable();
$('#submit').click(function(){
$('#form').submit(function(e){
e.preventDefault();
var in_arr = [],
name = ("<?php echo $_SESSION['name']?>"),
email = ("<?php echo $_SESSION['email']?>"),
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>"),
dept = ("<?php echo $_SESSION['dept']?>"),
semester = ("<?php echo $_SESSION['semester']?>");
$('.inChk').each(function(i){
var checked = $(this).is(':checked');
if(checked){
in_arr.push($(this).val());
}
});
$.ajax({
url: 'submit.php',
type: 'POST',
cache: false,
async: false,
data: {
post_inId : in_arr,
name : name,
email : email,
regno : regno,
level : level,
dept : dept,
semester : semester
},
success: function(data){
loadNewCourse();
loadDelTable();
// setTimeout(function(){
// $('#regModal').modal('hide');
// }, 1000);
$('body').removeAttr('style');
$('#regModal').removeAttr('style');
$('.modal-backdrop').remove();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Registration successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data){
swal("Oops...", "Registration failed.", "error");
}
});
});
});
////////////////////////////////////////////////////////////////////////////////////////
// PROCESS AJAX DELETE ON CHECKBOX SELECT
$('#deleteCheck').click(function(){
$('#delform').submit(function(e){
e.preventDefault();
var id_arr = [],
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>");
$('.delChk').each(function(i){
var checked = $(this).is(':checked');
if(checked){
id_arr.push($(this).val());
}
});
swal({
title: "Are you sure you want to delete selected courses?",
text: "You can add these courses by registering again!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete!",
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
closeOnConfirm: false
},
function(isConfirm){
if(isConfirm){
$.ajax({
type: "POST",
url: "submit.php",
data: {
post_id : id_arr,
regno : regno,
level : level
},
cache: false,
async: false,
success: function(data){
// console.log(data);
loadDelTable();
loadNewCourse();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Delete successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data){
swal("Oops...", "Delete failed.", "error");
}
});
}else{
// alert('isNotConfirm and is not success');
swal("Oops...", "Delete failed", "error");
}
});
return false;
///////////////////////////////////////////////////////////////////////////////////////////
});
});
function loadNewCourse(){
$.ajax({
url: 'processReg.php',
type: 'POST',
cache: false,
async: false,
data: {
loadit : 1
},
success: function(disp){
$("#reveal").html(disp).show();
}
});
}
function loadDelTable(){
$.ajax({
url: 'delete_tbl.php',
type: 'POST',
cache: false,
async: false,
data: {
loadDel : 1
},
success: function(deldisp){
$("#showRegtbl").html(deldisp).show();
}
});
}
});
And this is the page displaying submitted data
<div class="" style="margin:auto;margin-top:0;text-align:center">
<div class="" >
<h2 class="#" style="font-family: 'proxima-nova','Helvetica Neue',Helvetica,arial,sans-serif;letter-spacing:5px;font-weight:100;color:#061931;">Welcome!</h2>
<p style="width:100%;font-size:14px;text-align:center;padding:5px;background:whitesmoke;padding:20px;">If this is your first visit, click on <b>Register Courses</b> to register courses available for you. <br>If you are re-visiting, you can continue where you left off.<br><span class="btn btn-md btn-primary" style="letter-spacing:3px;margin-top:10px;"><b>Register Courses</b></span></p>
</div>
</div><br>
<!--Display Courses that are available-->
<span id="reveal"></span>
<!--Table to display courses registered-->
<span id="showRegtbl"></span>
</div>
</div>
I've been stuck in this for more than 3days now. Can anyone here help me out pls?
I think you misunderstood the submission of the form and even handling.
The default action of the form ie submit can be done with input type="submit" or <button>
The default
<h2> Form default action </h2>
<form action="">
<input type="hidden" id="someInput" value="hey">
<input type="submit" value="submit">
</form>
To prevent form's default action you can do 2 things.
Avoid using type="submit" or button
Do something like this
function customForm(){
alert("Hey this is custom handler, dont worry page will not refresh...!");
}
<h2> Form with custom action </h2>
<form action="">
<input type="hidden" id="someInput" value="hey">
<input type="button" value="submit" onclick="customForm()">
</form>
Use event.preventDefault()
$('#myform').submit(function(e){
e.preventDefault();
alert("custom handler with preventDefault(), no reload no worries...!");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2> Form with custom handler using preventDefault() </h2>
<form id="myform" action="">
<input type="hidden" id="someInput" value="hey">
<input type="submit" value="submit" onsubmit="customForm(this)">
</form>
For any queries comment down.
Calling $("#form").submit(function() { ... }) creates a handler for the next time the form is submitted. Doing this inside the handler for $("#submit").click() is not correct. Clicking the submit button will establish a handler for the next submission, but then the default action will submit the form immediately, which refreshes the page. Putting e.preventDefault() inside the click handlers would prevent the reload, but then you would have to click twice to submit the form (and this wouldn't actually work, because the default action of a submit button is to trigger the submit event, and you're preventing that).
Just create submit handlers for each form, without doing it inside a click handler.
$(document).ready(function() {
loadNewCourse();
loadDelTable();
$('#form').submit(function(e) {
e.preventDefault();
var in_arr = [],
name = ("<?php echo $_SESSION['name']?>"),
email = ("<?php echo $_SESSION['email']?>"),
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>"),
dept = ("<?php echo $_SESSION['dept']?>"),
semester = ("<?php echo $_SESSION['semester']?>");
$('.inChk').each(function(i) {
var checked = $(this).is(':checked');
if (checked) {
in_arr.push($(this).val());
}
});
$.ajax({
url: 'submit.php',
type: 'POST',
cache: false,
async: false,
data: {
post_inId: in_arr,
name: name,
email: email,
regno: regno,
level: level,
dept: dept,
semester: semester
},
success: function(data) {
loadNewCourse();
loadDelTable();
// setTimeout(function(){
// $('#regModal').modal('hide');
// }, 1000);
$('body').removeAttr('style');
$('#regModal').removeAttr('style');
$('.modal-backdrop').remove();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Registration successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data) {
swal("Oops...", "Registration failed.", "error");
}
});
});
////////////////////////////////////////////////////////////////////////////////////////
// PROCESS AJAX DELETE ON CHECKBOX SELECT
$('#delform').submit(function(e) {
e.preventDefault();
var id_arr = [],
regno = ("<?php echo $_SESSION['regno']?>"),
level = ("<?php echo $_SESSION['level']?>");
$('.delChk').each(function(i) {
var checked = $(this).is(':checked');
if (checked) {
id_arr.push($(this).val());
}
});
swal({
title: "Are you sure you want to delete selected courses?",
text: "You can add these courses by registering again!",
type: "warning",
showCancelButton: true,
confirmButtonText: "Yes, delete!",
confirmButtonClass: 'btn btn-success',
cancelButtonClass: 'btn btn-danger',
closeOnConfirm: false
},
function(isConfirm) {
if (isConfirm) {
$.ajax({
type: "POST",
url: "submit.php",
data: {
post_id: id_arr,
regno: regno,
level: level
},
cache: false,
async: false,
success: function(data) {
// console.log(data);
loadDelTable();
loadNewCourse();
swal({
// "Success", "Registration successful", "success"
position: "top-end",
type: "success",
title: "Delete successful",
showConfirmButton: false,
timer: 2000
})
},
error: function(data) {
swal("Oops...", "Delete failed.", "error");
}
});
} else {
// alert('isNotConfirm and is not success');
swal("Oops...", "Delete failed", "error");
}
});
return false;
///////////////////////////////////////////////////////////////////////////////////////////
});
function loadNewCourse() {
$.ajax({
url: 'processReg.php',
type: 'POST',
cache: false,
async: false,
data: {
loadit: 1
},
success: function(disp) {
$("#reveal").html(disp).show();
}
});
}
function loadDelTable() {
$.ajax({
url: 'delete_tbl.php',
type: 'POST',
cache: false,
async: false,
data: {
loadDel: 1
},
success: function(deldisp) {
$("#showRegtbl").html(deldisp).show();
}
});
}
});
If you had multiple submit buttons in the same form you would instead assign click handlers to each button, but not create submit handlers for the form.
Thanks everyone for the assistance. I did some debugging on my end and was able to fix the issue by removing the form tags from the Add and Delete scripts and then include them in the page displaying the submitted data.
Like this...
<div class="" style="margin:auto;margin-top:0;text-align:center">
<div class="" >
<h2 class="#" style="font-family: 'proxima-nova','Helvetica Neue',Helvetica,arial,sans-serif;letter-spacing:5px;font-weight:100;color:#061931;">Welcome!</h2>
<p style="width:100%;font-size:14px;text-align:center;padding:5px;background:whitesmoke;padding:20px;">If this is your first visit, click on <b>Register Courses</b> to register courses available for you. <br>If you are re-visiting, you can continue where you left off.<br><span class="btn btn-md btn-primary" style="letter-spacing:3px;margin-top:10px;"><b>Register Courses</b></span></p>
</div>
</div><br>
<!--Display Courses that are available-->
<form id='form' action='POST' href='#'>
<span id="reveal"></span>
</form>
<!--Table to display courses registered-->
<form id='delform' action='POST' href='#'>
<span id="showRegtbl"></span>
</form>
</div>
</div>
Is there a more proper way to do this or this is just okay? Thank you for the help so far.

Javascript Confirm change into jquery modal dialog

I have here a delete record via ajax. I add confirm message if I want to delete the record or not. What I need is change the confirm message into modal dialog http://jqueryui.com/dialog/#modal-confirmation.
I want to change this javascript code
if(confirm("All PR and PO in this record will be deleted. Are you want to delete?"))
into this jquery modal dialog. Any help?
<script>
$(function () {
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Delete all items": function () {
$(this).dialog("close");
},
Cancel: function () {
$(this).dialog("close");
}
}
});
});
</script>
Ajax delete
<script>
$(function () {
$(".delbutton").click(function () {
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("name");
//Built a url to send
var info = 'name=' + del_id;
if (confirm("All PR and PO in this record will be deleted. Are you want to delete?")) {
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function () {}
});
$(this).parents(".record").animate({
backgroundColor: "#fbc7c7"
}, "fast")
.animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
</script>
You will override confirm method of javascript in your html code as follow
<script>
function confirm(message) {
var myTitle =
"<div style='float: left'>Error</div><div style='float: right; margin-right: 15px;'>Close</div>";
$('<div id="dlgTest1" style="display: none;min-height:auto;"><p style="text-align:justify;font-family:verdana;font-weight: bold;">'+message+'</p></div>').dialog({
resizable: false,
modal: true,
width: 300,
height: 'auto',
bgiframe: false,
//position: ['top', 5],
draggable: true,
closeOnEscape: true,
minHeight:20,
buttons: [{
text: "Cancel",
"style": 'background-color:#CCCCCC !important;color:rgb(119, 119, 119);font-family:verdana',
click:function(){
$(this).dialog('close');
return false;
}
},{
text: "Ok",
"style": 'background-color:#007AC0 !important;color:white;font-family:verdana',
click:function(){
$(this).dialog('close');
}
}
],
close:function(){ $(this).dialog('destroy').remove(); }
}).siblings('.ui-dialog-titlebar').append(myTitle); // title goes here;
//$("#dlgTest1").dialog("open").dialog("moveToTop");
};
and then use it , But be careful don't use html submit button on it, Use html normal button
//try this code
<script>
var isConfirmed=false;
$(function () {
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Delete all items": function () {
isConfirmed=true;
$(this).dialog("close");
},
Cancel: function () {
isConfirmed=false;
$(this).dialog("close");
}
}
});
$(".delbutton").click(function () {
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("name");
//Built a url to send
var info = 'name=' + del_id;
$("#dialog-confirm").html("All PR and PO in this record will be deleted. Are you want to delete?");
if (isConfirmed) {
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function () {}
});
$(this).parents(".record").animate({
backgroundColor: "#fbc7c7"
}, "fast")
.animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
</script>
//replace your script with this code and try
<script>
var isConfirmed=false;
$(function () {
$("#dialog-confirm").dialog({
resizable: false,
height: 140,
modal: true,
buttons: {
"Delete all items": function () {
isConfirmed=true;
$(this).dialog("close");
},
Cancel: function () {
isConfirmed=false;
$(this).dialog("close");
}
}
});
$(".delbutton").click(function () {
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("name");
//Built a url to send
var info = 'name=' + del_id;
$("#dialog-confirm").html("All PR and PO in this record will be deleted. Are you want to delete?");
$("#dialog-confirm").dialog();
if (isConfirmed) {
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function () {}
});
$(this).parents(".record").animate({
backgroundColor: "#fbc7c7"
}, "fast")
.animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
</script>

Custom confirm pop

I'm trying to customize confirm message using plugins. I have php tables records that has delete button every row. How I can customize the confirm pop up just like in jquery plugins below?
<?php echo'
<tr class="record">
<td align="center"><img src="images/del.png"></td></tr>';
?>
<script>
$(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("Are you want to continue ?"))
{
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
Jquery Plugins
<script>
$(function() {
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Delete all items": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
});
</script>
</head>
<div id="dialog-confirm" title="Empty the recycle bin?">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>These items will be permanently deleted and cannot be recovered. Are you sure?</p>
</div>
Hope this helps:
<?php echo'
<tr class="record">
<td align="center"><img src="images/del.png"></td></tr>';
?>
<script>
$(function() {
$(".delbutton").click(function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
$( "#dialog-confirm" ).dialog({
resizable: false,
height:140,
modal: true,
buttons: {
"Delete all items": function() {
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function(){
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast").animate({ opacity: "hide" }, "slow");
}
});
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
return false;
}
}
}); // end Dialog
return false;
}); // end .delbtn
}); // end jquery load
</script>
If you need more help, just ask.
"Delete all items": function() {
// insert your ajax here
$( this ).dialog( "close" );
},
Reference: .dialog()

Loading bar while submitting jquery ajax post, don't show up

I'm using jQuery UI dialog modal form.
All works great, but I send an ajax post, so I added this code:
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 500,
width: 550,
modal: true,
buttons: {
"Create an account": function() {
var bValid = true;
allFields.removeClass( "ui-state-error" );
// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
if ( bValid ) {
$.ajax({ url: 'about.php',
data: {name: name.val(), email: email.val()},
type: 'post',
async: false
});
}
}
}
});
The $.ajax part is what I added.
I want to show a Loading bar while processing the post, I added this code:
$('#progress')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
But it doesn't work, my post goes to a php script which one have 2 seconds waiting time.
It just don't show the #progress div, so the .hide is working.
Also, for example if I add $( "#dialog-form" ).dialog({ hide: "slide" }); before the $.ajax it doesn't work, it hides once all button function is finished.
Thanks.
If your #progress div is only show during this ajax call, why don't you put the show/hide action on your button action ?
Like this :
$( "#dialog-form" ).dialog({
autoOpen: false,
height: 500,
width: 550,
modal: true,
buttons: {
"Create an account": function() {
var bValid = true;
allFields.removeClass( "ui-state-error" );
if ( bValid ) {
// show before ajax call
$('#progress').show();
$.ajax({ url: 'about.php',
data: {name: name.val(), email: email.val()},
type: 'post',
async: true,
complete: function() {
//hide on complete
$('#progress').hide();
}
});
}
}
}
});
Hope this will help.

JQuery Dialog that calls remote script via ajax

I'm trying to get JQuery's dialog to send data to a remote script whenever the 'Add' Button is clicked in the dialog button, but my script seems to die at the .ajax and nothing is showing up in my console to give me a clue as to the error:
$( "#button" ).dialog({
resizable: false,
title: "Confirm",
height:140,
modal: true,
autoOpen: false,
buttons: {
"Add": function() {
var data = $('.part1').serialize()
$.ajax({
url: "/www/htdocs/test.pl",
type: "GET",
data: data,
cache: false,
success: function {
$('#div1').fadeOut('slow');
$('#div2').fadeIn('slow');
}
});
return false;
},
Cancel: function() {
$(this).dialog( "close" );
}
}
});
<div id="div1">
<input class="part1" type="hidden" value="Jon" name="fname">
<input class="part1" type="hidden" value="Doe" name="lname">
<input class="part1" type="hidden" value="jon#doe.com" name="email">
<input id="button" type="button" value="button">
</div>
<div id="div2">Complete</div>
You got a few syntax errors (which do show up in FireBug):
Add ; at the end of:
var data = $('.part1').serialize()
like:
var data = $('.part1').serialize();
Add () after success: function
like:
success: function()
Making the full code like this:
$( "#button" ).dialog({
resizable: false,
title: "Confirm",
height:140,
modal: true,
autoOpen: false,
buttons: {
"Add": function() {
var data = $('.part1').serialize();
$.ajax({
url: "/www/htdocs/test.pl",
type: "GET",
data: data,
cache: false,
success: function()
{
$('#div1').fadeOut('slow');
$('#div2').fadeIn('slow');
}
});
return false;
},
Cancel: function() {
$(this).dialog( "close" );
}
}
});
with those fixes, working fine here:
http://jsfiddle.net/YzhG9/10/

Categories