1325

Parse HTML in jquery through ajax into elements and replace each corresponding on page

Question:

I have the following on an HTML page:

<script type="text/javascript"> setInterval(function(){refresh()},5000); function refresh() { $.post("test.php", { // nothing here }, function(data, textStatus) { $('' + data + '').find('.maindiv').each(function () { $('.maindiv').replaceWith('.maindiv'); }); }); } </script> <div id = "1" class= "maindiv"> <div sid= "1" class= "subdiv">old sub div content</div> <div cid= "1" class= "childdiv">another old sub div</div> <img id = "1" src="http://foo.com/bar.png"/> </div> <div id = "2" class= "maindiv"> <div sid= "2" class= "subdiv">this content is old</div> <div cid= "2" class= "childdiv">please update me!</div> <img id= "2" src="http://foo.com/bar.png"/> </div>

The PHP page that gets called to update elements (test.php):

<?php echo '<div id = "1" class= "maindiv"> <div sid= "1" class= "subdiv">this is new sub div</div> <div cid= "1" class= "childdiv">this is also new sub div content</div> <img id= "1" src="http://foo.com/bar.png"/> </div>'; echo '<div id = "2" class= "maindiv"> <div sid= "2" class= "subdiv">new content</div> <div cid= "2" class= "childdiv">new content for this child div</div> <img id= "2" src="http://foo.com/bar.png"/> </div>'; ?>

These 2 elements are also present on the HTML page. Basically what I want to call the PHP page and get those elements from the PHP page and loop through them in the response in the HTML page and replace each maindiv (including all its child elements) with the corresponding one on the HTML page.

This is just a very basic example. I do this because the content changes in these elements and want to replace the elemnts like live update.

The function I'm posting seems to have no response so don't know how to achieve this.

Thanks in advance

Answer1:

You need to index the maindiv elements in page so that they match with the new elements.

Also need to modify what you are replacing with

$(data ).filter('.maindiv').each(function (index) {/* filter or find depends on html structure sent*/ /* "this" is the current div in response*/ $('#'+this.id).replaceWith(this); });

each will track index, eq() is used to match same index in page.

<strong>EDIT:</strong> Also change find() to filter() if only output is the DIV's in root of output

Answer2:

Why dont you have 1 div that surrounds the content that you want to poll then upon receiving the ajax response replace the whole block with html()

<?php //check for ajax and return if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){ header('Content-Type: text/html'); $response = ' <div id = "a" class= "maindiv"> <div sid= "1" class= "subdiv">'.date("D M j G:i:s T Y").'</div> <div cid= "1" class= "childdiv">'.md5(time()).'</div> <img id= "1" src="http://foo.com/bar.png"/> </div> <div id = "a" class= "maindiv"> <div sid= "1" class= "subdiv">'.date("D M j G:i:s T Y").'</div> <div cid= "1" class= "childdiv">'.md5(time()+1).'</div> <img id= "1" src="http://foo.com/bar.png"/> </div>'; echo $response; die; } ?> <script type="text/javascript"> function poll(){ setTimeout(function(){ $.ajax({ url: "./test.php", cache: false, success: function(data){ $("#polling").html( data ); poll(); }}); }, 5000); } $(document).ready(function(){ poll(); }); </script> <div id = "polling" class= "maindiv"> <!--New response will replace the below html--> <div id = "1" class= "maindiv"> <div sid= "1" class= "subdiv">old sub div content</div> <div cid= "1" class= "childdiv">another old sub div</div> <img id = "1" src="http://foo.com/bar.png"/> </div> <div id = "2" class= "maindiv"> <div sid= "2" class= "subdiv">this content is old</div> <div cid= "2" class= "childdiv">please update me!</div> <img id= "2" src="http://foo.com/bar.png"/> </div> </div> <h2>Edit</h2>

You can also return json and then loop the response into the divs based on id Here is an example:

<?php //check for ajax and return if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'){ header('Content-Type: application/json'); $response = array( 'block_a'=>'content for block a (last_updated:)'.date("D M j G:i:s T Y"), 'block_b'=>'content for block b (last_updated:)'.date("D M j G:i:s T Y"), 'block_c'=>'content for block c (last_updated:)'.date("D M j G:i:s T Y"), 'block_d'=>'content for block d (last_updated:)'.date("D M j G:i:s T Y"), 'block_e'=>'content for block e (last_updated:)'.date("D M j G:i:s T Y"), ); echo json_encode($response); die; } ?> <script type="text/javascript"> function poll(){ setTimeout(function(){ $.ajax({ url: "./test.php", cache: false, success: function(data){ $.each(data, function(k, v) { //key value place html blocks $("#"+k).html(v); }); poll(); }, dataType: "json"}); }, 1000); } $(document).ready(function(){ poll(); }); </script> <div id = "block_a" class= "maindiv"></div> <div id = "block_b" class= "maindiv"></div> <div id = "block_c" class= "maindiv"></div> <div id = "block_d" class= "maindiv"></div> <div id = "block_e" class= "maindiv"></div>

This way you can build $response with only the content you want replaced upon each poll.

Recommend

  • WPF: When is a TabItem actually loaded, rendered and completly ready?
  • Copying rows in a database when rows have children
  • Passing information to server-side function in a Google Docs Add On
  • Ruby and class variables in inherit class
  • Insertion large number of Entities into SQL Server 2012 [duplicate]
  • Why doesnt this Java loop in a thread work?
  • What's the syntax to inherit documentation from another indexer?
  • Most efficient way to move table rows from one table to another
  • How to retrieve information from antrun back to maven?
  • Floated image with variable width and heading with background image
  • Stop Bash Script if Hive Fails
  • How to add git credentials to the build so it would be able to be used within a shell code?
  • How to have background script and something similar to a default popup?
  • Mysterious problem with floating point in LISP - time axis generation
  • How to know when stdin is empty if it contains EOF?
  • Python urlparse: small issue
  • Meteor helpers not available in Angular template
  • How to delay loading a property with linq to sql external mapping?
  • Xamarin Forms - UWP Fonts
  • Is there any way to access browser form field suggestions from JavaScript?
  • Align navbar back button on right side
  • Window Size for Mac application
  • Display Images one by one with next and previous functionality
  • Upload files with Ajax and Jquery
  • Build own AppleScript numerical error handling
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • jQuery tmpl and DataLink beta
  • GridView Sorting works once only
  • Is there a mandatory requirement to switch app.yaml?
  • VB.net deserialize, JSON Conversion from type 'Dictionary(Of String,Object)' to type '
  • File upload with ng-file-upload throwing error
  • ExecuteAsync RestSharp to allow backgroundWorker CancellationPending c#
  • AngularJs get employee from factory
  • Change div Background jquery
  • How does Linux kernel interrupt the application?
  • Busy indicator not showing up in wpf window [duplicate]
  • Reading document lines to the user (python)
  • Why do underscore prefixed variables exist?
  • java string with new operator and a literal
  • How to push additional view controllers onto NavigationController but keep the TabBar?