Welcome to WebmasterWorld Guest from

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

InsertAfter php into jQuery

12:01 pm on Dec 9, 2016 (gmt 0)

Junior Member

10+ Year Member Top Contributors Of The Month

joined:July 4, 2007
posts: 193
votes: 0

I need to insert the following php dynamically after the 3rd paragraph on my page.

<?php echo dfads(); ?>

I have the following but nothing displays.

<script type="text/javascript">
$("<div class='article-ad'><?php echo dfads(); ?></div>").insertAfter(".entry-content > p:nth-of-type(3)");

Any ideas? Thanks in advance.
12:48 pm on Dec 9, 2016 (gmt 0)

Senior Member

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month

joined:Sept 25, 2005
votes: 370

I don't know that much about jQuery (in fact, when I first saw your code, I didn't think you could mix CSS and jQuery in that way, but apparently you can), but shouldn't those two selectors be reversed? It looks to me like you're currently trying to insert ".entry-content > p:nth-of-type(3)" after "<div class='article-ad'><?php echo dfads(); ?></div>", which doesn't exist in the DOM because you haven't inserted it. The insertAfter function applies to the preceding selector, the way that getElementById() would apply to document in document.getElementById().

I would probably use only PHP to insert that ad. Assuming your paragraphs are neatly enclosed with <p>...</p>, you can replace the third occurrence of "</p>" with "</p><div class='article-ad'><?php echo dfads(); ?></div>". There's no standard function for that, but if you search for "php replace nth occurrence of string" you're bound to find some solutions.
5:29 pm on Jan 9, 2017 (gmt 0)

Senior Member from MZ 

WebmasterWorld Senior Member 10+ Year Member

joined:Nov 9, 2005
posts: 837
votes: 0

If you are looking to insert the OUTPUT of this php function call then it is not going to work like this, I am afraid. PHP code must be run when the browser starts parsing the page. Otherwise, in spite of adding output of this function call, it will add the actual php code as simple text.

use AJAX or execute the " echo dfads()" and keeps its output in a div. then you can add it without sending a call to the server to compile php code.