Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript function to return an object , but it does not , variable get destroyed outside xhr.onload function

Tags:

javascript

this has may be discussed over several times. but just to make the idea clear. I want my function to return an object. but the way I wrote the code, it does not return the object. I tried other ways. but variable gets destroyed when it comes to outside of xhr.onload function. please help me understanding the problem

function hhtprequest(id)
{
    var pobj = function(image,name,price){
        this.image = image;
        this.name = name;
        this.price = price;
    }

    var xhr =  new XMLHttpRequest();
    xhr.open("GET","ajax/productinfforsell.php?pid="+id,true);
    xhr.onload = function(){
        if (this.readyState === 4 && this.status === 200) {
            var data = JSON.parse(this.response);

              new pobj(data.imagefile,data.name,data.price);

        }

    }

    xhr.send();
    return pobj;
}
console.log(hhtprequest(9));
like image 753
Atik Hashmee Avatar asked Nov 07 '22 10:11

Atik Hashmee


1 Answers

Try this..

var pobj = {};
function handleData(obj){
   console.log(JSON.stringify(obj));
}
function hhtprequest(id)
{
    var xhr =  new XMLHttpRequest();
    xhr.open("GET","ajax/productinfforsell.php?pid="+id,true);
    xhr.onload = function(){
        if (this.readyState === 4 && this.status === 200) {
            var data = JSON.parse(this.response);
            pobj.image = data.imagefile;
            pobj.name = data.name;
            pobj.price = data.price;     
            handleData(pobj);         
        }
    }
    xhr.send();
}
like image 126
kheya Avatar answered Nov 14 '22 23:11

kheya