Append <script> into <div> using jquery - javascript

I'm trying to append a <script> tag into my <div>. Whenever I try to do this, the script just doesn't loads. But it works if I hard coded it under the tag.
But if I try to append an <img> tag, it works!
Here's a partial code to give you some ideas.
$(document).ready(function() {
var tag = '<script src="xxx.js"></script>'; // file to grab images
var tag2 = '<img src="some image link"></img>';
$('#test').append(tag); //testing
$('#test2').append(tag2); //testing
});
On HTML
<div id="test"></div> <!-- Not Working! -->
<div id="test2"></div> <!-- This Works! -->
<div id="test"><script src="xxx.js file to grab images"></script></div> <!-- This Works too! -->
Edit with more info below:
I've actually looked for solutions over the net and most of the answer are almost the same as the ones given here. In my case, it is slightly different from the others. That's because the tag variable is actually a must from database.
<?
$result = mysql_query("SELECT code FROM users_loc WHERE method='script'") or die(mysql_error());
$row = mysql_fetch_array($result);
?>
and on javascript side:
$(document).ready(function() {
var tag = <? echo $row['code'] ?>;
var tag2 = <? echo $row2['code'] ?>;
$('#test').append(tag); //testing
$('#test2').append(tag2); //testing
});
On my site, users will input their external image source into my database, and I will grab the source and display it on my site. But the problem arise when a user put in a <script> tag which works if it were hard coded into the <div>
I kept having this error message on my console "A call to document.write() from an asynchronously-loaded external script was ignored."
I hope this answers the confusions. Thanks.
Edit: I think this is the problem with append: Does Jquery append() behave asynchronously?

It all because about the parsing problem. The problem showing up after found </script> this code. It's assume we want to close the script tag but we won't. In order to avoid that, put \ before / like so to escape special character :
$(document).ready(function() {
var tag = '<script src="xxx.js"><\/script>'; // file to grab images
var tag2 = '<img src="some image link"></img>';
$('#test').append(tag); //testing
$('#test2').append(tag2); //testing
});
DEMO
Try inspect the element in chrome to see the code.

Try it:
var script = document.createElement( 'script' );
script.type = 'text/javascript';
script.src = 'xxx.js';
$('#test').append(script);

If it matters where in the source order the script tag is injected, Mario Araque's solution is for you. If it does not matter, R3tep's solution does the job nicely.

Related

Need To Get Featured Image URL From External Site Looking At WP Page [duplicate]

I'm trying to get Facebook's meta tags from my HTML.
I'm using simple html dom to get all html data from the site.
I've tried with preg_replace, but without luck.
I want for example to get the content of this fb meta tag:
<meta content="IMAGE URL" property="og:image" />
Hope someone can help! :-)
I Was going to suggest to use get_meta_tags() but it seems to not work (for me) :s
<?php
$tags = get_meta_tags('http://www.example.com/');
echo $tags['og:image'];
?>
But I would rather suggest using DOMDocument anyways:
<?php
$sites_html = file_get_contents('http://example.com');
$html = new DOMDocument();
#$html->loadHTML($sites_html);
$meta_og_img = null;
//Get all meta tags and loop through them.
foreach($html->getElementsByTagName('meta') as $meta) {
//If the property attribute of the meta tag is og:image
if($meta->getAttribute('property')=='og:image'){
//Assign the value from content attribute to $meta_og_img
$meta_og_img = $meta->getAttribute('content');
}
}
echo $meta_og_img;
?>
Hope it helps
As per this method you will get key pair array of fabcebook open graph tags.
$url="http://fbcpictures.in";
$site_html= file_get_contents($url);
$matches=null;
preg_match_all('~<\s*meta\s+property="(og:[^"]+)"\s+content="([^"]*)~i', $site_html,$matches);
$ogtags=array();
for($i=0;$i<count($matches[1]);$i++)
{
$ogtags[$matches[1][$i]]=$matches[2][$i];
}

Getting DOM elements after div updated from load php file

I have an html file with a div that gets updated by a php file. The php file puts a single book's title and author into the div, that works.
I am trying to use getElementById to get the book's title getElementById('btitle') and author name getElementById('authr') when I click a button because I need to use that information. I am not getting the value of the btitle or authr ids. If I assign the whole div to a variable I get all of the div but I want them separate and the getElementByID() is not working.
Any help is appreciated.
a.html
'<div id='books'> </div>
addbooks.php
echo <stitle id='btitle'>Foundation</stitle>
echo <author id='authr'>Asimov</author>
Try putting your javascript just before the closing </body> tag. Otherwise, if your javascript is in the head, it is looking for an element that has yet to be rendered to the DOM.
I tested the following and it returns the elements as you would expect.
<?php
echo "<stitle id='btitle'>Foundation</stitle>";
echo "<author id='authr'>Asimov</author>";
?>
<script type="text/javascript">
var title = document.getElementById('btitle').textContent,
author = document.getElementById('authr').textContent;
alert(title + " by: " + author);
</script>

PHP: Reading DOM info of own HTML page

So, let's say I have only one file on my server called index.php :
<!DOCTYPE html>
<html>
<body style="background-color: orange;">
<!-- On/Off button's picture -->
<?php
echo ("<img id='button' src='data/button.jpg' alt='off'/>");
?>
</body>
</html>
Now, let's say I attach a JavaScript that changes the buttons ALT to ON when I click the button at some point.
How can I read the DOM elements on this page using PHP?
So far, I've found this code:
$dom = new DOMDocument;
$dom->loadHTML($html);
$main = $dom->getElementById('alt');
but I can't figure out how I would fit that in my code above, what page should I call loadHTML() for?
How do I make PHP read DOM elements it generated using echo?
First of all, your button has id button, so searching for the id alt would return no results.
Second: The piece of php you found reads a page $html (probably file_get_contents('some_url'), puts it in the variable dom and parses it, searching for the id alt. In your case it would read your own page, breaking it down in pieces looking for that button.
Thats of no use if you can read the status with javascript on your own page. You can then pass it to php trough an ajax-call or by adding it to the url like mypage.php?button=off
$main = $dom->getElementById('button');

Auto refreshing div with javascript

Trying to refresh a div every 60 seconds, using the following javascript:
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load').fadeOut('slow').load('index.html #load').fadeIn("slow");
}, 60000);
</script>
Here is the corresponding div:
<div class = "well" id="load">
<center><h3><i class="icon-bar-chart"></i> Mt.Gox</h3></center>
<center><h3>Ƀ1 = <?php echo $usd; ?> USD</h3></center>
<hr>
<center><h3><i class="icon-bar-chart"></i> BTC-e</h3></center>
<center><h3>Ƀ1 = <?php echo $usde; ?> USD</h3></center>
</div>
The div is currently not refreshing at all.
Thanks for any help!
Ok that's because you are using the script incorrectly., You need to use callbacks as below
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#load').fadeOut('slow',$(this).load('index.html #load',
function(){
$(this).fadeIn("slow");
})
)
}, 60000);
</script>
Edit: I misunderstood the code a bit so ignore my original comment below!
Try to remove the #load in the url. It's perfectly valid according to the jQuery API, but I think in this case it can cause reduncancy.
That is, make it like this instead:
$('#load').fadeOut('slow').load('index.html').fadeIn("slow");
When you call .load() on an element it will load into that element, if you also specify the same element in the Url to load - I think it can cause a problem.
Please see this link: Origin null is not allowed by Access-Control-Allow-Origin
Also that issue, I think that you shouldn't load html data via file:/// URL. Why don't you load a div in the same file. Forexample:
$('#load').fadeOut('slow').load($('#test').css('display', 'inline')).fadeIn("slow");
and the div tag is like this:
div id="test" style="display:none;"

WP get page content

I'm trying to retrieve page content in a javascript function. When I echo the test variable $htmlblock, the javascript lightbox works perfectly. But when I echo $contactinfo, it opens the page in a new tab.
<?php
// retireve content from "contact" page
$contactpageid=85;
$contactpage = get_page($contactpageid);
$contactinfo = apply_filters('the_content', $contactpage->post_content);
//test variable
$htmlblock = '<strong>Contact Information</strong><br/><table><tr><td id="name"><strong>NAME</strong></td><td id="phone">888-8888</td><td id="email">name#email.com</td></tr></table>';
?>
<script language="javascript" type="text/javascript">
function openLightbox() {
lightbox('<?php echo $contactinfo; ?>');
}
</script>
$contactinfo possibly contains HTML tags, where as $htmlblock is just a simple string.
I'm not sure you can do this with that Lightbox. You may want to check with the Lightbox docs (of the version you are using) on how to insert HTML content.
Or, you could try stripping out the HTML.
$contactinfo = apply_filters('the_content', strip_tags($contactpage->post_content));
http://php.net/manual/en/function.strip-tags.php

Categories