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));
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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With