Appending script with document.write synchronous - javascript

I've encountered a problem when appending script to html. Here is a sample code:
<script>$('body').append("<script type=\"text\/javascript\" src=\"http:\/\/localtest\/test.php\"><\/script>");</script>
test.php source
<?php sleep(1); ?>
document.write('<div></div>');
HTML inside append function can be any html, not necessarly a script. It works unless I got HTML mentioned in example.
Result
JS code from test.php is not executed because it's blocked by browser (I'm using FF): "A call to document.write() from an asynchronously-loaded external script was ignored."
I'm not able to modify test.php content, it's loaded from external server.
Wy it is executed async? How to force sync execution?

I think you must use
$(window).ready(function() {
//put your code here
});
berfore appending.
So, complete code would be like this
<script type="text/javascript">
$(window).ready(function() {
$('body').append("<script type=\"text\/javascript\" src=\"http:\/\/localtest\/test.php\"><\/script>");
});
</script>

Related

How load and execute (scoped) script by $.getScript()

I need to dynamically load script wrapped like this:
{
(function () {
"use strict";
function myFunction() {
// code
}
myFunction();
})();
}
I i use jquery function $.getScript() script is loaded, but no executed. (in webmaster tools i can see request and response - script is here with content)
How i can load and automaticly execute script like this?
I was solve this problem with another ajax request not to javascript file but to html file (html response) with basic tag script with url address. Also with passed some variables into it.
So my html looks like this:
<script type="text/javascript">
var varPassedToScript = 1;
</script>
<script type="text/javascript" src="https://www.urlToScript.com/script.js"></script>
And it works...
If anybody have better solution - i'm curious

Javascript not working when echo'd by php

I have the problem when i echo this:
echo "Logged in! <script> alert('hello'); </script>";
The message "Logged in!" appears, but not the alert. How can i fix it so i get the alert? I can't use header(); because i already echod things out!
I also tried multiple thing like:
echo "Test message <script> window.location.href = 'index.php';"
Same thing again, Test message was echo'd, but the script wasn't run.
I hope someone can help me!
Edit:
NOTE: All of this code is in a xml file that i get that response of and put that in a div. So the script is in a message that i get with responseXML and output the data in a div.
Question i have in 1 sentence: How can you run a javascript function in a ajax call without jquery?
I'm guessing you call this script through ajax after the page is already loaded. In this case it's not surprising the script isn't running because the browser runs the scripts as it reads them and isn't on standby for another script tag to appear.
If this is the case, you can solve this by adding some event listener or even better, call a desired function in the end of the ajax response.
Your PHP looks fine, but you might need to change the way that you collect the JavaScript.
Consider this example:
http://jsfiddle.net/0vcewvkc/1/
If you are collecting JavaScript only, you can wrap the response in a jQuery tag ($()), and then append it to your document.
$("#go").click(function() { // call the function here
// your ajax code would go here, but either way you will end up with a string of JavaScript
var response = '<script>alert("hi");</' + 'script>';
// use jQuery to append this script to your document's body, like so:
$(response).appendTo(document.body)
});
Update
To do this without jQuery, the end of your AJAX call would have this code:
var response = 'alert("hi");'; // note that we have removed the <script> tag
var s = document.createElement("script");
s.innerHTML = response;
document.getElementsByTagName('body')[0].appendChild(s);
try the following this should work
<?php
echo 'Logged in ';
?>
<script> alert("hello")</script>;
<?php
// the rest of your php code
?>

Executing script written inside the div when the div dynamically loads on to the page

I have a div which looks like
<div>
//Useful content
<script type="text/javascript">
function(){
//some useful code
}
</script>
</div>
Now am getting this div as a response of an Ajax call and appending that into body. Now when the gets appended to body, the function inside the script tag should get executed. But not.. what is the problem here?
You should be using document.createElement("script"); if you need to insert some script dynamically. This is recommended approach.
Anyway, following code is working just fine for me:
var str = "<script>alert('Hi!');</scr"+"ipt>";
$('#container').append($(str)[0]);
Make sure you escape you script properly.
Your function is not executing because it is not being called.
You should use a self-executing function that will just run as soon as it's loaded:
(function() {
alert('hello world!');
})();

Javascript Document.write Issue

I'm trying to get the lines of code below to help me write "<?php include('like.php'); ?>" on a page only when the visitor isn't using a a mobile device but it doesn't seem to be working. Any ideas on how to get it to work?
<script type="text/javascript">
<!--
if (screen.width > 699 {
document.write("<?php include('like.php'); ?>")
}
//-->
</script>
By the time JavaScript is writing to the document, it's too late - PHP has already sent everything to the browser. Your next best approach would be to make an AJAX call to fetch the content and append it to the DOM.
Assuming you're willing to use a JavaScript framework like jQuery, it's quite simple:
if (screen.width > 699) {
$.ajax({
url : '/like.php',
dataType : 'html',
success : function(data) {
$('#myContainer').html(data);
}
});
}
http://api.jquery.com/jQuery.ajax/
As others have mentioned, you can not have JavaScript include a piece of PHP-code and have it executed. As PHP is run server-side, before the page is served to the client, injecting the code like you suggest would just write <?php include('like.php'); ?> as plain text to the document.
You could however load the content of like.php through Ajax and inject it into the DOM, if a certain criteria is met.
With a library like jQuery, it is quite easy, as it provide a method .load() that let you load content into the DOM like that. You could do it something like this:
// Wait for the DOM to be ready
$(function () {
// Check the width of the screen
if (screen.width > 699) {
// Load the content and add the HTML to an element
$('#id-of-element-to-add-content-to').load('like.php');
}
});
In the above example, the content of like.php will be loaded into the HTML-element with id id-of-element-to-add-content-to, but you could use any selector you like, that match your need. If you want to replace the entire body of the page, your could do $('body').load('like.php'); instead.
More about the available jQuery selectors: http://api.jquery.com/category/selectors/
javascript executes on the browser and php executes on the server so, you need to add an if condition and then include
you could test the user agent server side and append that line if not from a mobile device

Execute JavaScript code at the end when the HTML has been loaded

I want to execute a function at the end when the HTML has been loaded. I tried it with onload without success. I also tried it with ready, but it still doesn’t work. Here is my code. This is again placed in the header:
<script type="text/javascript">
$(document).ready(function() {
$('#infowindow_content').html('test');
});
</script>
The div is also set by an external JavaScript file. Content:
window.onload = initialize;
function initialize() {
document.getElementById('infowindow_content').innerHTML = 'testa';
}
It is included the following way before the closing body tag:
<script type="text/javascript" src="../lib/functions.js"></script>
I tried to place the above code before the closing body tag, but currently I have no idea why this doesn't work (the content isn't changed by my JavaScript code). If I execute it on the console afterwards everything works fine.
Solution:
I set a configuration parameter (language) in the HTML file. In the JavaScript file I ask for this value and depending on the value I define another content. Sometimes it could be so simple ...
Try this:
setTimeout(function() {
$(document).ready(function() {
$('#infowindow_content').html('test');
});
}, 20);
I don't know the jQuery equivalent but try the native JS.
Since the <body> has the most HTML & loads after <head>...
document.body.onload=function(){
yourFunction(args)
}
<body onload="yourFunction(args)">...</body>
Or maybe the window object, since it's the root of every webpage DOM...
window.onload=function(){
yourFunction(args)
}
Always place DOM manipulating code directly before your </body> tag. JavaScript in the header should only be called to libraries, such as jQuery.

Categories

Resources