0

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 Answer 1

1

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) {
                ....
            });
        }
    });  
};
Sign up to request clarification or add additional context in comments.

3 Comments

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();
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).
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.