Chris
Chris

Reputation: 6182

jQuery Ajax returns undefined

$('.updateDescriptionProduct').click( function() {
  if ( updateProductDescription(productID, description) == 'true') {
    alert('success!');
  } else {
    alert('did not update');        
  }
});

function updateProductDescription(productID, description) {
  $.ajax({
    url: '/index.php/updateProductDescription',
    global: false,
    type: 'POST',
    data: ({productID: productID, description: description}),
    dataType: 'html',
    async:false,
    success: function(msg){
      alert(msg); 

      return msg;
    }
  });
}

The function itself says true, but my click event comes back as undefined.

Upvotes: 0

Views: 2849

Answers (1)

Gregory Baker
Gregory Baker

Reputation: 129

the return applies to the callback. Try setting a variable in the initial function and setting the value in the callback, then returning it?

function updateProductDescription(productID, description) {
    var ret = false;
    $.ajax({
          url: '/index.php/updateProductDescription',
          global: false,
          type: 'POST',
          data: ({productID: productID, description: description}),
          dataType: 'html',
          async:false,
          success: function(msg){
            ret = msg;
          }
    });
    return ret;
}

I haven't ever done an async call but it seems this should work. Let me know if it doesn't.

Upvotes: 10

Related Questions