Jquery AJAX submits the form even if confirm() method is false - javascript

<div class="report" data-id="55"></div>
<script>
$('.report').click(function() {
var id = $(this).data("id");
confirm("do you really want to report this post?");
$.ajax({
url: 'forumreport.php',
type: 'GET',
data: 'id='+id,
success: function(){
alert("reported!!");
},
});
})
</script>
I want to stop $.ajax() method if user clicks cancel on confirm form. However ajax is still sending the id to .php page. What should i do?

The confirm method returns a boolean indicating whether the prompt is confirmed, therefore you can simply save the resulting boolean in a variable and check whether it is true before executing the AJAX request.
$('.report').click(function() {
var id = $(this).data("id");
var confirmed = confirm("do you really want to report this post?");
if (confirmed) {
$.ajax({
url: 'forumreport.php',
type: 'GET',
data: 'id='+id,
success: function(){
alert("reported!!");
},
});
}
});

Confirm function returns a boolean value indicating whether OK or Cancel was selected (true means OK)
https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
Check for result which is returned by confirm function:
<script>
$('.report').click(function() {
var id = $(this).data("id");
if(confirm("do you really want to report this post?")){
$.ajax({
url: 'forumreport.php',
type: 'GET',
data: 'id='+id,
success: function(){
alert("reported!!");
},
});
};
})
</script>

Related

Not able to prevent redirecting

Here is script for action.
I want to prevent redirecting to url.
$('#rem_btn').click(function(event) {
event.preventDefault();
var remove = $(this).attr('href');
$.ajax({
type: 'get',
url: remove,
success: function(data) {
$('shop_pro_remove').html(data);
}
});
return false;
});
Please try this
HTML:
<a id='rem_btn' rel='remove_product.php?id=<?php echo $pro_id; ?>&name=<?php echo $product_name;?>' href="javascript:void(0)"> remove </a>
AJAX call:
$('#rem_btn').click(function(event) {
event.preventDefault();
var remove = $(this).attr('rel');
$.ajax({
type: 'get',
url: remove,
success: function(data) {
$('#shop_pro_remove').html(data);
}
});
return false;
});
The reason you’d want to do this with the href of a link is that normally, a javascript: URL will redirect the browser to a plain text version of the result of evaluating that JavaScript. But if the result is undefined, then the browser stays on the same page. void(0) is just the smallest script possible that evaluates as undefined.
Reference VOID
First of all, you're missing a closing } and a ). Second, there is an invalid selector in your ajax success callback , you probably wanted to use a class or an id.
Should look like:
$('#rem_btn').click(function(event) {
event.preventDefault();
var remove = $(this).attr('href');
$.ajax({
type: 'get',
url: remove,
success: function(data) {
$('#shop_pro_remove').html(data);
}
});
return false;
});

One submit button for multiple forms. Master save strategy,

Picture below shows simplification of the html page layout I am working with. It has 3 forms, every form has it's own submit button and can be submitted individually. At the top of the page "Master Save" is located. This button should save all 3 forms.
Every form have submit() function overloaded and they look like this:
form1.submit(function () {
Form1SubmitOverloaded(this);
return false;
});
Form1SubmitOverloaded = function (form) {
$.post(form.action, $(form).serialize(), function (data) {
//DOM manipulation, etc/
}).fail(function () {
//error parsing etc.
});
return false;
};
After pressing "Master Save" I want to submit forms in order 1 > 2 > 3. But I want Form 2 to wait until form 1 has ended.
Form1 submitted >> Form2 submitted >> Form3 submitted.
$('#masterSave').click(function () {
$('#form1').submit();
$('#form2').submit(); // wait until form1 ended
$('#form3').submit(); // waint until form2 ended
return false;
});
Please provide method to order submits in 'click' function as presented.
Thanks.
.post() method doesn't look to have a synch property. But .ajax() has.
I suggest you use the .ajax() method instead of the .post() shortcut method. That way you could force ajax to be synchronious
$.ajax({
[...]
async : false
}
you can use something like this
Form1SubmitOverloaded();
$.ajax({
type: "POST",
url: test1.php,
data: $( "#form1" ).serialize(),
success: function(){
Form2SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
Form3SubmitOverloaded();
$.ajax({
type: "POST",
url: test2.php,
data: $( "#form2" ).serialize(),
success: function(){
alert("All submit successfully");
}
});
}
});
}
});

Check if some ajax on the page is in processing?

I have this code
$('#postinput').on('keyup',function(){
var txt=$(this).val();
$.ajax({
type: "POST",
url: "action.php",
data: 'txt='+txt,
cache: false,
context:this,
success: function(html)
{
alert(html);
}
});
});
$('#postinput2').on('keyup',function(){
var txt2=$(this).val();
$.ajax({
type: "POST",
url: "action.php",
data: 'txt2='+txt2,
cache: false,
context:this,
success: function(html)
{
alert(html);
}
});
});
Suppose user clicked on #postinput and it takes 30 seconds to process.If in the meantime user clicks on #postinput2 . I want to give him an alert "Still Processing Your Previous request" . Is there a way i can check if some ajax is still in processing?
Suppose I have lot of ajax running on the page. Is there a method to know if even a single one is in processing?
You can set a variable to true or false depending on when an AJAX call starts, example:
var ajaxInProgress = false;
$('#postinput2').on('keyup',function(){
var txt2=$(this).val();
ajaxInProgress = true;
$.ajax({
..
..
success: function(html) {
ajaxInProgress = false;
Now check it if you need to before a call:
if (ajaxInProgress)
alert("AJAX in progress!");
Or, use global AJAX events to set the variable
$( document ).ajaxStart(function() {
ajaxInProgress = true;
});
$( document ).ajaxStop(function() {
ajaxInProgress = false;
});

Given a form submit, how to only submit if the server first responses back with a valid flag?

I have a form, with a text input and a submit button.
On submit, I want to hit the server first to see if the input is valid, then based on the response either show an error message or if valid, continue with the form submit.
Here is what I have:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
if (data.valid) {
return true
} else {
// Show error message
return false;
e.preventDefault();
}
}
});
});
Problem is the form is always submitting, given the use case, what's the right way to implement? Thanks
Try like this:
$('#new_user').submit(function(e) {
var $form = $(this);
// we send an AJAX request to verify something
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
// if the server said OK we trigger the form submission
// note that this will no longer call the .submit handler
// and cause infinite recursion
$form[0].submit();
} else {
// Show error message
alert('oops an error');
}
}
});
// we always cancel the submission of the form
return false;
});
Since you're already submitting via AJAX why not just submit the data then if it's valid rather than transmit the data twice?
That said, the function that makes the Ajax call needs to be the one that returns false. Then the successvfunction should end with:
$('#new_user').submit()
The fact that AJAX is asynchronous is what's throwing you off.
Please forgive any typos, I'm doing this on my cell phone.
Submitting the same post to the server twice seems quite unnecessary. I'm guessing you just want to stay on the same page if the form doesn't (or can't) be submitted successfully. If I understand your intention correctly, just do a redirect from your success handler:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
location.href = "success.htm";
},
// if not valid, return an error status code from the server
error: function () {
// display error/validation messaging
}
});
return false;
});
Another approach
EDIT: seems redundant submitting same data twice, not sure if this is what is intended. If server gets valid data on first attempt no point in resending
var isValid=false;
$('#new_user').submit(function(e) {
var $form = $(this);
/* only do ajax when isValid is false*/
if ( !isValid){
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
isValid=true;
/* submit again, will bypass ajax since flag is true*/
$form.submit();
} else {
// Show error message
alert('oops an error');
}
}
});
}
/* will return false until ajax changes this flag*/
return isValid;
});

jquery ajax call taking too long or something

I have a form that I want to ensure the paypal email address is valid before I submit. So i am making a jquery submit call like this
$('#new_user').submit(function(){
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('#user_paypal_email').append('<span style="color:#E77776;">This is not a valid email address</span>');
return false;
}else{
return true;
}
}
});
but the problem is this call thats a second and the page already refreshes before the ajax is complete....if I put the return false at the end of the call I can see my json is correct but for some reason the way I have it now wont finish...any ideas on how to correct this
Just use preventDefault() immediately when the submit event is fired. Then wait for the response from paypal and then call submit() on the form.
$('#new_user').submit(function(e){
e.preventDefault();
var form = $(this); //save reference to form
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('#user_paypal_email').append('<span style="color:#E77776;">This is not a valid email address</span>');
return false;
}else{
form.unbind('submit'); //remove binding
form.submit(); //submit form
}
}
});
If you want to do something right away you would need to set async false in the request

Categories

Resources