0

cant seem to get the response from this ajax post

  $("#btn_update_shipping_cost").click(function(e){
       var new_freight = 0;

       $.post("/action.shipping.cost.php?page=get-adjusted-freight",{
          current_weight : current_weight,
          shipping_country:shipping_country
       },
       function(result){
          new_freight = result;
       });
    });
ram obrero
  • 197
  • 10
  • 1) `new_freight` isn't a global variable, it's scoped to the click handler. 2) I can't tell for sure, but you may run into async issues doing it this way. – Jason P Mar 26 '14 at 03:48
  • how to set new_freight as global? should i declare it outside the clik event? – ram obrero Mar 26 '14 at 03:49
  • Yes, or use `window.new_freight` instead. – Jason P Mar 26 '14 at 03:49
  • @ramobrero: won't matter. You need to use the response inside the callback, unless you don't need it immediately. Your question sounds like you're trying to use it right away. – cookie monster Mar 26 '14 at 03:49
  • i need the response immediately, because i will be using the returned value during the whole click event – ram obrero Mar 26 '14 at 03:51
  • this is $.post per se, thanks – ram obrero Mar 26 '14 at 03:52
  • The result is available in the `$.post()` completion handler callback function. That's where you use it. That's the ONLY place to use it. Read the post I linked a couple comments up to explain the async issue here. Put all code that needs to use the `$.post()` result IN the completion handler for that ajax call and nowhere else or call a function from the completion handle rand pass the data to that function. – jfriend00 Mar 26 '14 at 03:52
  • Is there more to the click event that you haven't posted? If so, you'll need to put the rest inside the ajax callback. – Jason P Mar 26 '14 at 03:52
  • this is the only click event im doing, i will be validating the returned value, perhaps, ill do the validation inside the $.post itself – ram obrero Mar 26 '14 at 03:54
  • So, where else are you using `new_freight`? – Jason P Mar 26 '14 at 03:55
  • Yes, you HAVE to do the processing of the result IN the `$.post()` completion handler. – jfriend00 Mar 26 '14 at 03:56

1 Answers1

0
$(document).ready(function(){
var new_freight = 0;

$("#view_report").click(function(){
  $("#btn_update_shipping_cost").click(function(e){

       $.post("/action.shipping.cost.php?page=get-adjusted-freight",{
          current_weight : current_weight,
          shipping_country:shipping_country
       },
       function(result){
          new_freight = result;
       });
    });
});
Sajitha Rathnayake
  • 1,688
  • 3
  • 26
  • 47