I am trying to get data from a PHP page with ajax and then store it in a variable used for a while loop.

I have used the data to output the number on the screen so I know it is working however when using the variable for a while loop it's not working.

function viewl(){
    var counter = 1;
    var amount = null;
    url: 'amountl.php',
    success: function(data){
        amount = parseInt(data);

    while(counter <= amount){

    var name = "";
    var cost = "";
    var archetype = "";
    var rarity = "";
    var ability = "";
    type: "GET",
    data: {name: name, cost: cost, archetype: archetype, rarity: rarity, ability: ability},
    url: 'viewl.php',
    success: function(value){});

Some of the code is still left out because it is too much and the site won't let me post it all.

1 Answers

Merioles On

It looks like your PHP code is trying to return an HTML document, hence you cannot read the value as is. In viewl.php, you should try to return the response in JSON format.

// amountl.php
$data = array( "amount" => 5 );
header('Content-Type: application/json');
echo json_encode($data);
// json_encode will convert the array to { "amount" : 5 }

Then in our Javascript code, modify the success function.

url: 'amountl.php',
dataType: 'json',
success: function( data ) {
    amount = parseInt( data.amount );