-2

OK, so I'm reading the contents of my data file, where I have stored display width, display height, image width, image height. I'm trying to store these values into variables, that I can use in other functions on my page. Having heard that global variables are a bad idea, I created this object:

        var slidedata = {dw:null,dh:null,rw:null,rh:null}

I get to this part, within a function:

        slidedata.dw = d[o].dispWidth; // How do I do this?

When I do alert(slidedata.dw);, later on, I get null, meaning I haven't changed the value of slidedata.dw. I checked, when I alert(d[o].dispWidth);, I get an OK value (307), so that's not the problem. The problem is that I don't know how to change the value of slidedata.dw. HOW DO I DO THIS?

FULL CODE:

 <script type="text/javascript">
    var slidedata = {dw:null,dh:null,rw:null,rh:null}
    function ajaxjson(folder){

    var info = document.getElementById("info-wh");
var hr = new XMLHttpRequest();

hr.open("POST", "gallery_data.php");
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
    if(hr.readyState == 4 && hr.status == 200) {
        var d = JSON.parse(hr.responseText);
        for(var o in d){
            if(d[o].src == $('.image').attr('src')){


               slidedata.dw = d[o].dispWidth; 
    // HERE I'M TRYING TO SET slidedata.dw TO BE d[o].dispWidth
    // d[o].dispWidth RETURNS 307

               slidedata.dh = d[o].dispHeight;
               slidedata.rw = d[o].realWidth;
               slidedata.rh = d[o].realHeight;


              }
            }
         }
       }
     hr.send("folder="+folder);
    }
    </script> 

    </head>

    <body>

    <div id="info-wh"></div>
    <div id="info-cd"></div>
    <script>ajaxjson('slides');</script>
    <script>alert(slidedata.dw);</script> <!-- THIS RETURNS NULL -->
    <img class="image" alt="" border="0" src="slides/slide1.jpg" 
         style="width:400px; height:600px; left:200px; top:25px; position:relative;" />
Knight1805
  • 121
  • 1
  • 10
  • Is `d[o].dispWidth)` just a typo in the post? – RobG Jul 05 '15 at 08:16
  • should work, without the extra closing bracket.. – Jordan Davis Jul 05 '15 at 08:17
  • It is unclear what your question is asking. `slidedata.dw = 3;` will change the value of `slidedata.dw`. I suspect you will have to show much more of your code for us to follow what the question and problem are. – jfriend00 Jul 05 '15 at 08:22
  • @RobG it was a typing error. Thanks for your interest so far... – Knight1805 Jul 05 '15 at 12:28
  • @jorjordandan it was a typing error. Thanks for your interest so far... – Knight1805 Jul 05 '15 at 12:29
  • @jfriend00 it was a typing error. Thanks for your interest so far... full code uploaded. – Knight1805 Jul 05 '15 at 12:29
  • Right after the line `var d = JSON.parse(hr.responseText);` add a `console.log(d)` and report here exactly what that shows. We need to know what `d` is in order to help here. Also, do you only have one `.image` object in your page? or multiple ones? – jfriend00 Jul 05 '15 at 14:42
  • @jfriend00 OK, so oddly enough, it returns [object Object], as does console.log(d.img1). var d represents data, and o is object, to make things clearer. Once again, d[o].dispWidth returns the right value, so I think my main problem is that I don't know how to make the variables d[o].dispWidth and others global. Here is the output of gallery_data.php. [link](http://www.mega.co.rs/gallery_data.php). Now I think, you'll see this clearer. I have only one .image on the page, and I'm certain that the non-javascript part is OK. – Knight1805 Jul 05 '15 at 15:14
  • "global" sends off a warning signal here. Your ajax call is asynchronous. The only place you can use the result from the ajax call is inside your readyState handler. If you're trying to stuff it into a global variable and then immediately use it, that will not ever work because of the asynchronous timing of the result.. You are probably trying to access the `slidedata` properties BEFORE the ajax call has completed. Put the code that uses that data inside the readyState handler callback or in a function you call from that. – jfriend00 Jul 05 '15 at 15:55
  • Also, see this [How to return data from an Ajax call](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) to further understand. If, from the start, you showed us the code where you're trying to use the `slidedata` result (which you still haven't disclosed), this would have been immediately clear from the start. – jfriend00 Jul 05 '15 at 15:56

2 Answers2

0

First off, you don't need to define every property of the object beforehand:

var sldiedata = {};
console.log(slidedata.dw); // undefined

Will give you the same functionality as

var slidedata = {
   dw: null
}
console.log(slidedata.dw); // null

Section of answer removed due to added informations making it irrelevant. For reference it was:

Then you wrote

slidedata.dw = d[o].dispWidth)

And it's full of typos. Maybe you mean

slidedata.dw = d[0].dispWidth();
Alberto
  • 399
  • 1
  • 6
  • 19
  • Thank you for answering. It's not full of typos, the only typo was that bracket :) I've uploaded the full code, so you could see. What's wrong here? – Knight1805 Jul 05 '15 at 12:31
  • @Knight1805 Ok your poblem is that you are treating asyncronous code like async. Let me explain: – Alberto Jul 05 '15 at 15:59
  • You are checking the value of "slidedata" BEFORE it is available: the AJAX request will take time to lead and it's not immediately available. What you need to research and know is callbacks. I will link a corrected version of your code soon – Alberto Jul 05 '15 at 16:04
  • There is no point in correcting your code. I think you will learn more by reading this article: http://javascriptissexy.com/understand-javascript-callback-functions-and-use-them/ Also, note that if you are already using jQuery, use the [jQuery.post](http://api.jquery.com/jquery.post/) method instead. – Alberto Jul 05 '15 at 16:17
  • So, for 8 of the last 14 hours, I've been trying to get this code right... and failed miserably. At least, I get how callback works and everything... I guess it's my knowledge of the JS syntax that's bogging me. I can't seem to code the handler callback, and I'm getting tired of it. Could you please post a corrected version of my code, just so I could see a direct example of what works, and why. – Knight1805 Jul 06 '15 at 07:24
  • @Knight1805 There is no point in correcting you code, it's completely wrong. Research the following questions: Do you need a POST request in this scenario? (you don't) Use jQuery more! Read the jQuery.post API documentation, it's full of examples. – Alberto Jul 06 '15 at 08:12
0

OK, so I finally found the solution to the problem by using the jquery.post function and setting the async option to false. Thanks to anyone who commented on the topic and help me learn something new... I hope the reader will too.

I've just renamed the function, the JS looks like this:

<script>
  var slidedata = {dw:null, dh:null, rw:null, rh:null};

  function readData(){
     $.ajax({
     async: false, 
     url: 'gallery_data.php',
     success : function(data){   
              var id = $('.image').attr('src');
              id = id.replace('slides/slide','');
              id = id.replace('.jpg','');
              slidedata.dw = data['img' + id].dispWidth;
              slidedata.dh = data['img' + id].dispHeight;
              slidedata.rw = data['img' + id].realWidth;
              slidedata.rh = data['img' + id].realHeight;
          }

     });
  }
</script>
Knight1805
  • 121
  • 1
  • 10