47

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

<form method="post">
    <button id="button_1" value="val_1" name="but1">button 1</button>
    <button id="button_2" value="val_2" name="but2">button 2</button>
    <input id="access_token" type="hidden" name="access_token" value="<?php echo $_SESSION['access_token']; ?>" />
</form>
$(document).ready(function() {
  $("#button_1").click(function(e) {
    e.preventDefault();
    $.ajax({
      type: "POST",
      url: "/pages/test/",
      data: {
        id: $("#button_1").val(),
        access_token: $("#access_token").val()
      },
      success: function(result) {
        alert('ok');
      },
      error: function(result) {
        alert('error');
      }
    });
  });

  $("#button_2").click(function(e) {
    e.preventDefault();
    $.ajax({
      type: "POST",
      url: "/pages/test/",
      data: {
        id: $("#button_2").val(),
        access_token: $("#access_token").val()
      },
      success: function(result) {
        alert('ok');
      },
      error: function(result) {
        alert('error');
      }
    });
  });
});

How can I improve this code and maybe merge it into one function?

user5305519
  • 3,008
  • 4
  • 26
  • 44
Max Maxymenko
  • 551
  • 1
  • 5
  • 13

3 Answers3

61

Given that the only logical difference between the handlers is the value of the button clicked, you can use the this keyword to refer to the element which raised the event and get the val() from that. Try this:

$("button").click(function(e) {
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: "/pages/test/",
        data: { 
            id: $(this).val(), // < note use of 'this' here
            access_token: $("#access_token").val() 
        },
        success: function(result) {
            alert('ok');
        },
        error: function(result) {
            alert('error');
        }
    });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    Yeah, thanks I'm new to Stackoverflow - currently trying to figure out things! :) – Max Maxymenko Feb 04 '16 at 14:22
  • This worked. but i am trying to get pick out the `name` from my json data returned and i get undefined. i map it this way `alert(result.name)` –  Oct 26 '17 at 14:38
  • The answer to that depends entirely on how your JSON is structured. I'd suggest starting a new question for it – Rory McCrossan Oct 26 '17 at 14:39
13

Use jQuery multiple-selector if the only difference between the two functions is the value of the button being triggered.

$("#button_1, #button_2").on("click", function(e) {
    e.preventDefault();
    $.ajax({type: "POST",
        url: "/pages/test/",
        data: { id: $(this).val(), access_token: $("#access_token").val() },
        success:function(result) {
          alert('ok');
        },
        error:function(result) {
          alert('error');
        }
    });
});
Aung Myo Linn
  • 2,820
  • 3
  • 27
  • 38
6
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
Alankar More
  • 1,107
  • 2
  • 8
  • 26