Search code examples
javascriptjqueryajaxwikitude

Javascript object cannot access url if it was received from AJAX


If url is assigned manually, for example imgUrl="http://image.jpg" it works perfectly, but if it received with the use of AJAX in function "getRemote" from back end it didn't. If the request asynchronous it's not even in this block, but if it synchronous it is received, but AR object cannot use it. Any ideas why?

var imgUrl = getRemote();
this.img = new AR.ImageResource(imgUrl);
this.imgOverlay = new AR.ImageDrawable(this.img, 0.5, {
    offsetX: 0,
    offsetY: 0,
});

getRemote function:

function getRemote() {
return $.ajax({
    type: "GET",
    url: "http://someurl.php",
    async: true
}).responseText;

}


Solution

  • Unless you can wait for response a method cannot return an ajax response, instead you should wrap your code in a function and use it a a callback, that will be executed when ajax is complete:

    var callOnRemote = function(imgUrl){
       this.img = new AR.ImageResource(imgUrl);
       this.imgOverlay = new AR.ImageDrawable(this.img, 0.5, {
           offsetX: 0,
           offsetY: 0,
       });
    };
    
    getRemote(callOnRemote);
    

    The getRemote function with jquery would look something like this:

    $.ajax({
      url: "/test.html"
    }).success(callOnRemote);