Reputation: 854
I developed a plugin architecture application. Each time a plugin is added, a link is added to the main MVC app using jquery, the script is loaded dynamically from a js file in the plugin (DLL) and that link will be the entry point to the new module, the script successfully adds the link to the razor page but when I click on the link it does not work.
Here is the code.
Ps: I am not really good at javascript so forgive me if am making a stupid mistake in my code and couldn't find the solution.
$(document).ready(function () {
$("#myLinkDiv").append('<a id="aLink" href="#">ClickMe</a>');
$("#aLink").click(function () {
event.preventDefault();
$.ajax({
url: '/Candidate/CreateCandidate/',
type: 'GET',
success: function (data) {
return data;
}
});
});
});
Upvotes: 1
Views: 178
Reputation: 218722
Looks like you are dynamically injecting the new link element(a
tag) to the DOM. In that case, you need to register the click event after injecting the element to DOM Or use the jquery on
method to register event handlers which works with current and future DOM elements(dynamically injected after the DOM is rendered).
$(function(){
$(document).on("click","#aLink",function (e) {
e.preventDefault();
alert("Going to make ajax call now");
//your code to make ajax call
});
});
It might be a good idea to narrow down the jQuery selector on which you are registering the event handlers. For example, If you know you are adding the link to the id "myLinkDiv", You may replace the jQuery selector to that.
$("#myLinkDiv").on("click","#aLink",function (e) {
});
Here is a working sample. http://jsbin.com/zuciwoloba/edit?html,js,output
I am also a little confused with your ajax code. In the success handler you are having a return statement, which does not makes sense. Usually you want to update the DOM / show a message to user when the ajax call is successful.
$.ajax({
url: '/Candidate/CreateCandidate/',
type: 'GET'
}).done(function(res){
alert("Success.Check browser console for server response");
console.log(res);
}).fail(function(){
alert("Failed.Check browser network tab for server response");
console.log(res);
});
Upvotes: 1
Reputation: 1396
To introduce an element after creation of DOM you need to bind event listener to newly introduced element -
Please do something like this... (You missed to pass event
)
$(document).on('click',"#aLink",function (event) {
instead of $("#aLink").click(function () {
Upvotes: 0