Add confirm (yes no) in submit with preventDefault - javascript

i have code submit with preventDefault. this my code
//submit terima barang
$("form.form_terima").submit(function (event) {
if (confirm('Submit Terima Barang ?')) {
$(".loader").show();
//disable tombol submit supaya tidak reload
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'po_req/po_req_crud.php', //type='add_terima'
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
//action if success
}
});
return false;
}
});
but, it's not working. how to solve it ? thanks buddy :)

In your code, the event.preventDefault() will run only when the user has clicked "OK"/"Yes". If the user has clicked "No", then the form will submit.
You must add the event.preventDefault() outside of the if block to make it work as you expect.
$("form.form_terima").submit(function (event) {
if (confirm('Submit Terima Barang ?')) {
$(".loader").show();
//disable tombol submit supaya tidak reload
var formData = new FormData($(this)[0]);
$.ajax({
url: 'po_req/po_req_crud.php', //type='add_terima'
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data);
//action if success
}
});
}
// prevent default regardless of user's response
event.preventDefault();
return false;
});

Related

Submit form do action and refresh page with back to url

PHP variable:
<?php $course_details_url_back = site_url("home/lesson/".slugify($course_details['title'])."/".$course_id); ?>
script do action for form:
$(document).on('submit','#form_create_user',function(e){
e.preventDefault();
var fd = new FormData(this);
var obj = $(this);
fd.append('course_id', "<?php echo $this->uri->segment(4); ?>");
obj.find('input[type="submit"]').val("Tworzenie...")
$.ajax({
url: $(this).attr("action"),
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
// obj.find('input[type="submit"]').val("Confirm user")
}
});
$.ajax({
url: "<?php echo site_url('home/saveValues/'); ?>",
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
toastr.success("Success created user.");
obj.find('input[type="submit"]').val("Potwierdź")
}
});
})
After submit form I need do above actions and also I need to implement to above code refresh page on submit form and back to url.
For this I've separate code:
document.getElementById("form_create_user").onsubmit = function(){
window.location.replace("<?php echo $course_details_url_back; ?>");
}
But can anyone help me implement this to current one code?

Display confirmation message before send ajax request

I have written an ajax function where I want to display confirmation meeessage before submitting the form. How should I add with my condition. Below is my code.
$.ajax({
url: "UBRDashboard.aspx/GetDllValue",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ddlOduModel: ddlOduModel, ddlAntModel: ddlAntModel, ddlOMTModel: ddlOMTModel, ddlSapID: ddlSapID, ddlVendorName: ddlVendorName, strReqID: r.d, ddlSapDescVal: ddlSapDescVal, SITE_ADD: SITE_ADD, LATITUDE: LATITUDE, LONGITUDE: LONGITUDE, ddlEQP_SEQ: ddlEQP_SEQ, txtLinkID: txtLinkID, RJ_QUANTITY: RJ_QUANTITY, USER_NAME: USER_NAME, CREATED_DATE: CREATED_DATE, LOCATIONTYPE: LOCATIONTYPE, TOWERTYPE: TOWERTYPE }),
async: true,
processData: false,
cache: false,
success: function (r) {
if (r.d == "OK") {
alert('Record Saved successfully');
window.location.href = "UBRDashboard.aspx";
}
},
error: function (xhr) {
alert('Error while selecting list..!!');
window.location.href = "ErrorPage.aspx";
}
})
},
error: function (xhr) {
alert('Error while selecting list..!!');
window.location.href = "ErrorPage.aspx";
}
The solution is to use beforeSend ajax property.
beforeSend is a pre-request callback function before it is
sent.Returning false in the beforeSend function will cancel the
request.
beforeSend:function(){
return confirm("Are you sure?");
},
AJAX
$.ajax({
url: "UBRDashboard.aspx/GetDllValue",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ddlOduModel: ddlOduModel, ddlAntModel: ddlAntModel, ddlOMTModel: ddlOMTModel, ddlSapID: ddlSapID, ddlVendorName: ddlVendorName, strReqID: r.d, ddlSapDescVal: ddlSapDescVal, SITE_ADD: SITE_ADD, LATITUDE: LATITUDE, LONGITUDE: LONGITUDE, ddlEQP_SEQ: ddlEQP_SEQ, txtLinkID: txtLinkID, RJ_QUANTITY: RJ_QUANTITY, USER_NAME: USER_NAME, CREATED_DATE: CREATED_DATE, LOCATIONTYPE: LOCATIONTYPE, TOWERTYPE: TOWERTYPE }),
async: true,
processData: false,
cache: false,
beforeSend:function(){
return confirm("Are you sure?");
},
success: function (r) {
if (r.d == "OK") {
alert('Record Saved successfully');
window.location.href = "UBRDashboard.aspx";
},
error: function (xhr) {
alert('Error while selecting list..!!');
window.location.href = "ErrorPage.aspx";
}
});
Use ajax beforeSend callback function.
beforeSend: function () {
if(confirm("Are you sure?")){
// do something
} else {
// stop the ajax call
return false;
}
},
See documentation Ajax http://api.jquery.com/jquery.ajax/
Write your ajax into a function like:
function save(){
// something in here
}
After that write a confirmation functionality, if user confirm then call save() function
Maybe this exemple is what you need ?
var r = confirm("Press a button!");
if (r == true) {
// Make your ajax call here
} else {
// He refused the confirmation
}
Call your confirm before ajax call ?
You can try to put your confirmation message in the beforeSend method : http://api.jquery.com/jquery.ajax/
if ( confirm("Do you want to Submit?")) {
// If you pressed OK!";
$.ajax({
url: "UBRDashboard.aspx/GetDllValue",
dataType: "json",
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ ddlOduModel: ddlOduModel, ddlAntModel: ddlAntModel, ddlOMTModel: ddlOMTModel, ddlSapID: ddlSapID, ddlVendorName: ddlVendorName, strReqID: r.d, ddlSapDescVal: ddlSapDescVal, SITE_ADD: SITE_ADD, LATITUDE: LATITUDE, LONGITUDE: LONGITUDE, ddlEQP_SEQ: ddlEQP_SEQ, txtLinkID: txtLinkID, RJ_QUANTITY: RJ_QUANTITY, USER_NAME: USER_NAME, CREATED_DATE: CREATED_DATE, LOCATIONTYPE: LOCATIONTYPE, TOWERTYPE: TOWERTYPE }),
async: true,
processData: false,
cache: false,
beforeSend:function(){
return confirm("Are you sure?");
},
success: function (r) {
if (r.d == "OK") {
alert('Record Saved successfully');
window.location.href = "UBRDashboard.aspx";
},
error: function (xhr) {
alert('Error while selecting list..!!');
window.location.href = "ErrorPage.aspx";
}
});
} else {
// If you pressed Cancel!";
}
Please check with window.confirm
I ran into this issue recently, so this is my answer, I am using jquery and jqueryconfirm, the "beforesend" callbak only allows the standard "alert" and "confirm" functions.
What I did is placing a "fake" submit button and hide the actual submit one, so it was easy dealing with the response from the custom confirm dialogs, once I got the affirmative answer from the dialog I call the "click" method of the hidden submit button.
...
<button id="confirmSave" type="button">Save</button>
<button id="save" class="is-hidden" type="submit"></button>
<button id="close" aria-label="close" type="reset">Cancel</button>
...

Jquery is not submitting the form with the custom button

My requirement is to upload a file from a form upon clicking the custom button by using Jquery stuff.
My form details are below:
<form id="CreateAttachmentForm" method="post" enctype="multipart/form-data" action="../../FileUploadServlet" >
My file is defined as below:
<input type="file" id="fileupload1" name="fileupload1" accept="image/*,application/pdf" "/>
My custom button related code is below:
<contact:contactbutton
id="printButton"
style="position:relative; width:90px; top:27px; height:30px; left:160px;"
textTop="7px"
defaultButton="false"
tabindex=""
accesskey="C"
onClickEx="createAttachmentRequest();"
onfocus="if(event.altKey){click();}">
<u>C</u>reate
</contact:contactbutton>
Whenever the user clicks on the custom button, the form should be submitted.I have registered an onClick event event where the control should reach the function named createAttachmentRequest()
The following is my createAttachmentRequest() function:
function createAttachmentRequest() {
alert("test ");
$("#CreateAttachmentForm").submit(function() {
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/FileUploadServlet',
type: 'POST',
data: formData,
async: false,
success: function(data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
}
But the form is not submitted when I click the custom button. I have searched various questions on SO, but no suitable solution found so far.However I could see the alert message printed which confirms that the control is reaching the function createAttachmentRequest().What's wrong with my code?
The issue is because you're attaching a submit event handler in the function - not actually submitting the form.
It would be best to remove the createAttachmentRequest() function entirely and use unobtrusive JS code to attach the event. To do that, remove the onClickEx attribute from your <contact:contactbutton> element, then use this JS code:
$(function() {
$("#CreateAttachmentForm").submit(function(e) {
e.preventDefault();
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/FileUploadServlet',
type: 'POST',
data: new FormData(this),
success: function(data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
});
});
Also note that I removed async: false as it's incredibly bad practice to use it. If you check the console you'll even see warnings about its use.
You can do one of the following:
Take the submit event outside the function and remove the function like so:
$("#CreateAttachmentForm").submit(function(e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/FileUploadServlet',
type: 'POST',
data: formData,
async: false,
success: function(data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
OR
inside the function remove the submit listener like so:
function createAttachmentRequest() {
alert("test ");
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://HDDT0214:8080/pqawdTestWebApp/FileUploadServlet',
type: 'POST',
data: formData,
async: false,
success: function(data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
}

Saving tinyMCE value before submiting to php

I am trying to accomplish this. it does work but I have to submit the form twice before tinyMCE value get stored.
$("form#data").on('submit',function(e){
e.preventDefault();
tinymce.init({
selector: "textarea",
statusbar: false,
setup: function (editor) {
editor.on('change', function () {
editor.save();
});
}
});
var formData = new FormData($(this)[0]);
$.ajax({
url: 'includes/new_post.php',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
The Ajax part of the code works perfectly its just that the form like wise other forms but the tinyMCE text area wont submit on first go. if i click the button twice then it will save please assist.
Looks like you're doing the initializing in the wrong place.
The first time you submit the form, the tinymce gets initialized. Instead you should initialize it on page load.
you should do it like this:
tinymce.init({
selector: "textarea",
statusbar: false,
setup: function (editor) {
editor.on('change', function () {
editor.save();
});
}
});
$("form#data").on('submit',function(e){
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'includes/new_post.php',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});

How to send String data with formdata in ajax

<script type="text/javascript">
$(document).ready(function(){
$("#btnUpdate").click(function(){
alert($("#frm_data").serialize());
var formData = new FormData($("#frm_data")[0]);
var Desc= CKEDITOR.instances.editor1.getData();
$("#btnUpdate").attr('value', 'Please Wait...');
$.ajax({
url: 'update_job.php',
data: formData,
cache: false,
contentType:false,
processData:false,
type: 'post',
success: function(response)
{
$("#btnUpdate").attr('value', 'Update');
}
});
return false;
});
})
</script>
i use ckeditor for textarea field. but its can update value with new value, so i want to use another way with send textarea value with form data.
so how to send Desc data with fromData. in ajax.
To achieve this you can use the append() method of FormData to add whatever additional information you require:
$("#btnUpdate").click(function(e) {
e.preventDefault();
var $btn = $(this).attr('value', 'Please Wait...');
var formData = new FormData($("#frm_data")[0]);
formData.append('desc', CKEDITOR.instances.editor1.getData());
$.ajax({
url: 'update_job.php',
data: formData,
cache: false,
contentType: false,
processData: false,
type: 'post',
success: function(response) {
$btn.attr('value', 'Update');
}
});
});

Categories

Resources