title: Asynchronous javascript issue, appends undefined to page even though network has response
body: <p>I am having an issue with the values obtained from an ajax call attempting to append to the page before the value is actually assigned. For example, when sendRequest below is called I am getting a price response from the network each time, but when I console.log it, sometimes I get undefined. See comments in bold. I have tried making ajax request synchronous and a really ghetto setTimeout function, but I still get the occassional undefined. How can I make sure the price gets appended to the page? Please be nice to me if I'm being slow today :D</p>
  
  <pre><code>function updatePrices(IDs,callback){
      var product_id= &lt;?=$product_id ?&gt;;
      var qty= parseInt($j("#qtyUpdateBox input").val());
      var customer_id = null;
  
      &lt;?php if (isset($customer_id)) {?&gt;
          customer_id = &lt;?=$customer_id?&gt;;
          //$j('#vendorPriceListHeading').css({
              //'width': '230px',
              //'margin-left':'105px',
              //'margin-right':'-80px'
          //  });
      &lt;?php }?&gt;
  
      if (qty==1){
          function sendRequestOne(i) {
              var optionSelectionArray = currentlySelectedAttributes(IDs[i]);
  
              simpleWithAttrPrice(optionSelectionArray, customer_id, qty, function(data) {
                  var data= JSON.parse(data);
                  var unitPrice = parseFloat(roundDollar(data.basePrice));
  
                  $j('.details'+IDs[i]+ ' .priceBlock').empty();      
                  $j('.details'+IDs[i]+ ' .priceBlock').append('&lt;span&gt;'+formatCurrency(unitPrice,"$")+'&lt;/span&gt;');
  
                  $j('.details'+IDs[i]+ ' .vendorCheck input[name="customPrice"]:checked').val(unitPrice);
              });
          }//end sendRequest
  
          for(i=0; i&lt;IDs.length; i++)
          {   
              sendRequestOne(i);
          }
  
      }//end if
      else{
          //ajax call to obtain tier prices for each vendor id
          function sendRequest(i,qty,product_id){
              var vendor = IDs[i]; 
              $j.ajax({
                      type: "POST",
                      url: "/ajax_calls/updatePrices.php",
                      async:false,
                      data: { 'vendorID': vendor, 'product_id': product_id}
                      }).done(function(data) {
                          //CAITLIN below may need to be parsed in the php script
                              var data= JSON.parse(data);
  
                              var optionSelectionArray = currentlySelectedAttributes(vendor);
  
                              simpleWithAttrPrice(optionSelectionArray, customer_id, qty, function(price) {
                                  var price= JSON.parse(price);
                                  var unitPrice = roundDollar(parseFloat(price.basePrice));
                                  var pricexQty= unitPrice * qty;
  
  
                                  if (qty &lt; data.tier2_range_start){
                                      var unitPrice = totalPrice/qty;
                                  }
                                  else if (qty &gt;= data.tier2_range_start &amp;&amp; qty &lt; data.tier3_range_start){
                                      var discountPercent = data.tier2_discount;
                                      var discount = pricexQty * data.tier2_discount / 100;
                                      var totalPrice = pricexQty - discount;
                                  }
                                  else if (qty &gt;= data.tier3_range_start &amp;&amp; qty &lt; data.tier4_range_start){
                                      var discountPercent = data.tier3_discount;
                                      var discount = pricexQty * data.tier3_discount / 100;
                                      var totalPrice = pricexQty - discount;
                                  }
                                  else if (qty &gt;= data.tier4_range_start &amp;&amp; qty &lt; data.tier5_range_start){
                                      var discountPercent = data.tier4_discount;
                                      var discount = pricexQty * data.tier4_discount / 100;
                                      var totalPrice = pricexQty - discount;
                                  }
                                  else if (qty &gt;= data.tier5_range_start){
                                      var discountPercent = data.tier5_discount;
                                      var discount = pricexQty * data.tier5_discount / 100;
                                      var totalPrice = pricexQty - discount;
                                  }
                                  else{
                                      console.log('Something went wrong');
                                  }
                                  var unitPrice = roundDollar(totalPrice/qty); //unitPrice including Shipping
  
                                  setTimeout(function(){
                                      //BELOW IS LOGGING UNDEFINED SOMETIMES, BUT AJAX RESPONSE HAS THE VALUES
                                      console.log("The unit price is " + unitPrice + " and the discount percent is " + discountPercent);
  
                                      $j('.details'+vendor+ ' .priceBlock').empty();//update product price in DOM
                                      $j('.details'+vendor+ ' .priceBlock').append('&lt;span&gt;'+formatCurrency(unitPrice,"$")+'&lt;/span&gt;');
                                      //$j('.details'+data.vendor_id+ ' .priceBlock').append('&lt;span&gt;Total Price: '+formatCurrency(unitPrice*qty,"$")+'&lt;/span&gt;');
                                      $j('.details'+vendor+ ' .vendorCheck input[name="customPrice"]:checked').val(unitPrice);
                                      $j('.details'+vendor+ ' .priceBlock').append('&lt;h5 style="color:green"&gt;You will save '+discountPercent+'% !&lt;/h5&gt;');
                                  },1000);
                          });//end callback function
  
                          //reorderByPrice();
  
                      });//end done function
                  }//end function sendRequest
  
          for(i=0; i&lt;IDs.length; i++)
          {   
              sendRequest(i,qty,product_id);
          }
      }//end else
  
  
      if (callback) {
          setTimeout(callback, 1);
      }
  }//end function 
  
  
  
  function simpleWithAttrPrice(optionSelectionArray, customer_id, qty, callback){
      var product_id= &lt;?=$product_id ?&gt;;
  
          $j.ajax({
              type: "POST",
              url: "/ajax_calls/obtainBasePrice.php",
              data: { 'productID': product_id, 'optionSelectionArray' : optionSelectionArray, 'customer_id': customer_id, 'qty': qty} 
              }).done(callback);
  }   
  </code></pre>
  
  <p>Update Prices ajax call PHP:</p>
  
  <pre><code>&lt;?php
  $dbname='secret';
  require_once('/connect.php');
  require_once('/app/Mage.php');
  umask(0);
  Mage::app(); 
  $productModel = Mage::getModel('catalog/product');
  $attr = $productModel-&gt;getResource()-&gt;getAttribute("vendor");
  
  
  //post variable
  $ID= $_POST['vendorID'];
  //$ID= 1497;
  //echo 'the id is initially ' .$ID;
  
  if ($attr-&gt;usesSource()) {
      $ID= $attr-&gt;getSource()-&gt;getOptionText($ID);
      //echo $ID;
  }
  $product_id= $_POST['product_id'];
  $echoArray= array();
  
  if($ID == 3|| $ID ==4 || $ID ==11 || $ID ==12 || $ID ==13)
      $sql = 'SELECT * FROM tier_pricing WHERE vendor_id=' . $ID;
  else
      $sql = 'SELECT * FROM tier_pricing WHERE vendor_id=' . $ID. ' AND product_id=' . $product_id;
      foreach ($con-&gt;query($sql) as $row) {
          $echoArray['vendor_id']= $row['vendor_id'];
              $echoArray['tier2_range_start']= $row['tier2_range_start'];
          $echoArray['tier2_range_stop']= $row['tier2_range_stop'];
          $echoArray['tier3_range_start']= $row['tier3_range_start'];
          $echoArray['tier3_range_stop']= $row['tier3_range_stop'];
          $echoArray['tier4_range_start']= $row['tier4_range_start'];
          $echoArray['tier4_range_stop']= $row['tier4_range_stop'];
          $echoArray['tier5_range_start']= $row['tier5_range_start'];
          $echoArray['tier2_discount']= $row['tier2_discount'];
          $echoArray['tier3_discount']= $row['tier3_discount'];
          $echoArray['tier4_discount']= $row['tier4_discount'];
          $echoArray['tier5_discount']= $row['tier5_discount'];
      }
  
  echo json_encode($echoArray); 
  ?&gt;
  </code></pre>
  
  <p>Response screen shot (all ajax calls are returning correct values): </p>
  
  <p><img src="https://i.stack.imgur.com/uEuw7.png" alt="Console">
  <img src="https://i.stack.imgur.com/Ra5qp.png" alt="Network"></p>