Veda Sadhak
Veda Sadhak

Reputation: 424

jQuery, Ajax getting data from a database

I am trying to get data from an SQL Database through jQuery, Ajax and PHP.

Here is the jQuery Code

$.ajax({
    url: 'OpenQuiz.php',
    data: '',
    dataType:'json',
    success: function(data) {
        var one = data[0];
    }
}

$(document).ajaxComplete(function(event,request,settings) {
    alert("check");
}

Here are the json encode lines at the end of the PHP file called "OpenQuiz.php"

echo json_encode($QuizName);
echo json_encode($options);
echo json_encode($votes);
echo json_encode($row_num);
echo json_encode($percentage);
echo json_encode($TruncPercentage);

Please note: $options, $votes, $Percentage and $TruncPercentage are all two-dimensional arrays. $row_num is an integer. $Quiz_Name is a single-dimensional array.

I find that the jQuery runs fine and the ajax request is called because the alert box for "check" shows up. The problem is that I dont know how to access the variables after they have been transferred. I know that it has something to do with data[0] but I don't really understand what "data[0]" means or what it represents. Basically how to I access the variables that I have sent using json_encode in the PHP file?

Upvotes: 0

Views: 400

Answers (1)

PlantTheIdea
PlantTheIdea

Reputation: 16359

data[0] is the first json_encoded item in the array returned. You shouldn't json_encode everything separately, you should build an array and json_encode this.

$items = array('QuizName'=>$QuizName,'options'=>$options, ... ,'TruncPercentage'=>$TruncPercentage);

echo json_encode($items);

Then you retrieve with:

success: function(data) {
    var qn = data.QuizName,
        opt = data.options;
}

And so on for each item, with data.[whatever], and [whatever] being the name of the item you gave it in the array. I know I originally said to retrieve by index (data[0]), but I prefer to retrieve explicitly so that the code is more maintainable.

As a side note, you can eliminate the datatype:'json' declaration in your ajax call by simply setting the header correctly on the PHP side:

header('Content-type: application/json');

Placing that at the top of the document will force the server to recognize the page as json. Far more consistent and explicit than having jQuery look for it.

Upvotes: 1

Related Questions