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
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);
});
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/
in callback function, which looks something like
function(response){
response = //edit response here
$("#content").html(response);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With