Search code examples
javascriptajaxprototypejs

Prototype Ajax.Updater evaluate string before the update


here's my code:

new Ajax.Updater('container', url, {
    method: "get",
    onLoading: function () {
        document.getElementById('container').innerHTML = "Loading...";
    },
    on200: function(response) {
        if(response.responseText.match(/WhatImLookingFor/)) {
            window.location = "leNewURL";
        }
    },
    onComplete: function(response) {
        //do other cool stuff
    }
});

What I'm trying to do is intercept the response before container gets updated and if the text in the response matches WhatImLookingFor, I want to redirect the user to leNewURL. With the code above this is happening, but not before the update, so it looks quirky. Is there anyway that I can intercept right before the update happens or do I have to resort to other hacks like hiding container and show it only if there's no match?


Solution

  • If you want to customize the behavior of your Ajax call like that I would recommend using the base Ajax.Request() http://api.prototypejs.org/ajax/Ajax/Request/

    new Ajax.Request(url, {
        method: "get",
        onLoading: function () {
            $('container').update("Loading...");
        },
        onComplete: function(response) {
            if(response.responseText.match(/WhatImLookingFor/)) {
                window.location = "leNewURL";
            }
            else {
                //do other cool stuff
                $('container').update(response.responseText);
            }
        }
    });
    

    I swapped out the document.getElementById() with the $() utility method as its less to type and includes all of PrototypeJS's Element methods