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;
?>
4
  • See: stackoverflow.com/questions/21897398/… Commented Nov 20, 2016 at 18:08
  • why are you using return in document ready function ? Also you can add success and error callbacks to $.ajax Commented Nov 20, 2016 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? Commented Nov 20, 2016 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. Commented Nov 20, 2016 at 23:29

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the tip! Although I've altered the code and it still doesn't seem to be echoing $answer :/
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?
@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.
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>

2 Comments

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!
@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
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.