views:

222

answers:

1

updated: i use this:

$.getimagesarr = function(operation) {
  return $.ajax({
      type: 'POST',
      url: 'operations.php',
      data: {'operation':operation},
      async: false
    }).responseText
}


var jsonstring = $.getimagesarr('getimg');
var data = (new Function("return " + jsonstring))() 
if (data){
   ....
}

old: i want to pass a php aray to jQuery:

$.getimagesarr = function() {
    $.getJSON('operations.php', {'operation':'getimglist'}, function(data){
        var arr = new Array();
        arr = data;
        return arr;
    });  
}

var data = $.getimagesarr();
if (data){
 jQuery.each(data, function(i, val) {
     ....
    });
}

it return undefined

in php i have this:

function getimglist(){
    $results = $_SESSION['files'];
    echo json_encode($results);
}

it is possible?

+1  A: 

The return arr; line isn't going to return a value for the $.getimagesarr function. It's going to execute asynchronously, after the $.getJSON() call has finished. You should move the bottom area of code to within the success event handler for the $.getJSON() call:

$.getimagesarr = function() {
    $.getJSON('operations.php', {'operation':'getimglist'}, function(data){
        if (data){
            jQuery.each(data, function(i, val) {
                ....
            });
        }
    });  
};
awgy
i really need a function, i use this in more places, i don't want to put all this code 3..4... times!how to return a value in a variable?something like this: var data = $.getimagesarr();
robertdd
To do that you would need to use a synchronous AJAX call, which brings with it a lot of evil. It can cause performance issues in the browser and/or cause the browser to hang. I would **strongly** advise against that route.An event-based approach, though painful for any refactoring you may have to do, is the way to go. I mean, "asynchronous" is literally the first letter of the acronym "AJAX" (Asynchronous JavaScript And XML).
awgy
i edited the question! is that a safe way to do this?
robertdd
I believe that should work, but remember that it will block execution of your script while it waits for the data. I would still strongly suggest you consider refactoring to accomodate using an asynchronous request.
awgy