1

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;
?>
Andrew Bruce
  • 123
  • 3
  • 15
  • See: http://stackoverflow.com/questions/21897398/how-do-i-debug-jquery-ajax-calls – Tim Grant Nov 20 '16 at 18:08
  • why are you using `return` in `document ready function` ? Also you can add `success` and `error` callbacks to `$.ajax` – Michael Yousrie Nov 20 '16 at 18:08
  • Like I said I'm new to Ajax but saw that way of returning the data somewhere online. What would be the best way to return the data? – Andrew Bruce Nov 20 '16 at 18:12
  • @AndrewBruce Did you see the solution I posted? I made some changes and I got it working :). Please let me know if you need anything. – HenryDev Nov 20 '16 at 23:29

3 Answers3

1

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

pradeep1991singh
  • 8,185
  • 4
  • 21
  • 31
  • Thanks for the tip! Although I've altered the code and it still doesn't seem to be echoing $answer :/ – Andrew Bruce Nov 20 '16 at 18:23
  • That's still not working unfortunately, it's doesn't seem to be logging anything in the console either with that code. Should it be? – Andrew Bruce Nov 20 '16 at 22:21
  • @AndrewBruce did you see the solution I posted? I made some changes and I got it working :). Please let me know if you need anything. – HenryDev Nov 20 '16 at 23:23
0

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.

Christos Lytras
  • 36,310
  • 4
  • 80
  • 113
0

There 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>
HenryDev
  • 4,685
  • 5
  • 27
  • 64
  • Hi @HenryDev , thanks very much for your answer! I managed to get it printing the number fine but now when I'm trying to use the $data variable in another conditional statement it doesn't seem to work. The idea is that the Javascript generates a random spam question and if they answer it correctly it sends an email. i.e. - if ($spam == $data) { mail($to,$subject,$message,$headers); etc etc } It doesn't even seem to echo the number anymore when that extra code to mail is in there. I feel like I'm doing something totally wrong but I'm not very sure! – Andrew Bruce Nov 21 '16 at 14:34
  • @AndrewBruce I'm not really sure how you implemented your send email function, but I think my job is done. I did what you asked which is being able to send the random number to PHP. At least I deserve you accept my answer as the correct one for spending some time trying to help you :). Thanks – HenryDev Nov 21 '16 at 16:33