JQuery Ajax call to launch onClick

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 call an AJAX call that will make a GET request to a web server running on my local computer.

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 someone help me? Thanks in advance!

+5
source share
2 answers

You have a few problems with the code. For example, your selector does not point to any class or identifier. For a class or identifier you need to use .call or #call . Secondly, your script does not have a 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> 
+2
source

As pointed out by @NightOwlPrgmr, your selector is wrong. To fix this, you should use #call , not .call , as this is an identifier, not a class attribute. Also, the Document.ready function guarantees that your code will be launched after loading all html elements. This will reduce the risk of trying to use an item that has not yet been created. Example code similar to the above: -

 <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"> </script> </head> <body> <div> <form> <div class = "buttons"> <input type="submit" id="call" value="call"> </div> </form> </div> <script type="text/javascript"> // document.ready function $(document).ready(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:[port_number_web_server]/blah/blah/blah', 'type' : 'GET', beforeSend: function() { alert(1); }, error: function() { alert('Error'); }, 'success' : function(data) { if (data == "success") { alert('request sent!'); } } }); }); }); </script> </body> 

0
source

All Articles