0

I have a key_gen.php file that contains a function to generate a random key. When executed, the php file gives back one key (tested and it works).

In my javascript file I have a click event on a button (that works), something like this:

$('#kg_btn').click(function(){});

Then, inside my click event I have a functions:

         var get_key = function(){
            for(var i = 0; i < kg_quantity; i++) {
                $.ajax ({
                    url: "../keygen/gen_rkey.php",
                    type: "GET",
                    datatype: "json",
                    success: function(data) {
                        var j_obj = JSON.parse(data);
                        //alert("Success!");
                        prs = j_obj.test;
                        console.log(prs);
                        //add_key();

                    },
                    error: function(error) {
                        alert("Error! Can't send the data");
                    }
                }); //ajax call ends 

            }
        }

When I run this function once (by setting up the "Kg_quantity" variable to 1), every time I click my button I get a correct behavior. The result is a different key on the console.log per click.

If I set up the "kg_quantity" to any other number than 1 (for example: 3,9,10), I do get the console.log messages back, but the number generated is the same.

I was hoping that by inserting the ajax object into a for-loop would execute the ajax call several times. I tried to put the ajax call within a prototype function, as well, but I get the same result.

Edit: I tried adding a closure (as Ross suggested), but I get the exact same result.

Thanks.

3
  • It could be a caching problem, try passing a parameter to the url that's different every time and see if it helps. Commented Aug 9, 2013 at 17:22
  • Do you realy need to use JSON.parse(data)? Doesn't jquery read the json automaitcally? Why don't you send the number of keys you need in a single request, then insert inside an array and send them back? After this you can loop through data Commented Aug 9, 2013 at 17:23
  • Dheed7, thanks for your answer.The key_gen process is triggered by a js process. I do not know how many keys will be generated (before-hand). On the same page there is an input field and a button. Based on the number the user inserts into the input-field. Ideally, I would have a function that would retrieve as many random-keys as needed through a loop. Commented Aug 9, 2013 at 17:33

1 Answer 1

3

AJAX is asynchronous. Your loop will finish before the first AJAX response most likely.

I would restructure that so the success response from the AJAX call will trigger the next iteration. Or if you're lazy you can just set async:false:

$.ajax ({
    url: "../keygen/gen_rkey.php",
    type: "GET",
    async: false,
    ....

Or even better, put the strain on the server and reduce the back-and-forth so you get all your keys in one response:

url: "../keygen/gen_rkey.php?qty=" + kg_quantity,

UPDATE: Async design method:

function getKeys(max,cur) {
    cur = cur || 1;
    if (cur == max) {
        return;
    }
    $.ajax({
        ....
        success(function(data) {
             // do stuff....

            // recursive iteration
            getKeys(max,cur + 1);
        }
    });
}
getKeys(5);
Sign up to request clarification or add additional context in comments.

1 Comment

AlienWebguy, thanks for your answer. I'd love to be able to keep it asynchronous. Can you give me a very simple, fast example on how to have the success affect the loop?

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.