Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery to alter an AJAX response

Tags:

jquery

ajax

When an AJAX call returns html, is it possible to use jQuery to alter the contents of the response string? If so, how does one go about doing that?

EDIT:

This question is directed at editing the response before writing it to the page

like image 475
yoozer8 Avatar asked Aug 17 '11 12:08

yoozer8


4 Answers

Well that depends on how you request the data. If you have $.ajax etc, then you can do the necessary modifications in the success handler. I assume since you don't understand jQuery very well, that you are using $.load() to load the data, in which case it's easiest to replace it with

$.get('/somecode.php', function(data) {
    data = $(data);

    // Find and remove all anchor tags for example
    data.find('a').remove();
    $('#target-id').append(data);
});

Or if you don't want to create a jQuery object, you can easily do something like

$.get('/somecode.php', function(data) {
    // Replace all strings "foo" with "bar" for example
    data = data.replace('foo', 'bar');

    // Manually append it to DOM or do whatever you want with it
    $('#target-id').append(data);
});
like image 131
zatatatata Avatar answered Oct 26 '22 07:10

zatatatata


If you're using jquery 1.5+ you can use ajax datafilter.

dataFilter callback option is invoked immediately upon successful receipt of response data. > It receives the returned data and the value of dataType, and must return the (possibly > altered) data to pass on to success.

Sample Code :

$.ajaxSetup({
    dataFilter: function (response, type) {
        response = response.replace(/username/g, 'Sina Salek');
        return response;
    }
});

https://api.jquery.com/jquery.ajax/

like image 29
Sina Salek Avatar answered Oct 26 '22 09:10

Sina Salek


in callback function, which looks something like

function(response){
  response = //edit response here
  $("#content").html(response);
}
like image 39
genesis Avatar answered Oct 26 '22 08:10

genesis


You can edit the content of the returned data with jQuery by transforming the data itself in a jquery object.

$.get(file.html, function(data){

    var $obj = $('<div>').html(data); //explaination of this below

    $obj.find("span").remove(); //just an example, this removes all the SPANs

    $("#destination").html($obj.first('div').html());
});

Please note that you need to wrap the returned data in a DIV, before editing it, because if your returned data has not a valid root node in the HTML structure, the jQuery object will not be able to perform modification with the find and other functions.

For this reason it's a good practice to wrap the returned data, modify it, and then unwrap it before the insertion in the destination html node.

like image 25
fstasi Avatar answered Oct 26 '22 07:10

fstasi