Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 428
Max Maxymenko Avatar asked Feb 04 '16 13:02

Max Maxymenko


People also ask

How do I send AJAX requests every second?

ajax({ type: 'POST', url: 'increment. php', data: $(this). serialize(), dataType: 'json', success: function (data) { $('#hidden'). val(data);// first set the value }, complete: function (data) { // Schedule the next setTimeout(doAjax, interval); } }); } setTimeout(doAjax, interval);

Can we send two URLs in AJAX?

You can't call 2 url simultaneously. but you can call one after another. You can't put two URLs in an ajax call.


1 Answers

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');         }     }); }); 
like image 75
Rory McCrossan Avatar answered Sep 19 '22 11:09

Rory McCrossan