Friday, 9 August 2013

$.ajax in a for loop pulling from a php file

$.ajax in a for loop pulling from a php file

I have a key_gen.php file that contains a functions 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 (: 3,9,10), I do
get the console.log message but the number generated is the same.
I was hoping that by putting the ajax in a for loop it would execute the
ajax call several time. I tried to put the ajax call within a prototype
function with the same result.
Thanks.

No comments:

Post a Comment