0

I'm creating a custom javascript library for a project im creating and I'm having trouble passing the data from the library to the the webpage. Basically I'm creating my own http request library. When I try to set a var to the returned value from my library call like so:

var data = Cynergi.get();
console.log(data); shows undefined.

This is my library code.

(function(window){
    function defineCynergi(){
            var Cynergi = {};
            Cynergi.alert = function (){
                alert("this is a cynergi test");
            }

            Cynergi.get = function(){
                    var data = getData();
            }
            return Cynergi;
        }
    if(typeof(Cynergi) === 'undefined'){
        window.Cynergi = defineCynergi();
    }
})(window);

function getData(){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', encodeURI('http://thewaywardjourney.com:3000/computer_stats?order=time.asc'));
    xhr.onload = function() {
        if (xhr.status === 200) {
            //alert('User\'s name is ' + xhr.responseText);
            var data = JSON.parse(xhr.responseText);
            console.log(data);
        }
        else {
            //alert('Request failed.  Returned status of ' + xhr.status);
            //data = JSON.parse(xhr.responseText);  
        }
    return data;
    };
    xhr.send(); 
}

I haven't parameterized the function yet because im trying to understand how it all works first.

ok so heres my attempt at callback as per suggestion and it still doesn't work. Now I get an undefined is not a function in the console and im following a stack post as suggested.

function getData(args, callback){
    var xhr = new XMLHttpRequest();
    xhr.open('GET', encodeURI('http://thewaywardjourney.com:3000/computer_stats?order=time.asc'));
    xhr.onload = function() {
        if (xhr.status === 200) {
            callback(xhr.responseText);
        }
        else {
        }
    };
    xhr.send(); 
    return;
}

OK SO I GOT IT WORKING BUT I CANT ACCESS THE DATA:

This is what I call: updateComputerdata(); var data = Cynergi.get(); console.log(data.data)

Object {data: null, setData: function}
data: Array[62]
setData: function (data){ this.data = data;}
__proto__: Object


(function(window){
    function defineCynergi(){
            var Cynergi = {};
            Cynergi.alert = function (){
                alert("this is a cynergi test");
            }
            Cynergi.get = function(){
                     var ret_data = {
                         data: null,
                         setData: function(data){ this.data = data;}
                     }
                    getData(ret_data);
                    return ret_data;
            }
            return Cynergi;
        }
    if(typeof(Cynergi) === 'undefined'){
        window.Cynergi = defineCynergi();
    }
})(window);

function getData(ret_data){
     var the_data = {
         data: null,
         setData: function(data){ this.data = data;}
     }
    var xhr = new XMLHttpRequest();
    xhr.open('GET', encodeURI('http://thewaywardjourney.com:3000/computer_stats?order=time.asc'));
    xhr.onload = function() {
        if (xhr.status === 200) {
            the_data.setData(JSON.parse(xhr.responseText));
        }
        else {
            the_data.setData(JSON.parse(xhr.responseText));
        }
    };
    xhr.send(); 
    ret_data.setData(the_data);
    return the_data;
}

if you see this image the first one is ret_data and then the second object in that console output is ret_data.data you can see that in the second console output object that data has an array and in the first one before I called .data it was a nested object. however if I call ret_data.data.data because thats the nested objects data value but it returns null and im not sure why or how to fix it.

updated code 

(function(window){

    function defineCynergi(){

            var Cynergi = {};

            Cynergi.get = function(){

                     var ret_data = {

                         data_returned: null,

                         setData: function(data_returned){ this.data_returned = data_returned;}

                     }

                    getData(ret_data);

                    console.log(ret_data);

                    return ret_data;

            }

            return Cynergi;

        }

    if(typeof(Cynergi) === 'undefined'){

        window.Cynergi = defineCynergi();

    }

})(window);



function getData(ret_data){



     var the_data = {

         data: null,

         setData: function(data){ this.data = data;}

     }

    var xhr = new XMLHttpRequest();

    xhr.open('GET', encodeURI('http://thewaywardjourney.com:3000/computer_stats?order=time.asc'));

    xhr.onload = function() {

        if (xhr.status === 200) {

            the_data.setData(JSON.parse(xhr.responseText));

        }

        else {

            the_data.setData(JSON.parse(xhr.responseText));

        }

    };

    xhr.send(); 

    ret_data.setData(the_data);

    return the_data;



}



            //alert('User\'s name is ' + xhr.responseText);

            //var data = JSON.parse(xhr.responseText);

            //alert('Request failed.  Returned status of ' + xhr.status);

            //data = JSON.parse(xhr.responseText);  

            //console.log(data);

enter image description here

ok so I changed it up a bit

(function(window){
    function defineCynergi(){
            var Cynergi = {};
            var returned_data;
            Cynergi.get = function(){
                getData('http://127.0.0.1:3000/computer_stats?order=time.asc', sendData);
            }
            return Cynergi;
        }
    if(typeof(Cynergi) === 'undefined'){
        window.Cynergi = defineCynergi();
    }
})(window);

function getData(url, callback){

    var xhr = new XMLHttpRequest();
    xhr.open('GET', encodeURI(url));
    xhr.onload = function() {
        if (xhr.status === 200) {
            callback(JSON.parse(xhr.responseText));
        }
        else {
            callback(JSON.parse(xhr.responseText));
        }
    };
    xhr.send(); 
}

function sendData(ret_data){
    returned_data = ret_data;
    console.log(ret_data); // this works but it doesnt send the data back.
}

HTML CODE:

<!DOCTYPE HTML>
<html>
    <head>
        <title>TheWayWardJourney</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <script src="cynergi.js"></script>
        <script>
            var data = Cynergi.get();
            console.log(data);

            //$.each( data, function( i, item ) {
            //  console.log(item);
            //});
            //console.log(data.data_returned);
        </script>
        <style>
                    #messages_modal{
                            position:fixed;
                            top: 30%;
                            left: 50%;
                            width:60%;
                            height:500px;
                            margin-top: -9em; /*set to a negative number 1/2 of your height*/
                            margin-left: -15em; /*set to a negative number 1/2 of your width*/
                            border-radius:15px;


                    }
                    #circular {
                        width: 40px;
                        height: 40px;
                        border-radius: 150px;
                        -webkit-border-radius: 150px;
                        -moz-border-radius: 150px;
                        background: url(images/avatar.jpg) no-repeat;
                    }
        </style>
        <!--[if lte IE 9]><link rel="stylesheet" href="css/ie/v9.css" /><![endif]-->
        <!--[if lte IE 8]><link rel="stylesheet" href="css/ie/v8.css" /><![endif]-->
    </head>
    <body>
                                <p style='text-align:left;align:left;' id='computer_info'></p></p>
                                <p style='text-align:left;align:left;' id='computer_stats'></p></p>

    </body>
</html>

console.log(data); outputs undefined

Grant Zukel
  • 1,153
  • 2
  • 24
  • 48
  • You need to use callbacks/promises for your function – MultiplyByZer0 Apr 02 '15 at 23:56
  • @MultiplyByZer0 an example? – Grant Zukel Apr 03 '15 at 00:08
  • 3
    possible duplicate of [How can I return a value from an AJAX request?](http://stackoverflow.com/questions/2956261/how-can-i-return-a-value-from-an-ajax-request) – Adam Jenkins Apr 03 '15 at 00:14
  • 2
    This is a dupe of about 1000 other questions on this site - returning data from an ajax/asynchronous request. – Adam Jenkins Apr 03 '15 at 00:14
  • @Adam there I added my attempt at a call back from that link you posted, what is wrong? – Grant Zukel Apr 03 '15 at 00:31
  • @Adam so I got a method of doing it to work but I can't seem to access the data. – Grant Zukel Apr 03 '15 at 00:58
  • @GrantZukel Look up Same origin policy, assuming of course that the url listed in your code is not a website you own. – Daedalus Apr 03 '15 at 01:00
  • @Daedalus the url im using is my rest service i own. This rest service is a database interaction rest service. Thus I'm writing a java script library to do dynamic put get delete post statements to the rest server that will add, retrieve and update the database with no server code. if you look at the console output I listed its listed under Here is the breakdown for the_data.data: Object {data: null, setData: function} data: Array[62] setData: function (data){ this.data = data;} __proto__: Object Then if I do the_data.data.data because data is where my array of info works but returns null. – Grant Zukel Apr 03 '15 at 01:35
  • @GrantZukel An ajax request is async.. Meaning you can't return data from it unless you halt the execution of the function until after the data is set. – Daedalus Apr 03 '15 at 01:55
  • ok thats cool an all but as you can probably tell im not that good at js, and that doesn't really help me because I'm not really sure as this is my first attempt at doing it. Examples are better the data is there but when ever I select.data I can see the data in the console out put of my return var but i cant get to it because its two layers deep – Grant Zukel Apr 03 '15 at 01:59
  • @GrantZukel As has already been said to you, this question is a duplicate of many questions on this site. An example of how to get around the async nature ajax requests has already been linked to you. Please read it. – Daedalus Apr 03 '15 at 02:03
  • and if you look I made the effort to go look at other questions and refine my question, obviously I didn't find the answer I was looking for or an understanding deep enough to understand my problem. – Grant Zukel Apr 03 '15 at 02:05
  • @GrantZukel There is no way I can tell what questions you have looked at, nor what specifically you are having a problem with, with what you looked at. – Daedalus Apr 03 '15 at 02:10
  • its the data structure can you not see the screen shot I posted – Grant Zukel Apr 03 '15 at 02:16
  • look at the second object its Object {data: null, setData:dunction} data: array[67] – Grant Zukel Apr 03 '15 at 02:17
  • @GrantZukel I don't see any real structure; you haven't clicked the arrows so all I can see is the initial, not the actual. – Daedalus Apr 03 '15 at 02:17
  • how do i get to the array – Grant Zukel Apr 03 '15 at 02:17

2 Answers2

0

Make this line work:

Cynergi.get(function (data) { console.log(data); });
Trindaz
  • 17,029
  • 21
  • 82
  • 111
0

You're not returning your data to Cynergie.get

Change this line:

function sendData(ret_data){ return ret_data; }

Or just add the return to your getData function and cut out the callback as long as you don't need to accept alternate callbacks.

btburton42
  • 3,307
  • 2
  • 13
  • 10