This question already has answers here:
Can scripts be inserted with innerHTML?
(26 answers)
Closed 8 years ago.
Hi I am trying to insert a JavaScript code in my HTML document using the following AJAX-PHP code inside the function called exJS(), following is the content of the function exJS()
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.php", false);
xmlhttp.send();
This what ajax.php is
<?php
echo '<script language="javascript">
alert("Hello World");
var testVAR = "Hello World";
</script>';
?>
Now whenever I execute this function exJS() the alert doesn't work but when I view the source code using F12 and see the contents of the div#myDiv" I see that the entire script is embedded inside the div but still the JavaScript for some reason is not getting registered.
I even tried accessing the JavaScript variable testVAR, I see the variable in the source code when I hit F12 but when I try to access that variable I get an error, that no such variable is defined.
Please note that it is simple example so there is no error and that the PHP code is echoing just fine, all the contents are returned from the PHP code, when I view the code and see what are the content of the div element the entire PHP echo content is present there but still not executing.
Also if I open the ajax.php file directly it works fine, I mean I get the alert message, but the same thing doesn't happen when I execute the function jsEx() the JavaScript code gets inserted into myDiv but nothing happens, no alert.
BTW jQuery has a specific AJAX function to get a script: http://api.jquery.com/jquery.getscript/
If you want to avoid jQuery a workaround would be to make it so you echo an iframe and from that Iframe you link to the PHP generating the actual Javascript.
E.G. a sample ajax.php
if( isset($_GET['getscript']) ){
header('Content-type: application/javascript'); #or header('Content-type: text/javascript');
echo 'alert("The script is working.")';
exit;
}
echo '<iframe src="ajax.php?getscript=1" frameborder="0"/>';
?>
try this:
tested in my WAMP (win 7, php 5.4) & works fine in IE11,Chrome,Safari,FireFox and Opera (I don't have any other ;-) )
index.html:
<head>
<title>Testing DYNAMIC JS</title>
<script type="text/javascript">
function exJS(){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var script = document.createElement('script');
script.onload = function() {
// alert("Script loaded and ready");
};
script.setAttribute("type","text/javascript");
script.text = xmlhttp.responseText;
document.getElementsByTagName('head')[0].appendChild(script);
}
}
xmlhttp.open("GET","ajax.php", false);
xmlhttp.send();
}
</script>
</head>
<body onload="exJS();">
</body>
</html>
in ajax.php try:
<?php
echo 'alert("Hello World"); var testVAR = "Hello World";';
?>
if you want to run script from within a div:
use:
javaScript:
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var MyDiv=document.getElementById("myDiv");
var arr = MyDiv.getElementsByTagName('script');
for (var n = 0; n < arr.length; n++)
eval(arr[n].innerHTML);
}
and php:
<?php
echo '<script language="javascript">
alert("Hello World");
var testVAR = "Hello World";
</script>';
?>
hope it'll help you.
Related
I have this JavaScript:
<script>
if (str == "") {
document.getElementById("txtHint1").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "/npsmart/umts/action_plano/?q=" + query1, true);
xmlhttp.send();
}
</script>
And this JavaScript call a page called getuser.php.
This is the code of getuser.php:
<!DOCTYPE html>
<html>
<body>
<p id="dumb"></p>
<script>
document.getElementById("dumb").innerHTML = "WORK";
</script>
</body>
</html>
What I would like is only to change the paragraph content, called dumb, to WORK. But when I call the page and it loads, my paragraph content keep null.
It's like my Ajax Call Request don't execute the Script Tag.
EDIT:
I have already solved my problem with this simple but genious solution:
function showUser() {
if(query_num == 2){
if (str == "") {
document.getElementById("txtHint1").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
eval(document.getElementById("runscript").innerHTML);
}
};
xmlhttp.open("GET","/npsmart/umts/action_plano/?q="+55555,true);
xmlhttp.send();
}
And in my getuser.php file:
<script type="text/javascript" id="runscript">
document.getElementById("dumb").innerHTML = "WORK";
</script>
I just putted the : eval(document.getElementById("runscript").innerHTML); in my function and then in the php file I called this script using this:
<script type="text/javascript" id="runscript">
So thanks everybody =)
Hope this post can help other people.
JS is not executed automatically from a script embedded in the response.
Since getuser.php is a PHP script there's no need to use JS and have the browser set the paragraph content. Use PHP itself:
<!DOCTYPE html>
<html>
<body>
<p id="dumb"><?php echo 'WORK'; /* or anything else */ ?></p>
</body>
</html>
Otherwise you'll have to use JS eval on the returned AJAX response to have the browser run the JS returned from your script. But I recommend against this.
I have three divs saved in an array as simple_html_dom objects. I needed to change a CSS property of two of them on the click of a button. That's easy, but then I also need to make that change in the CSS property (in the simple_html_dom object stored in the aforementioned array) in the PHP script on the server side.
So I figured from my web search I needed AJAX for this. So I read up this tutorial, and I am following this example, and doing something like:
On the client side:
function xyz(var divIdOne, var divIdTwo) {
document.getElementById(params.divIdOne).style.display = "none";
document.getElementById(params.divIdTwo).style.display = "block";
document.getElementById(params.divIdTwo).style.border = "5px solid red";
var xmlhttp;
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest();}
else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.open("GET","myfile.php?pass_back="+"pass_back",true);
xmlhttp.send();
}
On server side:
foreach($_REQUEST as $requestkey => $requestvalue) {
echo $requestkey.': '.$requestvalue;
}
if (array_key_exists('pass_back', $_REQUEST)) {
foreach ($array_of_divs as $div) {
if ($div->id=$divIdOne) {
$div->style='display:none';
} else if ($div->id=$divIdTwo) {
$div->style='display:block';
}
}
} else {echo 'FALSE!';}
The first foreach loop prints other variables but does not print pass_back. The next if block does not execute at all. The else block executes. This means that $_REQUEST clearly does not contain pass_back. Can anyone pinpoint why, or what I did wrong?
I fail to see the error. How do you check that you're not sending the data properly? I suggest using this piece of code in order to check what your server is receiving from your request:
function xyz() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);// Let's see what the server is echoing
}
}
xmlhttp.open("GET","myfile.php?pass_back="+"pass_back",true);
xmlhttp.send();
}
Please, let us know the output.
I would recommend that you use jquery and firebug, and first get rid of the following problem: why is passback variable not received.
Create the file: test.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<title>Html page</title>
</head>
<body>
<script>
(function($){
$.post("myfile.php", {
passback: "pooo"
}, function(d){
console.log(d);
});
})(jQuery);
// or if you cannot use jquery
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// do something with the response, if you need it...
// document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "myfile.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("passback=pooo");
// src: http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp
</script>
</body>
</html>
Then create the file: myfile.php
<?php
if(isset($_REQUEST['passback'])){
echo "ok";
}
else{
echo "oops";
}
Next, download firefox, and download the firebug extension (or you can use chrome's console alternatively). The goal here is to see what is being passed through the network.
Launch test.php in a browser, open the firebug console (or chrome's console),
and debug until you see the "ok" message.
I want php to return a value to ajax. I'm following W3 schools example but no joy.
Here is the javascript/ajax code:
function createReport() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
I have the following call inside an event handler that I know is triggering (other stuff it does is working fine)
createReport();
and later in the body section of the html I have:
<div id="report">Report will be placed here...</div>
If I run test.php by itself, it correctly shows "return this to ajax" so I know that's working. Here is the php code:
<?php
echo 'return this to ajax';
?>
My understanding is that "Report will be placed here..." will be replaced with "return this to ajax". But nothing happens. I don't see any errors listed in the firefox or IE consoles either. Any ideas?
I personally do not think the w3cschools a good place to learn ( see http://www.w3fools.com/ ).
It may be that the problem occurs because of the order that you set the ajax, you did:
XMLHttpRequest/onreadystatechange/open/send
is preferable (if you do not follow this order may occur several flaws in older browsers):
XMLHttpRequest/open/onreadystatechange/send
Note: do not worry, the "open(...)" does not start listeners.
Listeners only work after the "send(...)"
Another reason may be that you did not create "error handling" of XMLHttpRequest.status, it serves to verify faults in the server response.
Try this:
<script>
function XHR(){
if(window.XMLHttpRequest){//outers browsers
return new XMLHttpRequest();
} else if(window.ActiveXObject){//IE
try{
return new ActiveXObject("Msxml2.XMLHTTP");
} catch(ee) {//IE
try{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(ee) {}
}
}
return false;
}
function createReport(){
var xhr = XHR();// call ajax object
if(xhr){
xhr.open("GET", "test.php", true);//setting request (should always come first)
xhr.onreadystatechange = function(){//setting callback
if(xhr.readyState==4){
if(xhr.status==200){
document.getElementById("report").innerHTML=xhr.responseText;
} else {//if the state is different from 200, is why there was a server error (eg. 404)
alert("Server return this error: " + String(xhr.status));
}
}
};
xhr.send(null);//send request, should be the last to be executed.
} else {
alert("Your browser no has support to Ajax");
}
}
</script>
<div id="report">Report will be placed here...</div>
<script>
createReport();//prefer to call the function after its div#report
</script>
To prevent cache, replace:
xhr.open("GET", "test.php", true);
by
xhr.open("GET", "test.php?nocache="+(new Date().getTime()), true);
At first glance I don't see anything wrong on your js code, so I bet it will probably be a problem locating test.php in your folder structure.
With firebug check the call your javascript AJAX it's doing, and check if the file test.php is being correctly assesed.
I did not find anything wrong with W3Schools' Ajax example, after testing the code that follows (which was pulled from their Website).
Possible factors:
Missing <script></script> tags
Make sure you have JS enabled.
Make sure your browser supports it.
You may have forgotten to change the button's call to the proper function.
Working and tested code using FF 26.0 and IE version 7
Pulled from W3 Schools Website (example) and slightly modified to prove this works.
Result when clicking on the Change Content button:
return this to ajax - as per your PHP code.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="report"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
PHP used: (test.php)
<?php
echo 'return this to ajax';
?>
Other possible factors:
If on a local machine, your server doesn't support PHP or is not parsing PHP properly, or is either not installed or configured properly.
If on a hosted service, make sure PHP is available for you to use.
Files are not in the same folder as executed from.
try{
request = new XMLHttpRequest();
}catch(trymicrosoft){
try{
request = new ActiveXObject("Msxml2.XMLHTTP");
}catch(othermicrosoft){
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}catch(failed){
request = false;
}
}
}
if(!request)
{
alert("Error initializing XMLHttpRequest!");
}
function Create_Ajax_Query(LinkToFile,Parametrs)
{
window.document.body.style.cursor='progress';
request = new XMLHttpRequest();
var url = LinkToFile;
var params = Parametrs;
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = newinfo;
request.send(params);
}
function newinfo()
{
if(request.readyState==4 && request.status == 200){
window.document.body.style.cursor='default';
alert(request.responseText);
}
}
Hope its useful!
The code looks correct. it runs just fine on a local environment.
I would advise to look at the "Network" tab in the developer tools to detect any errors may occurs on the server side. You can also use console.log() to follow the javascript actual flow:
function createReport() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
console.log(xmlhttp); //to show the entire object after statechage.
console.log(xmlhttp.readyState); //to show specific parameter.
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
The objective is to display a list of URLs in an HTML page. The list is retrieved from another file (currently in XML-format).
Validator: What is the proper xHTML mark-up for a list generated by JavaScript and still validate properly?
I assume the reason is that JavaScript-code inside [ul]'s is not accepted. Is this correct? Is there another solution?
The code below does produce the list anticipated, but it creates a warning (pls see below, 2.).
<ul>list A
<li>item A1</li>
<li>item A2</li>
<ul>List B
<li>item B1</li>
<script type="text/javascript">/* <![CDATA[ */
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.open("GET","/test-code/panorama-list2.xml",false);
// xmlhttp.open("GET","/test-code/panorama-list2.xml",true); //this does not work. xmlDoc is null.
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{ document.write('<li class="menu2">'+'<a href="');
document.write(x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue);
document.write('">');
document.write(x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue);
document.write('</li>'); }
//]]></script> //This is line: 136
</ul>
The JavaScript used in the code above is called using the synchronous method and thus creating the Warning:
"An unbalanced tree was written using document.write() causing data from the network to be reparsed. For more information https://developer.mozilla.org/en/Optimizing_Your_Pages_for_Speculative_Parsing
/ Source File: /test-code/index2.htm / Line: 136"
The solution is to use the asynchronous method similar to the code below placed into the section.
The solution is NOT to simply setting 'true' in the function xmlhttp.open (..., ..., true);.
<script type="text/javascript">//<![CDATA[
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{ xmlhttp=new XMLHttpRequest(); } // code for IE7+, Firefox, Chrome, Opera, Safari
else
{ xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } // code for IE6, IE5
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
xmlDoc = xmlhttp.responseXML;
var txt = "";
var txt1 = "";
var x = xmlDoc.getElementsByTagName("item");
for (i=0;i<x.length;i++)
{
txt = x[i].getElementsByTagName('description')[0].childNodes[0].nodeValue + "<br />";
txt1 = x[i].getElementsByTagName('link')[0].childNodes[0].nodeValue + "<br />";
}
{
document.getElementById("myDiv").innerHTML=txt;
document.getElementById("myDiv1").innerHTML=txt1;
}
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
//]]></script>
That does take care of the Warning.
I assume a solution would be to combine these 2 examples of code.
That's what I am trying:
The Variables 'txt' and 'txt1' retrieve the last entry of the XML-file.
How do I get all entires as well? The amount of entries varies.
Here is the big question:
How can I create a proper list using the asynchronous method and obtain a result like in the initial code example where the list is generated by stepping through the XML-file?
After all, is there is another, better or simpler solution? The file with data for the list shall not be part of the xHTML mark-up.
At last an actual page using the initial code example. The list is revealed by hovering over the button at top-right: http://www.halo-photographs.com/2011-Cascata-da-Bernina/index.htm (yes, this is my own page)
Thanks for your attention.
you code is an soup..
you need refactor that
now with jquery
in the load the you page
you should put somthing how that
$(document).ready(function(){
BeforePrepareList();
});
function BeforePrepareList()
{
var xmlRequest = XmlHttpRequestResolver();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
var xmlDoc = xmlhttp.responseXML;
// you need parse string response a array or use xslt, the next
// is simple for each
ListSetting(xmlDoc);
}
xmlhttp.open("GET","panorama-list2.xml",true);
xmlhttp.send();
}
function XmlHttpRequestResolver()
{
if (window.XMLHttpRequest)
return xmlhttp=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
else
return xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
function ListSetting(rawdata)
{
ListPopulate($("_PUT_YOUR_LIST_ID_HERE").get(0), rawdata);
}
function ListPopulate(el, items) {
el.options.length = 0;
if (items.length > 0)
el.options[0] = new Option('All', '');
// THAT IS AN SIMPLE EXAMPLE, CHANGE FOR CREATE tag <a />
$.each(items, function (index,item) {
el.options[el.options.length] = new Option(item.[PROPERTY_A], item.[PROPERTY_B]);
});
}
and .....
more information here
invoke xml and transform http://www.ibm.com/developerworks/xml/library/x-ffox3/index.html
examples de http request http://www.jibbering.com/2002/4/httprequest.html
I am trying to get the javascript function in ajax call. My code works fine and returning back my javascript code but there is a problem in my received javascript function. Here is my code for Ajax..
function media_type(id)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
eval(document.getElementById("asad").innerHTML=xmlhttp.responseText);
}
}
xmlhttp.open("GET","video/media_type.php?cat_id="+id,true);
xmlhttp.send();
}
And her is the code where i am returning a simple hello world alert box.
if($num_rows==0)
{
//echo("Sorry no record found.");
echo'<script type="text/javascript">
alert("hello World");
</script>';
}
I am receiving the code back exactly but code is not executing. Please tell me how i can fix this issue. Thanks in advance.
Can I ask why you need to return JavaScript from the server? How about you return a simple response (string, boolean, number) from the server, and execute something that already lives on the client based on the return value? Much safer and easier. It may not be the solution you are looking for, but your js-fu will be much stronger for it.
Just return the JS that you want to execute (alert("hello World");) and make an eval. Remove <script type="text/javascript"> and </script>
eval(xmlhttp.responseText);
will be:
eval('alert("hello World")');
i will try with this
if($num_rows==0)
{
//echo("Sorry no record found.");
echo'<html><script type="text/javascript">
alert("hello World");
</script>
</html>';
}
i think this line is creating problem
eval(document.getElementById("asad").innerHTML=xmlhttp.responseText)
that is
eval(document.getElementById("asad").innerHTML='<script>alert("Hi");</script>';)
getting converted to
eval(document.getElementById("asad").innerHTML='< script > alert("Hi");</script>';)
I had this issue the other day...
you have to set your header in the php page to Content-Type: text/javascript; charset=utf-8
Here is the Entire Code to make this work
For your php file
<?php
header("Content-Type: text/javascript; charset=utf-8");
echo'<script type="text/javascript">
alert("hello World");
</script>
';?>
and here is the Javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js" type="text/javascript"></script>
<script>
$.ajax({
type:'POST',
url:'toget.php',
success:function(d)
{
$(document).append(d);
}
});
</script>
//try using this
<?php
if($num_rows==0)
{
//echo("Sorry no record found.");
?>
<script type="text/javascript">
alert("hello World");
</script>
<?php
}
?>