简体   繁体   中英

Pass JavaScript function through Ajax to PHP file

What I am trying to do:

I am working on a script intending to offer the user choices and depending on which choice they make, come up with a new choice. I have made two scripts for this, one for my HTML and the structure of my page and one for my PHP (getting the information from my server) and JavaScript (building the generated choices).

I am then using AJAX to communicate between these two scripts, or at least, that's what I am trying to do, but I am very new when it comes to AJAX and I cannot make it work.

I am trying to pass or somehow start the function 'generateProblems' from my page when one of the 3 buttons are pressed, preferably with the param 'id' .

Here's part of my index.html:

            <div id="testpile" class="inner cover">
                <div id="buttons">
                    <p><a id="rat" class="btn btn-default" role="button">Rationel</a></p>
                    <p><a id="emo" class="btn btn-default" role="button">Emotionel</a></p>
                    <p><a id="per" class="btn btn-default" role="button">Personel</a></p>
                </div>
            </div>

            <div id="testdrop" class="mastfoot">
                <p>Drop numbers here</p>
            </div>

<script type="text/javascript">
    $("#buttons").find(".btn").click(function() {
        var id = this.id;
        $("#testpile").load("include/responseget.php");
        $.post("include/responseget.php", {
            choice: "id",
        });
    });

</script>

And here's my PHP / Javascript:

<?php  include 'login.php';
//Query til at finde information til generation af question
$stmt = $conn->prepare("SELECT DISTINCT ResponseTitle, ResponseText FROM response Limit 8;");
$stmt->execute();
$result = $stmt->get_result();

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

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

// close connection
mysqli_close($conn);
?>
<script type="text/javascript">
    $(function() {
        var phase = 0;
        var rTitle = <?php echo json_encode($rTitle_array); ?>;
        var rText = <?php echo json_encode($rText_array); ?>;

        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 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);

            }
        }

    });

</script>

What am I doing wrong? The code worked pretty well before I split it up, but now clicking one of the buttons generate nothing.

This is not the right way to do. Keep your php away from html/js. You can't access to your html from another script which is not directly included in it.

  1. Re-add your javascript part to index.html
  2. In your php script return something at the end like return json_encode($rTitle_array);
  3. In your jquery/ajax post, get the returned value and use it

A sample from the jquery doc:

  var posting = $.post( url, { s: term } );

  // Put the results in a div
  posting.done(function( data ) {
    var content = $( data ).find( "#content" );
    $( "#result" ).empty().append( content );
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM