I'm trying to write a callback function with js here. The problem is that the returned value is incorrect. The variable "d" in the ajax call contains the right data. But the variable a in the done(..) function, does not. Does anyone know how to assign a the value of d?
function render_confirmation_email(data, cart, delivery_date){
console.log("Render confirmation email")
var purchaseTable = "<table>"
for (var i = 0; i < cart.length; i++) {
console.log(i);
var concept = cart[i].name;
var price = cart[i].price;
purchaseTable += "<tr>"
purchaseTable += "<td>" + concept + " - </td>"
purchaseTable += "</tr>"
purchaseTable += "<tr>"
purchaseTable += "<td>" + price + " kr\n</td>"
purchaseTable += "</tr>"
}
purchaseTable += "</table>"
purchaseTable += "<br> <p>It will be delivered on " + delivery_date + "</p>"
var tempDom;
tempDom = $('<div></div>').append(data);
tempDom.find('#purchaseTable').append(purchaseTable);
return tempDom.text()
}
function get_confirmation_email(cart, delivery_date, render_confirmation_email) {
return $.ajax({
type: "GET",
url:"/confirmation_email",
async: false,
success:function(data) {
console.log("success");
// render_confirmation_email called when data is ready
var d = (render_confirmation_email(data, cart, delivery_date));
console.log("Rendering done")
console.log(d)
return d
}
});
}
var a = get_confirmation_email(JSONcart, form.querySelector('input[name=deliverydate]').value, render_confirmation_email);
a.done(function(data) {
console.log("Function done");
console.log(data);
});
Thank you!!!
Use then()
for each instance. A return
does nothing in success
as it is not part of the promise chain
Basic example
function doAjax() {
// sample data that will be returned
var json = '{"foo":[1,2,3]}'
return $.ajax({...}).then(function(resp){
// return to next "then()" in promise chain
return resp.foo
})
}
doAjax().then(function(data){
console.log(data) // [1,2,3]
})
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments