Join the Stack Overflow Community
Stack Overflow is a community of 6.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
up vote 3 down vote accepted

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;
    }
});
share|improve this answer
    
Thank you very much for you answer, I understand why I wasn't getting anywhere, cause the script is handled as a single response. Also, when you say 'output it', do you then mean: "echo json_encode($response);"? Cause right now, doing "alert('rTitle = "' + rTitle + '", rText "' + rText + '" ');" after my AJAX, shows both arrays as undefined? Again, thank you for your time and answer! – user2304993 May 22 '16 at 15:05
    
@user2304993 yes, I did mean that. I'll update my answer to clear it out. – lolbas May 22 '16 at 15:06
1  
@user2304993 the first letter of AJAX technology stands for "asynchronous". Hence, if there is some code in function after ajax call, it will be executed immediately unless we specify async: false in request params. So, calling function first time and executing alert code will have variables be undefined. – lolbas May 22 '16 at 15:32
1  
@user2304993 it will stop execution of parent function so using async: false should only take place where it really needs to be. Like if you need to update some parameters of global objects and you depend on ajax call results, you should use async: false to work with latest results. However, such requests as POST used to just update information on server should be async. – lolbas May 22 '16 at 15:37
1  
@user2304993 call it within success of ajax call? I'm not really familiar with your task so this is all I can think of atm. – lolbas May 22 '16 at 15:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.