I have been reviewing my code trying to tidy it up, and I am just getting sick of the way I write jQuery when it needs to copy html from the page. Here is what I mean:
I have a section of the page that loops through posts like a forum (my actual code is more html heavy):
<? foreach ($posts as $post): ?>
<div class="post">
<div class"post_details">
<a href="<?= $post->link ?>"><?= $post->title ?></a>
<br>
<?= $post->timestamp ?>
</div>
</div>
<? endforeach ?>
And then in my jquery, I essentially have to duplicate this HTML to loop through the results of an AJAX request to get more recent posts:
for (i = 0; i < response.length; i++) {
post = respnse[i];
html = '<div class="post">';
html += '<div class"post_details">';
html += '<a href="' + post.link + '">' + post.title + '</a>';
html += '<br>';
html += post.timestamp;
html += '</div>';
html += '</div>';
}
// Inject html into page
$(".feed").prepend(html);
If I change the layout of the HTML where PHP loops through the object, then I also have to change the HTML in the jQuery. I then end up with lots of essentially duplicated code which just becomes messy as anything.
Is there a way to better link the jQuery to the HTML elements to make the code more concise?
Your method is crazy…
Why do this in JavaScript? Why not have the PHP return the fully formatted string and then just use jQuery to put it into its place? Just return this in an xml string and extract it.
Better yet, have the AJAX request return a View (if you’re using an MVC framework) that runs that exact code. Put the code in one place, a partial view or something and create a link to that that you can AJAX to. My $0.02.