Karem
Karem

Reputation: 18103

JS: Changing variable wont apply on next

I have this:

$('#albumPhotoNext').live('click', function () {
var currentDate = '<?php echo $grab["date"]; ?>';
    $.ajax({
    url: "photo.php",
    type: "post",
    data: { currentDate : currentDate },
    success: function(r){
    currentDate = r.date;
    }
    });
});

I want to set currentDate for the r.date, on success, so next time you click on #albumPhotoNext, the currentDate is the r.date.

Right now it gives me the $grab["date"]; when i click, no matter if i did set the currentDate to r.date or not.

I only want to have $grab["date"]; as "default" if it hasnt been set to r.date

How can I do this?

Upvotes: 0

Views: 71

Answers (3)

brian-d
brian-d

Reputation: 803

I would approach this in a slightly different way. Instead of assigning "currentDate" to a variable, just use another jQuery selector to set the current date on the page itself.

$.('#albumPhotoNext').live('click', function () {
    $.ajax({
    url: "photo.php",
    type: "post",
    data: { currentDate : currentDate },
    success: function(r){
        $.('#dateOnPage').html(r.date);
    }
    });
});

Upvotes: 0

Felix Kling
Felix Kling

Reputation: 816364

You have to define currentDate in a scope that is reachable from the scope you want to use it. Currently, currentDate is local to the event handler, so only the code inside the event handler can see the value and it gets reassigned to $grab["date"] every time the handler is called.
Define it in some scope above, e.g. in the document ready handler:

$(function() {  
    var currentDate = '<?php echo $grab["date"]; ?>';

    $('#albumPhotoNext').live('click', function () {       
        $.ajax({
        url: "photo.php",
        type: "post",
        data: { currentDate : currentDate },
        success: function(r){
        currentDate = r.date;
        }
        });
    });   
});

Upvotes: 0

Jacob Relkin
Jacob Relkin

Reputation: 163238

currentDate is a local variable, so its value gets reset every invocation.

You will need to make the variable exist in an outer scope for your changes to persist.

The easy way of doing this:

$(function() {
   var currentDate = '<?php echo $grab["date"]; ?>';
   $('#albumPhotoNext').live('click', function () {
      $.ajax({
         url: "photo.php",
         type: "post",
         data: { 'currentDate' : currentDate },
         success: function(r){
            currentDate = r.date;
         }
      });
   });
});

Upvotes: 2

Related Questions