Skip to content Skip to sidebar Skip to footer

Jquery/ajax Button Click Using Variable

I want to implement a simple webpage using jQuery/Ajax. I have 3 buttons, each of which will use ajax call to get different files from the server. The only difference is that each

Solution 1:

Your need to set url on all three button like

<buttonclass='button1'data-url='button1.txt'>button 1</button><buttonclass='button2'data-url='button2.txt'>button 2</button><buttonclass='button3'data-url='button3.txt'>button 3</button>

After That on your ajax.

<script>
$(document).ready(function(){
$(".button1, .button2, .button3").click(function(){
var url = $(this).attr('data-url');
    $.ajax({
        url: url", 
        /*more code*/
    });
});
});

Solution 2:

EDIT use a data attribute say an attribute named data-url, fetch it inside your click event

Provide same class names to all the buttons. Retrieve the value of the buttons, and pass them to the ajax call,

<script>
$(document).ready(function(){
    $(".buttonClass").click(function(){
        //var value = $(this).attr("value");var dataUrl = $(this).attr('data-url');
        $.ajax({
            url: dataUrl, 
            /*more code*/
        });
    });
});
</script>

Solution 3:

You can use data-* prefixed custom attributes to store the file to be access in the $.ajax() function. You can use a common class to attach the event handler.

HTML

<buttonclass="button"filename="button1.txt"></button><buttonclass="button"filename="button2.txt"></button><buttonclass="button"filename="button3.txt"></button>

FileName can be fetched using Element.dataset property or jQuery's .data() method.

Script

$(".button").click(function(){
    var fileName = this.dataset.filename;
    $.ajax({
        url: fileName, 
        /*more code*/
    });
});

Solution 4:

I guess a common class name would suffice. Although you need to have some id on your buttons to differ, yet it's not required. this can be used in this case.

I think this can be done with putting your ajax in a parameterised function:

functionmyAjaxCall(){
    var url = this.textContent.trim().toLowerCase()+'.txt';

    $.ajax({
        url: url, 
        /*more code*/
    });
}

$(document).ready(function(){
    $(".button").click(myAjaxCall);
});

consider such buttons:

<buttonclass='button'>Button1</button><buttonclass='button'>Button2</button><buttonclass='button'>Button3</button>

Solution 5:

simply add buttons in click event

<script>
   $(document).ready(function(){
     $(".button1, .button2 , .button3").click(function(){
        $.ajax({
            url: "button1.txt", 
            /*more code*/
        });
      });
    });
</script>

2 :

Add click onclik event in html

Post a Comment for "Jquery/ajax Button Click Using Variable"