I have a prompt box, which when i click on delete user, should ask to confirm if he wants to delete the user,
HTML
<form name="myform" id="myform" action="/AWSCustomerJavaWebFinal/DeleteUser" method="POST" onSubmit="myFunction()">
Choose User:
<br>
<select name="selectUser" multiple style="width: 200px !important; min-width: 200px; max-width: 200px;">
<c:forEach var="user" items="${listUsers.rows}">
<option value="${user.id}">
<c:out value="${user.userId}" />
</c:forEach>
</select>
<input type="submit" value="Delete User" class="btn btn-primary" />
<input type="reset" value="Reset" class="btn btn-primary" id=button1>
</form>
javascript
function myFunction() {
var confirm = prompt("Do you want to continue", "yes");
if (confirm == yes) {
var form = $('#myform');
form.submit(function() {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function(data) {
var result2 = data;
alert("deleted")
}
});
return false;
});
$(document).ready(function() {
$(document).ajaxStart(function() {
$("#wait").css("display", "block");
});
$(document).ajaxComplete(function() {
$("#wait").css("display", "none");
});
});
return false;
} else {
alert("User not deleted")
return false;
}
return false;
}
It asks to confirm, and if I press ok after writing yes in the textbox, it goes to the servlet, and does not give the alert("deleted"), and I have returned false, it still refreshes after pressing submit, also, if i press cancel, it still executes and deletes the user. I tried a lot of different approaches but nothing seems to work here. Thanks in advance.
Try using confirm rather than prompt
var r = confirm("Continue delete?");
if (r == true) {
//your logic to delete
} else {
//alert('user dint delete')
}
A nice one-liner :
if( !confirm("Do you want to continue?") ) return alert("User was not deleted.")
return will stop the execution of the function.
You have a form.submit(function() { $.ajax... that will always trigger your ajax call whenever the form is submitted, regardless of any validation mechanism you set up.
Here is a clean, rewritten version of your code :
in HTML : <form onSubmit="confirmSubmission()"> (a bit more explicit than myFunction() ;)
$(document).ready(function() {
var $wait = $("#wait");
$(document).ajaxStart(function() {
$wait.hide();
}).ajaxComplete(function() {
$wait.show();
});
});
function confirmSubmission() {
if ( !confirm("Do you want to continue")) return alert("Submission has been canceled.")
submit();
}
function submit(){
var $form = $('#myform');
$.ajax({
type : $form.attr('method'),
url : $form.attr('action'),
data : $form.serialize(),
success: function(data) {
var result2 = data;
alert("deleted")
}
});
}
Related
My issue is related to Page load.
I have the following code:
Controller:
public ActionResult Index()
{
BD.isEmailON_OFF= db.Email_ON_OFF_T.Select(x=>x.isEmailON_OFF).FirstOrDefault().GetValueOrDefault();
}
[HttpPost]
public ActionResult CheckEmail(string checkemails)
{
//calling Stored Procedure
if (!string.IsNullOrWhiteSpace(checkemails)|| checkemails=="true" || checkemails=="false")
{
var checkemails1 = new SqlParameter("checkemails", checkemails);
db.Database
.ExecuteSqlCommand("EXEC Sp_Email_on_off #checkemails", checkemails1);
}
return new JsonResult { };
}
I have table IS_Email_on_OFF_T:
I inserted to isemailonoff column as 0
Functionality:
I have turned on the email button and checkbox.
turn on email----->becomes turn off button and checkbox checked.
turn off button----> becomes turn on button and checkbox unchecked.
worked correctly till here.
turn on email----->becomes turn off button and checkbox checked.
page load(loading the page)
clicking on turn off button and not changing to turn on the button(1st attempt)(ISSUE)
clicking on turn off button(2nd tym) and it changes.
What I have tried is:
Views:
#{
if (Model.isEmailON_OFF == 0)
{
<input type="button" value="Turn Email on" class="btn btn-success" id="btnturnemailonoff" />
<input type="checkbox" id="Chkemailonoff" style="float:right;" />
}
else
{
<input type="button" value="Turn Email off" class="btn btn-success" id="btnturnemailonoff" />
<input type="checkbox" id="Chkemailonoff" style="float:right;" checked/>
}
}
AJAX call on button click:
<script type="text/javascript">
$(document).ready(function () {
$('#btnturnemailonoff').on('click', function () {
var checked = !$(this).data('checked');
var message = checked ? 'Turn Email ON' : 'Turn Email OFF';
if (confirm("Do you want to " + message + "? ")) {
$("#Chkemailonoff").prop('checked', checked);
$(this).val(checked ? 'Turn Email Off' : 'Turn Email on')
$(this).data('checked', checked);
debugger;
var url = '#Url.Action("CheckEmail", "BillingDetails")';
$.ajax({
url: url,
type: "POST",
data: { checkemails: checked },
dataType: "json",
// traditional: true,
success: function () {
alert("ajax request to server succeed");
}
});
}//end of if
});
});
</script>
SP:
ALTER procedure [dbo].[Sp_Email_on_off]
#checkemails varchar(10)
As
Begin
if(#checkemails='false')
Update Email_ON_OFF_T set isEmailON_OFF=0
else
Update Email_ON_OFF_T set isEmailON_OFF=1
End
I made changes in AJAX call button click and it worked for me.
$(document).ready(function () {
$('#btnturnemailonoff').on('click', function () {
debugger;
var checked = $("#Chkemailonoff").prop('checked');
var message = checked ? 'Turn Email On' : 'Turn Email Off';
if (confirm("Do you want to " + message + "? ")) {
$("#Chkemailonoff").prop('checked', !checked);
$(this).val(message)
var url = '#Url.Action("CheckEmail", "BillingDetails")';
$.ajax({
url: url,
type: "POST",
data: { checkemails: !checked },
dataType: "json",
success: function () {
//alert("ajax request to server succeed");
}
});
}
});
});
The following script shows the error message correctly, but the form always submits whether confirm_shop_code() returns true or false. I tried in many ways to solve the bug but it still persists. I have to stop the form from submitting when it returns false, but allow it to submit when it returns true. Please can any one help me to solve this?
<h2 id="shop_data"></h2>
<!-- form -->
<form action="" class="form-horizontal form-label-left input_mask" method="post" onsubmit="return confirm_shop_code();">
<div class="col-md-4 col-sm-4 col-xs-8 form-group">
<input type="text" class="form-control" id="shop" name="code" value="<?php echo $account->code; ?>" placeholder="Enter Shop Code">
</div>
</form>
<!-- validation script -->
<script>
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
return true;
} else {
return false;
}
}
});
} else {
$( '#shop_data' ).html("");
return false;
}
}
</script>
<!-- php code -->
<?php
include "system_load.php";
$code = $_POST['shop_code'];
global $db;
$query = "SELECT code from accounts WHERE code='".$code."'";
$result = $db->query($query) or die($db->error);
$count = $result->num_rows;
if($count > 0) {
echo "SHOP CODE already Exists";
} else {
echo "OK";
}
exit;
?>
The reason it is submitting is because AJAX calls are asynchronous by default. I wouldn't suggest making it synchronous because this will block the rest of the javascript execution. Also, you are returning false from the success method of $.ajax. This is not in the same scope as the parent function and therefore does not also cause the parent function to return false. So in fact, your confirm_shop_code() function is not returning anything unless code is false and that's why your form is always being submitted, no matter what happens with the AJAX call.
I would recommend using jQuery to bind to the form's submit event and just disable form submitting with preventDefault(). First, just add an id attribute to the form (e.g. "yourform") and do something like:
$("form#yourform").submit(function(e) {
e.preventDefault();
var form = $(this);
var code=document.getElementById( "shop" ).value;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
form.unbind('submit').submit()
}
}
});
} else {
$( '#shop_data' ).html("");
}
});
You need to add async:false to your ajax code
function confirm_shop_code(){
var code=document.getElementById( "shop" ).value;
var stopSubmit = false;
if(code) {
$.ajax({
type: 'post',
url: 'validations.php',
async:false,
data: {
shop_code:code,
},
success: function (response) {
$( '#shop_data' ).html(response);
if(response=="OK") {
stopSubmit = false;
} else {
stopSubmit = true;
}
}
});
} else {
$( '#shop_data' ).html("");
stopSubmit = true;
}
if(stopSubmit){
return;
}
}
You should call return false; function on the click event of the submit button.
<button type="submit" id="submit" onclick="return false;" class="btn btn-primary col-4">Proceed</button>
or you can use:
document.getElementById("submit").addEventListener("click", function (e) {
//your logic here
//this return false will not work here
return false;
//this will work
e.preventDefault();
});
I am trying to click on the "Change" button and send the form data to another JSP page in order to perform an UPDATE statement in the database. For some reason I cannot get the "update" id button to execute the click() function with the AJAX call in it as the "ham" alert does not pop up. Sorry I have multiple commented out approaches to this in the script tags since I tried out multiple things. Would someone be able to help me out with this? The current jsp page looks as follows:
<!DOCTYPE html>
<head>
<script src="/.jquery-1.9.1.js" type="text/javascript" charset="utf-8"></script>
<script src="http://code.jquery.com/jquery=latest.min.js" type="text/javascript">
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = decodeURIComponent(window.location.search.substring(1)),
sURLVariables = sPageURL.split('&'),
sParameterName,
i;
for (i = 0; i < sURLVariables.length; i++) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam) {
return sParameterName[1] == undefined ? true : sParameterName[1];
}
}
};
$(document).ready(function() {
var key = getUrlParameter("key");
});
$(form).submit(function() {
if (-1 == this.action.indexOf('register')) {
var jForm = $(this);
$.post(this.action, $(this).serialize(), function(data) {
if (data.status == 'SUCCESS') {
jForm[0].action = data.redirectUrl;
jForm.submit();
}
return false;
}
}
});
window.onload = function() {
document.getElementById("submit").onclick = function() {
location.href = "/View.jsp";
}
}
window.onload = function() {
document.getElementById("update").onclick = function() {
location.href = "/View.jsp";
}
}
$(document).ready(function() {
$('#update').on('click', function(e) {
alert('ham');
$.ajax({
type: "post",
url: "change.jsp",
data: $("#form").serialize(),
success: function(msg) {
alert(msg.data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
$(document).ready(function() {
function click() {
alert('ham');
$.ajax({
type: "post",
url: "change.jsp",
data: $("#form").serialize(),
success: function(msg) {
alert(msg.data);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
window.location.href = "change.jsp";
return false;
}
});
/*function validateForm(){
var x=document.forms["insert"]["ID"].value;
alert(x.len());
if(x==null||x==""){
alert("ID must be filled out");
return false;
}
}*/
</script>
</head>
<body>
...
<form id="myForm" action="register" method="post" name="insert">
ID:
<input type="text" name="ID" required value="<%=id%>" />
<br/> RHINO:
<input type="text" name="rhino" required value="<%=rhino%>" />
<br/> OX:
<input type="text" name="ox" required value="<%=ox%>" />
<br/> HORSE:
<input type="text" name="horse" required value="<%=horse%>" />
<br/>
<input type="submit" value="Submit" id="submit" />
<!--<input type="submit" value="Update" id="change"/>-->
<button id="update" onclick="return click()">Change</button>
</form>
...
</body>
</html>
You're defining the function in a closed scope:
$(document).ready(function() {
function click() {
//...
}
});
So it only exists within that anonymous function being used as the ready handler. Once that function terminates, anything defined in that scope is no longer used if nothing references it.
Then you try to invoke the function from global scope:
<button id="update" onclick="return click()">Change</button>
So the function can't be found.
Instead of trying to invoke it from inline code in the HTML, use the jQuery library that you're already using and attach the handler to the click event:
$(document).ready(function() {
$('#update').click(function () {
// the code in your click() function goes here
}
});
And remove that inline handler:
<button id="update">Change</button>
(Note: There may very well be other problems in this code. It's actually quite difficult to follow without any indentation at all. But at the very least this problem seems the most immediate upon clicking that button. It needs to be able to find the function in order to execute it.)
Update: Another user has formatted the code in your question, and there do appear to be other problems. Specifically, you are making multiple simultaneous attempts to attach very different behaviors to the click of that button. One of those events appears to even be a redirect, which would simply cancel any other operations because the page is reloading. Simplify your code. Perform exactly and only the operation you want on that button click.
I want to validate form and then send the values using $.ajax .but it shows Undefined index: is_ajax. why it does not get form_data? why it happens?What change should be done?
here is my script
function validateForm()
{
var oldPassword = document.forms["dsettings"]["oldPassword"].value;
var newPassword = document.forms["dsettings"]["newPassword"].value;
var retypePassword = document.forms["dsettings"]["retypePassword"].value;
if (document.forms["dsettings"]["oldPassword"].value == null || oldPassword == "") {
alert("Enter old password");
return false;
}
else if (document.forms["dsettings"]["newPassword"].value == null || newPassword == "") {
alert("Enter new password");
return false;
}
else if (document.forms["dsettings"]["retypePassword"].value == null || retypePassword == "") {
alert("Retype new password");
return false;
}
else if ( newPassword != retypePassword) {
alert("Retype new password correctly");
return false;
}
else
{
var action = $("#dsettings").attr('action');
var form_data = {
oldPassword: $('#oldPassword').val(),
newPassword: $('#newPassword').val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: form_data,
success: function(response)
{
if(response == "success")
$("#message").html('<p class="success">Successfully changed password!</p>');
else if(response == "wrong_old_password")
{
$("#message").html('<p class="error">Wrong old password!type again!</p>');
}
else
{
$("#message").html('<div class="error">update error.Try again! !</div>');
}
}
});
}
}
my html code
<button type="submit" id="submit" name="submit" onclick="return validateForm()" class="form-submit" >submit</button>
and php code
<?php $is_ajax = $_REQUEST['is_ajax'];
// some codes ?>
Since this seems to be your very first post and very ugly , you need to clean it something like this (which is not perfect either !)
Provide as much as data as possible e. g
HTML
<form action="fakeurl.com" method="post" name="dsettings" id="dsettings" >
<ul>
<li>Old Password: <input type="password" name="oldPassword" /></li>
<li>New Password: <input type="password" name="newPassword" /></li>
<li>Retype New Password: <input type="password" name="retypePassword" /></li>
<li><input type="submit" name="submit" value="Change Password" /></li>
<li><div id="message"/></li>
</ul>
</form>
Javascript
$(document).ready(function(){
$('#dsettings').on('submit',function(event){
changePassword(this)
event.preventDefault();
});
});
function validateChangePassword(frm){
var oldPassword=frm["oldPassword"].value
var newPassword=frm["newPassword"].value
var retypePassword =frm["retypePassword"].value;
if (oldPassword.trim()=="") {
$('#message').html("<p class='error'>Enter old password</p>");
return false;
}
else if (newPassword.trim()=='') {
$('#message').html("<p class='error'>Enter new password</p>");
return false;
}
else if (retypePassword.trim() == "") {
$('#message').html("<p class='error'>Retype new password</p>");
return false;
}
else if ( newPassword != retypePassword) {
$('#message').html("<p class='error'>Retype new password correctly</p>");
return false;
}
else
return true;
}
function changePassword(frm){
if(validateChangePassword(frm)){
var url = $(frm).attr('action');
var data = {
oldPassword: $(frm).find('input[name="oldPassword"]').val(),
newPassword: $(frm).find('input[name="newPassword"]').val(),
retypePassword: $(frm).find('input[name="retypePassword"]').val(),
is_ajax: 1
};
ajaxPost(url,data);
}
return false;
}
function ajaxPost(post_url,post_data){
$.ajax({
type: "POST",
url: post_url,
data: post_data,
success: function(response)
{
if(response == "success")
$("#message")
.html('<p class="success">Successfully changed password!</p>');
else if(response == "wrong_old_password")
{
$("#message")
.html('<p class="error">Wrong old password!type again!</p>');
}
else
{
$("#message")
.html('<div class="error">update error.Try again! !</div>');
}
}
});
}
DEMO
Possible Issues
Avoid using custom js and jquery mix
I suspect you provided any id to element e.g $('#oldPassword').val()
There is good plugin for form validation use that one
Try to change your code on function call with parameter:
function validateForm(e) {
e.preventDefault();
and here:
<button type="submit" id="submit" name="submit" onclick="validateForm(this); return false;" class="form-submit" >submit</button>
From the answers you've given in the comments, what's almost certainly happening is that:
You are not preventing the default submit behavior, so the default submit behavior is taking place
There is an error somewhere in your code that is causing your validateForm() function to fail and for your $.ajax to never run
To troubleshoot this:
Change your button to type="button".
Open up your JS console (you can usually do this by pressing F12 and clicking the Console tab)
See if there are any errors in the console.
Once you figure out what the error is, you should:
Stop using onclick handlers and unobtrusively set up events
Use preventDefault() to prevent default submit events
$(function () {
$("#submit").click(function (e) {
e.preventDefault();
validateForm();
});
});
Include jquery-1.4.3.min.js file before validateForm function call.
<input type="button" name="submit" value="Change Password" onclick="validateForm()" />
I was wonder if in JQuery, this is possible:
<form id="testform">
<input type="text" id="hi" name="hi" />
<input type="text" id="bye" name="bye" />
<button type="submit" id="submit1">Use Me</button>
<button type="submit" id="submit2">No, Use Me </button>
</form>
$('#testform').submit(function(e) {
e.preventDefault();
var submiturl;
if (e.name === 'submit1') { submiturl = '../sendToFactory.cshtml'; }
else if (e.name === 'submit2') { submiturl = '../sendOverseas.cshtml'; }
$.ajax({
url: submiturl,
data: $('testform').serialize(),
type: 'POST',
datatype: 'json',
success: function (response) {
//stuff
},
error: function (response) {
//error
}
});
});
I know the e.name isn't right, but there must be someway to do something similar to that, no?
And I'm using IE9 and above.
You can turn "type='submit'" to "type='button'" so it does not submit form and listen to the buttons clicks:
$("#testform button[type=button]").click(function (e) {
var submitUrl;
switch ($(e.target).attr('id')) {
case 'submit1':
submitUrl = 'url1.cshtml';
break;
case 'submit2':
submitUrl = 'url2.cshtml';
break;
}
$.ajax({
//...
})
});
You can extract the info from new FormData(form) while handling the submit event where form is a reference to <form> element. Note that you have to extract the info while handling the event because even if you go through event loop (e.g. setTimeout(..., 0)) the submit button info has already been lost.
It turns out that latest browsers do not populate FormData with the submit button anymore. So nowadays you can do something like following, given reference to <form> element as form:
form.addEventListener('submit', function(event)
{
event.preventDefault();
var formdata = new FormData(form);
formdata.append(event.submitter.name, event.submitter.value);
...
xhr.send(formdata);
}
The event.submitter will contain a reference to the form button that submitted the form.
In case the form may have multiple submit event handlers and one or more of those may actually modify the data on the form before submitting it (e.g. TinyMCE) you may need to do tricks like
form.addEventListener('submit', function(event)
{
let form = this;
let submitter = event.submitter;
setTimeout(function()
{
let formdata = new FormData(form);
formdata.append(submitter.name, submitter.value);
xhr.send(formdata);
}, 0);
event.preventDefault();
}
The setTimeout(..., 0) will allow all existing submit handlers to run and the full event loop to drain empty before proceeding to collect the FormData and send the XHR.
You can maintain the form, just add additional events to setup which button called the submit.
var form_config = {button: null};
$("#submit1").click(function(){
form_config.button = 'submit1';
});
$("#submit2").click(function(){
form_config.button = 'submit2';
});
$('#testform').submit(function(e) {
console.log(e);
e.preventDefault();
var submiturl;
if (form_config.button === 'submit1') { submiturl = '../sendToFactory.cshtml'; }
else if (form_config.button === 'submit2') { submiturl = '../sendOverseas.cshtml'; }
$("#hi").val(submiturl);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form id="testform">
<input type="text" id="hi" name="hi" />
<input type="text" id="bye" name="bye" />
<button type="submit" id="submit1">Use Me</button>
<button type="submit" id="submit2">No, Use Me </button>
</form>
If you don't use the submit event of the form and you need to use the button event trigger then you should do something like this :
$('button').click(function(e){
var id$ = $(this).attr('id');
e.preventdefault();
var submiturl;
if (id$ == 'submit1') { submiturl = '../sendToFactory.cshtml'; }
else if (id$ == 'submit2') { submiturl = '../sendOverseas.cshtml'; }
$.ajax({
url: submiturl,
data: $('testform').serialize(),
type: 'POST',
datatype: 'json',
success: function (response) {
//stuff
},
error: function (response) {
//error
}
});
});
try this
$(document).ready(function() {
$( "form" ).submit(function () {
// Get the submit button element
var btn = $(this).find("button:focus").val();
alert(btn);
//DO YOUR AJAX
});
});