Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing different PHP code for different HTML buttons (AJAX)

I'm trying to write different PHP code for different HTML <button> elements, but apparently it applies to all the buttons on the page. Here's one of my buttons:

<button name="plus" id="plus" type="button" onclick="plus()">+</button> 

Here's the function I tried to make, it applies to all the buttons on the page:

$(document).ready(function() {
    $("button").click(function() {
        $.ajax({
            type: 'POST',
            url: 'plus.php',
            success: function(data) {
                //
            }
        }); 
    }); 
});

The questions:

  1. How do I write functions for specific buttons?

  2. Why do I have to write type="button" for them to work?

  3. Where do I write AJAX functions? In <head></head> or anywhere in the body?

like image 386
Barrett_killz Avatar asked Sep 25 '26 18:09

Barrett_killz


2 Answers

1) How do I write functions for specific buttons?

You can do this by putting specific id or classes on the button elements so you can select a single element or groups of them at once. For example $('#plus') would target only the id="plus" element in your HTML sample.

2) Why do I have to write type="button" for them to work?

This is because the default type of a button is submit. Therefore if the button is in a form it will submit the form before your JS has time to complete.

3) Where do I write AJAX functions? In the head or anywhere in the body?

Either is fine, but if you put it in the <head> make sure you place your code in a document.ready handler.

Finally, I would suggest that you remove the onclick="plus()" attribute in your HTML. You don't appear to be using it and even if you were, attaching events through JS is considered much better practice over the use of archaic event attributes.

like image 58
Rory McCrossan Avatar answered Sep 28 '26 08:09

Rory McCrossan


Sure it will apply to all button because you select all button In Jquery when you select a specific element you have to use an id and for selecting an ID in your case you can do

$(document).ready(function(){
    $("#plus").click(function(){

        $.ajax({
            type: 'POST',
            url: 'plus.php',
            success: function(data) {
                //

            }
        }); }); });

It will work now

like image 44
thecassion Avatar answered Sep 28 '26 08:09

thecassion



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!