0

I currently have an ajax call that is working correctly and it is getting the required data but it is returning the data in the form of an object when i need it to return a string. I'm not exactly sure what im doing wrong here but here is my code:

var pillid=drawpills();
pillid=pillid.toString();
alert(pillid); //output is [object Object]

and the ajax method is:

function drawpills() {
    return $.post('js/fetchdata.php', function (data) { 
    });
}
drawpills().done(function(data) {
    var clock = document.getElementById('clock');
    clock.innerHTML = "<img src='images/clock/pill.png' alt='pill_image' id='pillpic" + data + "'/>";
    var picid = "pillpic" + data;
    return data;
}).fail(function() {
    // an error occurred
});

edit:

function drawpills() {
    return $.post('js/fetchdata.php', function (data) { 

    });
}
drawpills().done(function(data) {
    var clock = document.getElementById('clock');
    clock.innerHTML = "<img src='images/clock/pill.png' alt='pill_image' id='pillpic" + data + "'/>";
    callback(data);
}).fail(function() {
    // an error occurred
});
function callback(data){
var picid = "pillpic" + data;
return picid;
}
Ben
  • 2,518
  • 4
  • 18
  • 31
  • you cannot return data from done(). Here pillid is the promise interface, not the string you expect – A. Wolff Dec 15 '13 at 19:58
  • by setting your logic inside any promise method as done() callback. All functions which need to use returned value should be called once request is done. As a good read: http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – A. Wolff Dec 15 '13 at 20:05
  • I tried to follow that example and this is what I ended up with, if you could give me an example it would be appreciated. – Ben Dec 15 '13 at 20:12
  • instead of `return data;`, call function which need data value from here. Ajax is async, that's why! – A. Wolff Dec 15 '13 at 20:14
  • I tried doing this if you check the edit, but its still not working im really new to this so i dont really know what im doing. – Ben Dec 15 '13 at 20:20
  • I can't explain it better than in link i have previously posted, i'm afraid. If you use `var pillid=drawpills(); console.log(pillid);` maybe you'll better understand it, pillid being the promise interface returned from $.post() method but still not resolved because of async behaviour. – A. Wolff Dec 15 '13 at 20:26
  • a full example would be very helpful if you could? – Ben Dec 15 '13 at 20:29
  • my full example would be instead of `return data;` write `alert(picid );` and forget to use pillid variable because it is just wrong – A. Wolff Dec 15 '13 at 20:32

0 Answers0