6

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

1
  • 2
    Just a suggestion, since there seems to be so much confusion over this question. You may want to clarify that you are asking about using jQuery, NOT pure JavaScript, to accomplish the string manipulation. Of course this is exactly what your question says, but everyone seems to be providing responses about how to use pure JS, not jQuery. Commented Aug 17, 2011 at 12:59

7 Answers 7

12

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);
});
Sign up to request clarification or add additional context in comments.

4 Comments

In your first example, you're not explicitly using jQuery to modify the string. When you do $(data), you are creating jQuery objects (and therefore DOM elements) from the string. Consequently, you are actually using jQuery to modify a jQuery object, rather than a string. Therefore, from a performance/memory issue, it's still more expensive then modifying the string as a string first, and then creating the elements from that. But I'm not criticizing your response; unless the OP is a bit clearer about what exactly he's after, it's hard to know exactly what to tell him.
And your second example, of course, does not use jQuery at all, which is what the OP was asking about.
@maxedison simply saying that string manipulation is faster than DOM manipulation is just wrong. In some cases, yes, pure string solutions are faster (just concating a whole bunch of HTML strings and then appending them), but in most cases, using DOM to traverse, change attributes, modify css conditionally etc using DOM elements wins hands down. Try running regexps to accomplish it and you'll see the speed difference. And having worked with HTML pages (ebooks) that are multiple megabytes of pure HTML structure, I can assure you that you won't be running out of memory by using DOM elements.
good point. without knowing more clearly what the OP wanted, it's tough to say which is best.
4

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/

Comments

3

in callback function, which looks something like

function(response){
  response = //edit response here
  $("#content").html(response);
}

7 Comments

-1. This does not answer the OP's question. He wants to use jQuery to modify the string, not pure JavaScript. Obviously JavaScript has plenty of string manipulation functions. But he's asking about jQuery.
@Maxedison: when he says jquery, he obviously means javascript. it is assumed.
I did, in fact, mean jQuery. I was hoping to be able to apply the jQuery interface to the string the same way it is applied to a document. Although I am open to other js solutions
@LocustHorde -- since your assumption was clearly wrong, please remove your down vote from my response.
@Jim: technically, even if the assumption was wrong, strings can be manipulated with jquery. for example - Jquery trim
|
3

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.

Comments

0

Edited on maxedison's accuracy advice:

You can directly manipulate the return string as genesis pointed out (no need for JQuery to do that), or you can recreate a new output by parsing the html, using an helper library like jParse:

http://jparse.kylerush.net/demo

3 Comments

Again, this does not answer the OP's question. Other than $.trim(), jQuery does not do string manipulation. jQuery !== JavaScript
Sorry maxedison but your remark is IMHO uselessly fussy and, as you certainly know, jquery indeed is 100% javascript code, and there's no jquery without javascript, so what are we talking about? That aside I pointed out a jQuery library that can be used to modify the dom before injecting it.
Yes, jQuery is "indeed 100%" JavaScript code. But that's a bit irrelevant because it doesn't mean that jQuery can do string manipulation. If the question was sort of reversed, like "Can JavaScript do DOM manipulation" and you said "yes, use jQuery", that would be valid. I'd be fine if all these answers said "No, you can't do it in straight jQuery. But here's an alternative." Instead, you, like many, simply say "Yes." My answer might be fussy, but it's the only one that actually answers the OP's question correctly.
0

Primitive javascript

core: Object.defineProperty(this, 'responseText', { value: JSON.stringify(data), writable: false });

The method of using object assignment will be invalid, this.responseText = {...};

<button>send</button>
<p>hello</p>

<script>
  const nativeOpen = XMLHttpRequest.prototype.open;
  const nativeSend = XMLHttpRequest.prototype.send;

  const proxiedOpen = function () {
    // Mount the URL that needs to be intercepted to the `XMLHttpRequest` object.
    if (arguments[1].includes('jsonplaceholder.typicode.com/todos/1')) this._url = arguments[1];
    nativeOpen.apply(this, arguments);
  };

  const proxiedSend = async function () {
    if (this._url) {
      // Make other requests, it can also be a fixed value.
      const data = await fetch('https://jsonplaceholder.typicode.com/todos/5').then(res => res.json());
      // The data of `todos/1` is rewritten as `todos/5`
      Object.defineProperty(this, 'responseText', { value: JSON.stringify(data), writable: false });
    }
    nativeSend.apply(this, arguments);
  };

  // Override native methods
  XMLHttpRequest.prototype.open = proxiedOpen;
  XMLHttpRequest.prototype.send = proxiedSend;

  document.querySelector('button').addEventListener('click', () => {
    const xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function () {
      if (this.readyState == 4 && this.status == 200) {
        document.querySelector('p').textContent = this.responseText;
      }
    };
    xhttp.open('GET', 'https://jsonplaceholder.typicode.com/todos/1', true);
    xhttp.send();
  });
</script>

Comments

-7

No. jQuery will only operate on DOM elements. So until those are created from the string, all you have is... a string.

Can I ask why you're concerned about doing this? If it's a performance issue (i.e. you're creating a ton of DOM elements with the AJAX response, and then editing a lot of them with jQuery), then chances are that your PHP script should be modified to return a more desirable response. If the problem is that you don't want users to see the response until the DOM modifications have been made by jQuery, then just stick it all in a hidden div (display:none) until the modifications are complete.

Edit - 1 exception jQuery has a $.trim() function which will remove whitespace from the beginning and end of a string. Not sure if there are any others.

14 Comments

I think the best solution will be to modify what is returned in the AJAX response. Thanks!
@LocustHorde & the other people who down-voted my response: Please provide an example. Genesis' response is NOT a correct example because he doesn't show how you use jQuery to modify the string. Obviously JavaScript can be used, but not jQuery.
@Jim this is not the correct answer... you can easily modify the string/html/whatever you return with the request. My example shows the most basic way to do it (you don't have to convert it to a jQuery object if you wish to run regexp etc on it, but you can and it will not be included in the DOM until you append it yourself). Why did you accept an incorrect answer?
@Zanfa while your answer is correct, I found maxedison's answer more useful. The solution I'm taking away from this discussion is to return a more desirable response to the AJAX call so that I can just stick it in its appropriate place in the page.
@Zanfa & Jim - I upvoted Zanfa's answer, but I would argue against that being the "correct" answer. The OP asked about modifying the contents of the "response string." Zanfa -- your answer simply creates an object from the string, and then modifies that object. It does not modify the string itself, which is what the OP asked about (whether purposefully or not). Amazing... 5 down votes and I'm the only one who explicitly addressed the OP's question. jQuery does not do string manipulation :)
|

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.