How can I send an Ajax Request on button click from a form with 2 buttons?

后端 未结 3 1057
-上瘾入骨i
-上瘾入骨i 2020-12-13 18:09

I want to send a request from one page to another from a form which has 2 buttons:

3条回答
  •  清歌不尽
    2020-12-13 18:42

    function sendAjaxRequest(element,urlToSend) {
                 var clickedButton = element;
                  $.ajax({type: "POST",
                      url: urlToSend,
                      data: { id: clickedButton.val(), access_token: $("#access_token").val() },
                      success:function(result){
                        alert('ok');
                      },
                     error:function(result)
                      {
                      alert('error');
                     }
                 });
         }
    
           $(document).ready(function(){
              $("#button_1").click(function(e){
                  e.preventDefault();
                  sendAjaxRequest($(this),'/pages/test/');
              });
    
              $("#button_2").click(function(e){
                  e.preventDefault();
                  sendAjaxRequest($(this),'/pages/test/');
              });
            });
    
    1. created as separate function for sending the ajax request.
    2. Kept second parameter as URL because in future you want to send data to different URL

提交回复
热议问题