Nibras
Nibras

Reputation: 369

how to call AJAX function in anchor tag

I'm new to AJAX. i want to call AJAX function when i click a button using onclick() event. This is the AJAX function called by onclick() event

function onclickFunction(aId){
    $.ajax({
        type: "get",
        url: "like_audio",
        data: {
            aId:aId
        },
        success: function (data){
            alert(data);
        },
        error: function (xhr, ajaxOptions, thrownError){

        }
    });
    return false;
}

This is how i'm calling the onclick() event

<a href="" onclick=onclickFunction(id)

Upvotes: 5

Views: 17866

Answers (2)

IaMaCuP
IaMaCuP

Reputation: 845

<a href="#" onclick="onclickFunction('theid');">Click Me</a>

Will run the function, and pass it the value 'theid'

In your example, you don't have a comple href, and even if it was right, you might not have an ID value to pass to it. if i do this:

Click Me

I am basically saying, there is a variable called id in the global scope, go find its value and pass it to the function - if there is indeed a variable like that on your page, then it will work, however i don't know if there is.

Upvotes: 0

rrk
rrk

Reputation: 15846

Just get the use return inside onclick, which will prevent the reload.

<a href="" onclick="return onclickFunction('id')">a</a>

As an alternative you can use

<a href="javascript:onclickFunction('id')">a</a>

Upvotes: 6

Related Questions