Javascript – JQuery Ajax call to be triggered onClick

ajaxhtmljavascriptjquery

I am new to JavaScript, Jquery and Ajax. This is what I am trying to do:

I have a button in my HTML code, and I want to trigger an AJAX call which will make a GET request to a web server running on my local machine.

This is what I have so far:

JS code:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>


<script type="text/javascript">


$('call').click(function() {
    alert("hiii");

  $.ajax({
    'url' : 'localhost:8080/blah/blah/blah',
    'type' : 'GET',
    beforeSend: function() {
                alert(1);
            },
    error: function() {
                alert('Error');
            },
    'success' : function(data) {
      if (data == "success") {
        alert('request sent!');
      }
    }
  });
});

</script>

HTML code:

<body>
  <div>
    <form>
      <div class = "buttons">
          <input type="submit" id="call" value="call">
      </div>
    </form>
  </div>
</body>

Can somebody help me? Thanks in advance!

Best Answer

You have a few issues with your code. For one, your selector is not pointing at any class or ID. You need to use .call or #call for a class or ID respectively. Second, your script has no document.ready function. Check out the code below.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
    // document.ready function
    $(function() {
        // selector has to be . for a class name and # for an ID
        $('.call').click(function(e) {
            e.preventDefault(); // prevent form from reloading page
            alert("hiii");

            $.ajax({
                'url' : 'localhost:8080/blah/blah/blah',
                'type' : 'GET',
                beforeSend: function() {
                   alert(1);
                },
                error: function() {
                   alert('Error');
                },
                'success' : function(data) {
                   if (data == "success") {
                        alert('request sent!');
                   }
                }
            });
        });
    });
</script>