Search code examples
jqueryajaxprototypejs

Updating part of page with prototype and ajax


i work with page using prototype, and i have to add some ajax requests, which updates content of one specified div. Here how i did it in jquery:

$j.ajax({
    url: url,
    success: function (result) {
        var resultDiv = $j(result).find('.SOME-CLASS');
        $j('.SOME-CLASS').html(resultDiv.html());
    }
});

I tried to get the same result with prototype for last few hours and finaly i gave up. How would it look in prototype ? Its important to withdraw from result div with class SOME-CLASS and replace its content with existing in document div with the same class.

PS. I thought about parsing raw result string recived from prototypes request to get content of and then replace founded content with existing in document, but in my opinion this is bad, non elegant solution. Is there anything better ? I heard that prototype is great tool for DOM manipulation.


Solution

  • new Ajax.Request(url, {
        onSuccess: function(response) {
            var html = new Element('div');
            html.update(response.responseText);
            // There may be many .SOME-CLASS so use `invoke` to iterate through them
            $$('.SOME-CLASS').invoke('update', html.select('.SOME-CLASS').first());
        }
    });
    

    Prototype doesn't have an equivalent to jQuery's $(htmlString) shortcut, so you'll have to assign the HTML string to a newly created element then extract the child classes back (which is how jQuery does it behind the scenes). The temporary element is never added to the DOM so isn't seen directly.

    When searching for the incoming element by it's class we must use Element.select which returns an array. If we assume there will be only one match, or are only interested in one match, the first element of that array is used. Perhaps this isn't what you wanted and meant to collect multiple elements from the response. That is an ambiguity caused by using class names instead of IDs.

    Here is a demonstration fiddle.