3

Since, I am new to jQuery I am facing problem in parsing html data retrieved from ajax.

I have a form which is using ajax to post form data and retrieve the content back to that page by adding one div ( on the same page as that of form ) to display that data.

I want to perform some jQuery / Javascript operations on that data, but since I am not reloading the page, jQuery or javascript is not able to parse that data.

How can I force javascript or jquery to reparse the whole page without loading it.

Here is the code

html

<div class="col col-lg-9 search-data well">
            <div class="no-results">
                Search Results will appear here.
            </div>
        </div> 

jQuery

$('.search-form').click(function(e)
    {
        console.log('same-page');
        e.preventDefault();
        var form_var = this.form;
        var postData = $(this.form).serialize();
        var formURL = $(this.form).attr("action");
        $.ajax(
        {
            url : formURL,
            type: "POST",
            data : postData,
            success:function(data, textStatus, jqXHR) 
            {
                // console.log(data)
                $('.search-data').empty();  // Delete all child nodes
                $('.search-data').html(data); 
            },
            error: function(jqXHR, textStatus, errorThrown) 
            {
                $('.search-data').empty();  // Delete all child nodes
                $('.search-data').html(data);       
            }
        });
        return false;
    });

Thankyou

9
  • @AwladLiton, code added Commented Dec 31, 2013 at 8:02
  • Assuming the ajax call is successful and the server sends back even vaguely-valid HTML, that should work. (The $('.search-data').empty(); call is completely unnecessary. Also, if you have more than one element with the search-data class, it'll add the HTML to all of them.) If the ajax call fails, that code will fail because your error handler tries to get the value of a symbol (data) that isn't defined anywhere. Commented Dec 31, 2013 at 8:02
  • my question is how can I perform jQuery operations on the data I have got back from server. Commented Dec 31, 2013 at 8:04
  • what type of operations you want to do on that data? Commented Dec 31, 2013 at 8:05
  • You have data now select your element where you want to add or replace data then add or replace data into this element Commented Dec 31, 2013 at 8:06

1 Answer 1

1

my question is how can I perform jQuery operations on the data I have got back from server.

If you want to do something to the HTML before you add it to the page, you can do this:

var fragment = $(data);

That will parse the HTML into elements and give you a jQuery wrapper around those elements, without adding them to the page anywhere. You can then manipulate those with jQuery. Eventually, of course, if you want them to appear on the page, you have to add them to the page somewhere (via html or append or similar on an existing element).

data has some a links, I want to parse those links perform some operations on click of them

You can do that. Example: Live Copy | Live Source

HTML fragment:

<div>
  <a href="http://stackoverflow.com">Stack Overflow</a>
  <a href="http://w3schools.com" class="remove">w3schools</a>
</div>

Here's a page using it. In this case, I remove a link we don't want and hook the click event on the ones that remain, then append them to the page:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Modify HTML Before Appending</title>
</head>
<body>
  <script>
    $.ajax({
      url: "http://jsbin.com/IsixODa/1",
      dataType: "html",
      success: function(data) {
        var fragment = $(data);
        // Remove some links we don't want
        fragment.find(".remove").remove();

        // Hook the others
        fragment.find("a").click(function() {
          alert("You clicked a link: " + this.href);
          return false;
        });

        // Put them on the page
        fragment.appendTo(document.body);
      },
      error: function() {
        $("<p>Ajax call failed</p>").appendTo(document.body);
      }
    });
  </script>
</body>
</html>
Sign up to request clarification or add additional context in comments.

3 Comments

hi, I have added var fragment = $(data); but I am getting errror after adding that.. ( Uncaught Error: Syntax error, unrecognized expression: )
@AbhishekGoel: That tells you that the text in data doesn't look like HTML, so jQuery is trying to interpret it as a CSS selector instead. So that's what you need to fix. Make sure data starts with < to be sure jQuery will treat it as HTML and not a selector. (I forget jQuery's exact rules, but that should do the trick).
Found the error, there was empty lines in my data i.e. I tried with <div>hii</div> on other page, it was still giving error because of emptly lines above that <div>hii</div> and as soon as I removed those blank lines it worked. Thankyou again. :)

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.