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?
 
Snarf0001Connect With a Mentor Commented:
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
 
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
Cloud Class® Course: Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

 
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 KumarConnect With a Mentor Commented:
@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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.