简体   繁体   中英

Submit a link using javascript or jquery without refreshing a page

I have a link which invokes an API which saves a session. Suppose my API be present on http://www.example.net and my link is as below :

 <a href="http://www.example.net" >Click here </a>

Now i don't want to refresh the page. Just use JQuery or Javascript to simply execute the link and give an alert like "Action Succesfull". I don't see the point of using AJAX as I don't require any database actions from my side. Thanks

The point of AJAX is not to do database actions, its to comunicate with the server without needing to reload the page. I think your description qualifies for the use of AJAX, since you do expect a answer from the server, and you do not want to reload the page.

You could also open a iframe, or a new window, but ajax might be the solution here.

Keep in mind you need to cancel that event when you click on the anchor.

So, with ajax you could so something like:

$('a').on('click', function(e) {
  e.preventDefault;
  var href = this.getAttribute('href');
  $.ajax({
    url: href,
    success: function(text) {
      alert(text);
    }
  });
});

You will need an ajax call. Something like this:

$.ajax({
    cache: false,
    type: "Post",
    url: "http://www.example.net",
    success: function () {
       alert("Success");
    },
    error: function (xhr, ajaxOptions, thrownError) {
        alert("Error");
    },
    finaly: function () {
        alert("Finish");
    }
});

如果您不想使用AJAX,则可以简单地使用onclick事件

<a href="http://www.example.net" onclick="event.preventDefault();">Click here </a>

Try to use an ajax call when click on button submit or the link. Here is the code :

$("a").click(function(e){
    $.ajax({
        url: "http://www.example.net",
        type: "POST",
        error: function(jqXHR, textStatus, errorThrown) 
        {
            alert(errorThrown);
        },
        success: function(data,textstatus,jqXHR)
        {
            alert("Success");
        }

    });
    e.preventDefault();
});

you need to do something like this:

$('a').click( function(e) {
    e.preventDefault();
    var url = "your link";
    $.ajax({
       url: url,
       success: function(data)
       {
           alert(data); // show response.
       }
    });
    return false; 

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM