return false on javascript does not terminate the function but counties to run

I have ajax script for 'add to cart' functionality which works good.

In this I have a 'if 'condition set to check if the quantity has reached zero while adding to cart.

When it reaches zero the 'add to cart' function has to show alert message to customer and termniate.

I am getting the alert message on the browser. But still continues to add to cart, I have used return false here to stop it, but does not work. Please help me to fix this. Below is the code.


 $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json", url: url, data: data,
            success: function(response) {
           
                if (response) {
                              
                              if(response.flash_sale=='Yes')
                              {
                                    if(response.product_qty<0)// This will check the available qty.
                                    {
                                          alert('You have reached available quantity limit, Can not add more!');
                                          response.preventDefault();
                                          return false; //the whole function has to get terminated here, but still continues run below lines to add to cart.
     
                                    }
                              }
                              
                              
                    if (response.cart_type == 'add') {
                        $('#' + attr_id).html('Add to cart');
                    }
                 
                    var cart_class = $('#cart').attr('class');
                    if (response.cart) {
                                    get_cart_details();
                      //   console.log('asdfsd');
                      // setTimeout(get_cart_details(),5000);
                    } else {
                        $('#cart').removeClass('dropdown-menu').html('');
                    }
                    if (response.count) {
                    } else {
                        //$('#cart_count').html('');
                    }
                              
                              
                    $('#' + attr_id).attr('data-cart-type', response.cart_type);
                    return true;
                }
LVL 4
Peos JohnPHPAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Vijaya KumarCommented:
Try this
var exit_ajax=0;
$.ajax({
	type: "POST", 
	contentType: "application/json; charset=utf-8", 
	dataType: "json", url: url, data: data, 
	success: function(response) {
	if (response) {
				   
				  if(response.flash_sale=='Yes')
				  {
						if(response.product_qty<0)// This will check the available qty.
						{
							  alert('You have reached available quantity limit, Can not add more!');
							  response.preventDefault();
							  exit_ajax = 1 //the whole function has to get terminated here, but still continues run below lines to add to cart.

						}
				  }
		if(exit_ajax==0)
		{
		//do your add cart
		}
		else
		{
		//other options
		}

	}
});

Open in new window

0
Leonidas DosasCommented:
Test this please.I added an extra flag check variable inside to if conditions
$.ajax({
            type: "POST", 
            contentType: "application/json; charset=utf-8", 
            dataType: "json",
            url: url,
            data: data, 
            success: function(response) {
              var flag;
                if (response) {                               
                              if(response.flash_sale=='Yes' && response.product_qty<0 ){
                                    
                                          alert('You have reached available quantity limit, Can not add more!');
                                          flag=false;
                                          return false;                                          
     
                                    }                  
                              }                   
                            
                    if (response.cart_type == 'add' && flag!==false) {
                        $('#' + attr_id).html('Add to cart');
                    }else{return false;}                  
                    var cart_class = $('#cart').attr('class');
                    if (response.cart) {
                                    get_cart_details();
                    
                    } else {
                        $('#cart').removeClass('dropdown-menu').html('');
                    }
                    if (response.count) {
                    } else {
                        //$('#cart_count').html('');
                    }                               
                              
                    $('#' + attr_id).attr('data-cart-type', response.cart_type);
                    return true;
                }
            
});

Open in new window

0
Snarf0001Commented:
I'm more curious what else is going on in the function.  Nothing wrong with adding the flag checking in here, but there's no reason your existing code SHOULD be continuing execution.

"return false" by definition should exit out of the balance of the code in that block.  But there's a few other odd items in there, clarification might help:

1) What are you doing with the return statements?  Why "return true" and "return false"?  Since this is inside the success handler, that value is going nowhere, and essentially there's zero difference between "return true", "return false", or return anything, as nothing would be listening for that handler.

2) The "response" object coming back, is the direct response content coming back from the server, typically a json object.  Unless you declared some overrides somewhere else, ".preventDefault" would not exist on that object, and should throw an error, and again stop ALL further execution.

Can you post a more complete code sample?  Or shed some light on that?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

Peos JohnPHPAuthor Commented:
Thanks for your answers guys!

@Snarf0001 :
1) What are you doing with the return statements?  Why "return true" and "return false"?  Since this is inside the success handler, that value is going nowhere, and essentially there's zero difference between "return true", "return false", or return anything, as nothing would be listening for that handler.

You are right, that rings a bell.

Since everything is in success handler, it is already adding to cart while I try to reduce the available quantity in last.

However I have tried to handle this in this another way. Instead of stopping the function, I just disabled the add to cart button when it the quantity reaches zero using the response. I know it is not the best way to do it, but it works.

                       
						if(response.product_qty==0)
						{
							document.getElementById("buttons_"+response.product_id).style.display = "none";
						}

Open in new window



--------
2) The "response" object coming back, is the direct response content coming back from the server, typically a json object.  Unless you declared some overrides somewhere else, ".preventDefault" would not exist on that object, and should throw an error, and again stop ALL further execution.
--And I am not sure how to do this.
0
Snarf0001Commented:
Well that's what I'm confused about, it should be throwing an error already on the preventDefault() call.
Have you stepped through this in a debugger?  Or can you post a more complete code sample?
0
Vijaya KumarCommented:
@Snarf0001 return false in $ajax.success function is proper way of coding???


$ajax depends on $when.done(); it will skip....

@Peos John check $ajax dependency of return true
0
Snarf0001Commented:
@Vijaya

How do you figure that?  Under what scenario do you see a return true / false in the success handler making any difference?
The only time when.done would figure in, is if a promise was implemented around this particular call (which it isn't), and even then it would still pass in the response from the ajax call, not a true / false return value.
0
Peos JohnPHPAuthor Commented:
Thank you guys!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.