简体   繁体   中英

Pass JavaScript into PHP using Ajax

I'm attempting to pass a JavaScript function into a php file using Ajax, as far as I can see my Ajax syntax is right but it doesn't seem to work. This is the first time I've tried to use Ajax so any help would be much appreciated.

I made some test files just to test if the Ajax code passes the variable and I'll put it below -

script.js -

var number1 = Math.round(Math.random() * 6) + 1;
var number2 = Math.round(Math.random() * 6) + 1;
var randomAnswer = number1 + number2;

$ (document).ready(function() {
return $.ajax({
    url: 'index.php',
    type: 'POST',
    data: randomAnswer,
    });
});

index.php -

<script src = "jquery-3.1.1.min.js"></script>
<script src = "script.js"></script>

<?php
$answer = $_POST ['randomAnswer'];
echo $answer;
?>

There is small issues i can see is - dataType is missing and wrong data formatting, see code below -

$ (document).ready(function() {
 $.ajax({
    url: 'index.php',
    type: 'POST',
    dataType:'json', 
    data: ({randomAnswer: randomAnswer}),
    success: function(data) {
       console.log(data);
    }
  });
});

Hope this will help you in some way (y).

You should have a complete interface in order to display the returned data, or just have some debug function calls like console.log to view the returned data. Here is a sample script page based on your code that has a button to do the ajax call, and have the result displayed inside a div:

HTML

<div id="output">0</div>
<button id="getOutput">Get AJAX Random Answer</button>

PHP At the beggining of the PHP file, before the <!DOCTYPE html> tag

<?php
if(isset($_POST['randomAnswer'])) {
    $answer = $_POST['randomAnswer'];
    die($answer);
}
?>

jQuery Javascript

$(document).ready(function() {
    $('#getOutput').on('click', function() {
        var number1 = Math.round(Math.random() * 6) + 1;
        var number2 = Math.round(Math.random() * 6) + 1;
        var randomAnswer = number1 + number2;

        $.ajax({
            url: 'numecho.php',
            type: 'POST',
            data: {
                randomAnswer: randomAnswer
            },
            complete: function(data) {
                $('#output').text(data.responseText);
            }
        });
    });
});

Now you have your random generated number sending to your server side PHP script and then returning the value back displaying it to an html div element.

T here are many ways to solve this.

1.- First let's make sure we were able to post data to PHP by doing this in Ajax:

success: function (result) {
    alert("result: " + result);
}

2.- I have tested your code and made some changes to the PHP code as well.

3.- Now everything seems to be working fine :).

Just copy and paste this entire code below and you will see the results (create a file and called it index.php).

 <?php

   $data = array();
   if(isset($_POST['randomAnswer']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
   $data = 'You number is: ' . $_POST['randomAnswer'];       
   echo json_encode($data);  
   die();      
    }
 ?>
 <html>
 <head>
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
 </head>

 </body>
 <div id = "random"></div>

 <script type = "text/javascript">

$(document).ready(function() {

var number1 = Math.round(Math.random() * 6) + 1;
var number2 = Math.round(Math.random() * 6) + 1;
var randomAnswer = number1 + number2;

$.ajax({
   url: "index.php",
   method: "POST",
   dataType: "json",
   data: {randomAnswer: randomAnswer},
   success: function (result) {
      alert("result: " + result);
      $("#random").html(result);
   }
 });

});

</script>

</body>
</html>

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