Morten Hagh
Morten Hagh

Reputation: 2113

ajax loading of search results

I have setup a search funtionality that will search in an XSLT file. This works flawlessly but I have a little trouble returning the search results dynamically with ajax.

This is my JS:

 var SearchHandler = function(frm) {

        frm = $(frm);
        var data = frm.find(".search-field").val();

        $.ajax({ 
            method: 'GET',
            url: '/',
            data: { query: data },
            dataType: 'xml',
            success: SearchSuccessHandler,
            error: SearchSuccessHandler
        });

    };

    var SearchSuccessHandler = function(html) {


    };

What I want is the SearchSuccessHandler to dynamically load the search result from index.php?query=searchword

I just can't seem to figure out the right way to handle it.

Upvotes: 0

Views: 88

Answers (2)

SidOfc
SidOfc

Reputation: 4584

Based on your comment:

Bah.. Sorry... The ajax call will return some new html based on the query ... I want the existing html to be replaced I have tried $('body').html(html.responseText); but then I cannot search again because javascript is not loaded correctly

It's not the AJAX which is the issue but rather event delegation

When you bind a function to an element directly like this:

$('.my-element').on('whatever', function() { ... })

the handler will work as long as the element exists however if you replace the contents of the entire body you'll run into trouble as your original .my-element no longer exists.

You can overcome that by using event delegation to make sure your function keeps searching e.g.

$(body).on('whatever', '.my-element', function() { ... })

This basically says: "If I click on body and the target is .my-element then execute this function" Instead of a directly bound handler which says: "If I click on this specific element then execute this function"

the body will always exist and therefore you'll always be able to delegate down from the body but if you can do it on some more specific element that would obviously be better since then you won't have an onclick handler on the entire body.

I think this is what your issue is since you're replacing the entire body.

Upvotes: 1

SZD
SZD

Reputation: 81

Try this

success:function(data) {
// do your stuff here
}

Of course, you need to be sure your function is returning some values. To make it easier for your, encode the values as json on your index.php

return json_encode($values)

Then, inside your success function, just parse it with eval()

Upvotes: 0

Related Questions