user2304993 user2304993 - 6 months ago 48
Ajax Question

Pass multiple arrays from PHP through jQuery AJAX to Javascript

What I am trying to do:

I am trying to pass the ID of the button pressed to my PHP script through jQuery AJAX.

I then use the information to run a query that returns 2 rows, I save each as an array, respectively $rTitle_array[] and $qTitle_array[], I json_encode each and I then want to send them back to my index.html and use them in my generateProblems function.

I sadly cannot figure out how to pass them back and then use them.

Here's my Javascript:

$(function() {
//Take id of the button pressed and save it as userID
$("#buttons").find(".btn").click(function() {
var userID = this.id;
$.ajax({
type: "POST",
url: 'include/responseget.php',
data: {
userID: userID
},
success: function(data) {
alert("success!");
}
});
});

var phase = 0;
var rTitle = <?php echo json_encode($rTitle_array); ?>;
var rText = <?php echo json_encode($rText_array); ?>;

//Function to generate html based on query results
function generateProblems(param) {
var problemDef = param;
$("#buttons").hide();
var numbers = [1, 2, 3, 4, 5, 6, 7, 8];
for (var i = 0; i < 8; i++) {
$('<div>' + rTitle[i] + '</div>').data('number', rTitle[i]).attr('id', 'problem' + rTitle[i]).appendTo('#testpile').draggable({
containment: '.site-wrapper',
stack: '#testpile div',
cursor: 'move',
revert: true
});
$('<div>' + rText[i] + '</div>').data('number', rText[i]).attr('id', 'problem' + rText[i]).appendTo('#testpile');
}


$('#testdrop').droppable({
drop: handleDropEvent,
accept: '#testpile div'
});

//Function to restart generateProblems when draggable is dragged to specific place
function handleDropEvent(event, ui) {
var problemNumber = ui.draggable.data('number');
var problemCombination = problemDef + problemNumber;
ui.draggable.draggable('disable');
ui.draggable.draggable('option', 'revert', false);
phase++;
alert('ProblemCombination is "' + problemCombination + '", phase is "' + phase + '" ');
$("#testpile").children().hide();

generateProblems(problemCombination);

}
}
});


And here's my PHP:

<?php include 'login.php';
if(isset($_POST['userID'])){
$id = $_POST['userID'];
$stmt = $conn->prepare("SELECT DISTINCT AnswerTitle, AnswerText FROM question_answers
INNER JOIN question
ON question_answers.QuestionID=question.QuestionID
INNER JOIN answer
ON question_answers.AnswerID=answer.AnswerID
WHERE AnswerGroup = ?;");
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();

while($row = $result->fetch_assoc())
{
$rTitle_array[] = $row['AnswerTitle'];
$rText_array[] = $row['AnswerText'];
}

echo json_encode($rTitle_array);
echo json_encode($rText_array);
}

// close connection
mysqli_close($conn);
?>


I simply do not know how to fetch or pass the arrays back to my Javascript correctly, so I can use them for my function.

Any help, tips or such will be very greatly appreciated, thanks in advance.

Answer

The data outputted by scripts is handled as single response from your script. What you can do is combine two arrays on server side to look like:

$response = array(
    'rTitle' => $rTitle_array,
    'rText'  => $rText_array
);

Then perform json_encode on this combined array and output it. So, instead of

echo json_encode($rTitle_array);
echo json_encode($rText_array);

you write

echo json_encode($response);

Now as for client side, one of possible ways to handle response is:

  1. Change your $.ajax request so that it will say the server that we wait a response in json format by setting dataType param to 'json'.
  2. Treat your success data as json!

Example:

var rTitle, rText;

$.ajax({
    type: "POST",
    url: 'include/responseget.php',
    dataType: 'json',
    data: {
        userID: userID
    },
    success: function(json) {
        rTitle = json.rTitle;
        rText  = json.rText;
    }
});