-1

Why does my ajax not work?

These are my pages.

I'm using JQuery to check click event and using ajax to load the responder page.

What is wrong in this code?

index.php

<html>
  <head>
    <title>Test</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
      $(document).ready(function() {
          $('#clicket').click(function() {
            $.ajax({
              url: 'res.php?rand=' + Math.random(),
              type: 'GET'
              success: function(results) {
                alert(results);
              }
            });
          });
        });
      </script>
    </head>
  <body>
    <button id="clicket">Hi</button>
  </body>
</html>

Responder page:

res.php:

<?php
  echo "Worked!";
?>

UPDATE: I changed my javascript code above.

zx485
  • 28,498
  • 28
  • 50
  • 59
  • 2
    You're binding is in the head before the markup is defined; and it isn't in a document ready. So the selector will not find any elements to bind upon as the DOM has not been fully built yet. – Taplar Dec 13 '17 at 19:09
  • You forgot to wrap your jQuery code in the document's ready event: `$(function () { ... });` Conversely, you can put your jQuery code at the end of the HTML instead of the beginning. – David Dec 13 '17 at 19:11

2 Answers2

1

Put your logic in a document ready. Since your script is in your head, the markup in the body hasn't been loaded into the DOM yet. In order to make your script wait until the DOM has been built, put the logic in a document ready to delay it until that time.

$(document).ready(function() {
  $('#clicket').click(function() {
    $.ajax({
      url: 'res.php?rand=' + Math.random(),
      type: 'GET',
      success: function(results) {
        alert(results);
      }
    });
  });
});
Taplar
  • 24,788
  • 4
  • 22
  • 35
-3

Try using full URL for your ajax call. If you are on live server then write your full domain name, like www.your_domain.com/res.php?rand=.