0

My question is very simple for jquery lovers, but hard for me. I have simple a href tag with data atrribute included.

<a href="#/one" data-menu-button="menu1" class="button">menu 1</a>
<a href="#/two" data-menu-button="menu2" class="button">menu 2</a>

// etc

Also i have very simple ajax call script.

$(".button").click(function(){
        $.ajax({url: "test.php", success: function(result){
           $(".page").html(result);
        }});
});

My question:

How can i replace ajax url with clicked button data atrribute? For example, at the moment, as you can see, i have url: "test.php". What i need, is to change test to data atrribute (for example: menu1), but keep .php extension. I need that script finds clicked data atrribute, and replace it with test. Maybe $(this) would work?

Thanks for any answers, and sorry for bad english.

2 Answers 2

2

You can use .data() to fetch the value from data attributes.

Use $(this).data('menu-button') to fetch from data-menu-button and then append .php to it. It would look like menu1.php. $(this) would refer to the current element which is clicked.

You would also have to use e.preventDefault() to stop the page from navigating to whatever is present in href attribute. Unless you want to page url to have those fragments.

$(".button").click(function(e){
    e.preventDefault();
    $.ajax({url: $(this).data('menu-button') + '.php', success: function(result){
       $(".page").html(result);
    }});
});
Sign up to request clarification or add additional context in comments.

Comments

1

As you have guessed use $(this) to access the element, then .attr('data-menu-button) to get the attribute value.

$(".button").click(function(){
    var url = $(this).attr('data-menu-button') + '.php';
    $.ajax({url: url, success: function(result){
       $(".page").html(result);
    }});
})

1 Comment

Thanks to you too, but @Dhiraj Bodicherla was faster with good explanation :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.