views:

298

answers:

5

I have the following code

function updateSliderContent(json) {  //<- json defined here is correct
   var screen_order = json.screen_order.split('_');
   jQuery.each(screen_order, function(i, item) {
      var screen_id = item;
      //at this point it is not, thus the function does not execute whatever is in the if blocks
      if (json[screen_id].action == 'add') {
         //doSomething  
      } else if (json[screen_id].action == 'remove') {
         //doSomthingElse
      };
   }
}

My problem is that somehow, the value of json (which is an object from an AJAX Call) gets lost in the each function of jquery. I have not yet found out why, nor how to solve it. Google does not give me the answer I am looking for.

Edit 1

Here is the actual call.

function updateSlider() {
   var screenOrder = '';
   jQuery('div#slider td').each(function(i, item) {
      screenOrder += this.abbr + '_';
   })
   var ajaxData = {
      sid: sid,
      story: story,
      date: theDate,
      screenOrder: screenOrder,
      mode: 'ajax_update_slider'
   };
   jQuery.ajax({
      data: ajaxData,
      dataType: 'json',
      success: function (json) {
         updateSliderContent(json);
      }
   });
   theDate = Math.round(new Date().getTime()/1000.0); //UNIX Timestamp
   sliderTimer = setTimeout('updateSlider();',15000);
};
A: 

Are you sure json is an object. Maybe its a json-string? Than you should eval it before use.
If you get it via $.ajax() call don't forget to add dataType:'json' as an option...

NilColor
Try this: function updateSliderContent(json) { alert(typeof json); //<-- here you get an alert with json type. if its string then you found your error jQuery.each(screen_order, function(i, item) { ...
NilColor
I used dataType and set it to json. I actually have it defined in jQuery.ajaxSetup() since 90% of my calls all expect json as result.
Mike
typeof returns "object"
Mike
A: 

tray in the if() clause to use item.action, because if the json data is an array of objects, item will contain each object, but this is only my assumption

bozhidarc
+1  A: 

There seems to be nothing wrong with the jQuery.each as I can't reproduce your problem.

        function alertName (json) {
            var a = new Array();
            a.push(1);
            a.push(2);

            jQuery.each(a, function(i, item) {
                alert(json[0].name);
                alert(json[1].name);
            });
        }

        var andre = { name: "André" }
        var joana = { name: "Joana" }

        var arrayOfJson = new Array();
        arrayOfJson.push(andre);
        arrayOfJson.push(joana);

        alertName(arrayOfJson);

alertName() function works exactly as it should. The json parameter isn't lost within jQuery.each function

It seems to be a problem on your implementation, something you're not telling us about. Please try to "compress" your issue to a working sample as I did and show us so that we can try in on our own :)

Ciwee
That's odd, because this is basically what I am trying to do with the object. The function I provided is actually almost the entire thing. What I removed was the actual call, which you simulated in your example, except thatjson is an Object and not an Array.
Mike
A: 

I think you should make sure the function updateSliderContent is called after the json response from the server side.

The code below shouldn't work:

    var json = {};

    $.getJSON("/url/", {}, function(data){
        json = data;
    });

    //we call our function before the server response
    //and the json will be just blank object
    updateSliderContent ( json );

So, please have a look at your code because sometimes we did something like that without intention.

The code below should work and the json object must not be blank if the server really response the correct json.

    $.getJSON("/url/", {}, function(json){
        //we call only after the response from server
        updateSliderContent ( json );
    });
max
I have done that. See Edit 1.
Mike
+2  A: 

I've attempted, and failed, to reproduce your problem on JS Bin:
http://jsbin.com/ereha (editable via http://jsbin.com/ereha/edit)

The code you've shown us so far seems perfectly fine, so the problem must be caused by some other part of your code or system. We're all just shooting in the dark if we don't know what the issue is.

Please try and reproduce the problem on http://jsbin.com and we can help you from there.

Complete Source Code

index.html

<!doctype html>
<html lang="en">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>http://stackoverflow.com/questions/1831384/javascript-variable-value-gets-lost-between-functions&lt;/title&gt;
    <script type="text/javascript" src="http://getfirebug.com/releases/lite/1.2/firebug-lite-compressed.js"&gt;&lt;/script&gt;
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"&gt;&lt;/script&gt;
    <script type="text/javascript">
      $.ajaxSetup({url: 'test.json'});

      function updateSliderContent(json) {  //<- json defined here is correct
        var screen_order = json.screen_order.split('_');
        jQuery.each(screen_order, function(i, item) {
          var screen_id = item;
          //at this point it is not, thus the function does not execute whatever is in the if blocks
          if (json[screen_id].action == 'add') {
            console.log(screen_id, 'action add');
          } else if (json[screen_id].action == 'remove') {
            console.log(screen_id, 'action remove');
          };
        });
      }

      function updateSlider() {
        var ajaxData = {};
        jQuery.ajax({
          data: ajaxData,
          dataType: 'json',
          success: function (json) {
            updateSliderContent(json);
          }
        });
        // theDate = Math.round(new Date().getTime()/1000.0); //UNIX Timestamp
        sliderTimer = setTimeout('updateSlider();',15000);
      };

      $(updateSlider);
    </script>
  </head>
  <body>
  </body>
</html>

test.json

{
  'screen_order': 'foo_bar_baz',
  'foo': {
    'action': 'add'
  },
  'bar': {
    'action': 'add'
  },
  'baz': {
    'action': 'remove'
  }
}
brianpeiris
I have tried to also reproduce the problem on my local server but couldn't... Even if I revert to the version I had my problems with I cannot seem to reproduce it. I'll give you a correct answer for your trouble... still, I cannot understand why it works now...
Mike