mvlanga
mvlanga

Reputation: 109

Creating a dynamic variable in jQuery or PHP

I know there are already a few questions like mine but I wasn't able to fix my problem with their solutions.

I got this code in an external html file to include it in others files:

<div class="header">
   <h1 class="replace-me">I'am a placeholder</h1>
</div>

The "file" above gets included into this "file":

<h2 style="display: none" class="variable">Hey, I'm a variable</h2>

The Variable from the second code should replace the content of the h1 tag in the first code. I know this isn't a forum to get free codes, I just want some inspirations or suggestions. Thanks Guys!

Upvotes: 0

Views: 558

Answers (3)

Lajos Arpad
Lajos Arpad

Reputation: 76593

You should solve this on server-side if you can. Make the common template a function, like this:

function getHeader($content) { ?>
<div class="header">
   <h1 class="replace-me"><?php echo $content; ?></h1>
</div> <?php
}

calculate $content before you call the function and pass it to the function. If you cannot make this a function and you get this as it is from a third-party source, then you can do it via Javascript, like this:

<script type="text/javascript">
    document.getElementsByClassName("header")[0].getElementsByClassName("replace-me")[0].innerHTML = "<?php echo $content; ?>";
</script>

Make sure you add this script after the header tag was loaded.

Upvotes: 0

Marco de Zeeuw
Marco de Zeeuw

Reputation: 506

You can replace the html of one element with the html of another element, like so:

$(".replace-me").html($(".variable").html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="header">
   <h1 class="replace-me">I'am a placeholder</h1>
</div>
<h2 style="display: none" class="variable">Hey, I'm a variable</h2>

However, as Rama Schneider pointed out, you might want to get your content in a different way than html.

Also note that this jQuery-solution is done client-side. If you already know the content when serving the initial HTML, you want to do this server-side.

Upvotes: 1

Rama Schneider
Rama Schneider

Reputation: 64

If you have control over the external file, I'd suggest rewriting things so the external file serves a json object of some sort and work with your data from there.

Otherwise it's a simple matter of using JQuery to get the html contents from the variable and use that value to replace the html contents of the 'replace-me'.

Upvotes: 1

Related Questions