Support » Developing with WordPress » AJAX call out of the widget area

  • Resolved Mostafa Shahiri

    (@mostafadeveloper)


    Hi
    I want to make an advanced search widget. Main box of the widget including search fields and search button have been placed in widget area and I want to show results in the main div of wordpress theme. Also, I want to use a button for showing more results (more results button). I like to use AJAX method for searching and loading more result. AJAX call works correctly for the search button and initial results are loaded in the main div, but the more results button doesn’t work and I can not load more results. I think there is a restriction for AJAX calls in the widgets that it works just for the elements have been placed in the widget area. Is it right? How can I solve this problem.

    Thanks

Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    No restrictions for JavaScript or jQuery. They have full access to the entire DOM. I’m guessing the more results button does not have a click event listener added. Even if you have the proper selector in jQuery, by the time the more results button is added to the DOM, the code with the proper selector probably already ran. You need to explicitly add an event listener to any elements added via Ajax success: callbacks after the element itself has been added.

    To avoid further guessing, you should provide a link to the page you are having trouble with. Or at least post the relevant code. If this code is extensive, please post to pastebin.com and just provide the link here.

    @bcworkz Thank you. Your guess helped me.
    Solution for this problem:
    Using of the .on() method and setting the target element as second parameter for this method. For dynamic DOM elements, we must use a static element as the selector element and put the target element as second input parameter of .on() method.

    for example:
    using:
    jQuery("#wrapper").on("click",".clickedbtn", function(){});

    instead of:

    jQuery("#wrapper .clickedbtn").on("click", function(){});

Viewing 2 replies - 1 through 2 (of 2 total)
  • You must be logged in to reply to this topic.