0

I have used the $.get function in many cases in my project:

$.get(user, function (data) {
   // CODE
});

Now, i want to modify it to:

   $.get(user, function (data) {
         if (validate_data(data)){
             // CODE
         }
    });

but it is impossible to go to every single javascript file in project and modify all the instances. Is it possible to modify the jquery.js file instead to get the same result?

1
  • Yes, it is possible but I'd probably avoid it. Instead look for ajaxComplete kinda solution. Commented Sep 18, 2014 at 9:29

4 Answers 4

2

You might be able to pull something by using

$.ajaxComplete(function(data) { ... } )
Sign up to request clarification or add additional context in comments.

3 Comments

Dangerous to add that sort of validation code generically to all Ajax requests. What about breaking other plugins that use Ajax?
@trueblueaussi that's true indeed. you would have to take care of the potential collateral damages by checking the nature of your data and the origin of your request
I don't want the same Success function for all my get requests, I just want to do a validation before.
1

As I know you can handle data before success and use throw to stop script. Not the best solution but should works.

jQuery.ajaxSettings.dataFilter = function(response, type){
    if (!validate_data(response)){
        throw "Stop!";
    }
    return response;
}

2 Comments

If validate_data returns true, the code in the original $.get function does not get fired.
Sorry I forgot about return.
1

I think the easiest way to do so is to extend jQuery (not tested):

jQuery.fn.extend({
    get_validated: function(url, callback) {
        return $.get(url, function(data) {
            if(validateData(data)) {
                callback(data);
            }
        }
    }
});

and then replace every occasion of get with get_validated with the command replace in files in your IDE.

Comments

1

You can attach a callback function using ajaxComplete to the ajax request as below

$( document ).ajaxComplete(function( event, xhr, settings ) {
  if ( settings.url === "MY GET URL" ) { //IF URL matches the one that you need
  $( ".log" ).text( "Triggered ajaxComplete handler. The result is " +
  xhr.responseText );
  }
});

The only limitation of this trick is that you must have something in your call so that you can identify that it's get call of which you want to validate the response

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.