a tag how to trigger ajax 1

a tag how to trigger ajax

document.querySelector("#myId").onclick = function(e) {
  e.preventDefault();
  
  $.ajax({
    url: 'api_url',
    type: 'post',
    data: {key: 'value'},
  })
  .done(function() {
    console.log("success");
  })
  .fail(function() {
    console.log("error");
  });
}

Here is what the above code is Doing:
1. When the user clicks on the element with the id of myId, the function is called.
2. The function calls the jQuery ajax method.
3. The ajax method sends a post request to the api_url.
4. The data key/value pair is sent along with the request.
5. If the request is successful, the done function is called.
6. If the request fails, the fail function is called.

Similar Posts