Javascript not executed in Ajax responseText - javascript

The following is not my actual project, but an example that has the same problem as my project.
Here's the main HTML page snippet:
<div id="divExample">Before</div>
<script type="text/javascript">
loadExample();
</script>
Here's the javascript file snippet:
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById('divExample').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","mypanel.html",true);
xmlhttp.setRequestHeader("If-Modified-Since", "Sun, 31 Dec 1899 23:59:59 GMT");
xmlhttp.send();
Here's the fetched mypanel.html:
After
<script type="text/javascript">
alert("Fetched script is working.");
</script>
When I load the main HTML page, the AJAX javascript runs fine. It fetches mypanel.html and puts its contents in divExample.innerHTML. The word "After" correctly shows instead of "Before".
However, the script with the alert never executes. I would not like to separate the alert script from mypanel.html. Any ideas how I can make it execute after AJAX loads it?
I've read here that this can be done.
I've read here that this cannot be done.
Any ideas how to make it happen?

You would want to take care to prevent arbitrary code from being run, but something along these lines could work:
...
if(xmlhttp.readyState==4 && xmlhttp.status==200)
{
var myDiv = document.getElementById('divExample');
myDiv.innerHTML = xmlhttp.responseText;
var myScripts = myDiv.getElementsByTagName("script");
if (myScripts.length > 0) {
eval(myScripts[0].innerHTML);
}
}
...

In case for people, who still can't figure out,
1- check if your xmlhttp contains response key.
2- If present, then use xmlhttp.response instead of xmlhttp.responseText;
** if php is your backend server, do print_r(javascrip_code_as_string); then return;

Related

When running javascript loop with internal call to code behind, the code behind runs only the first time

When running Javascript loop,calling code behind with data, only the first line is showing. I need to get every time another value without reloading the page.
Here is the sample:
for (var counter = 0; counter < 50; counter++) {
val = <%= GetLon("500") %>;
alert (val);
}
It calls only one time!!
OK. I found this response:
You can use an XMLHTTPRequest to call a server side code page. Once
the server has processed the code, it will call back to the client
with the processed page. You then use the call back function to pull
whatever data you need out of the result. The whole process is called
AJAX.
function ajaxExample() {
var xmlhttp;
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("someID").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax.asp?q="+str,true);
xmlhttp.send();
}
I didn't tested it yet, but looks to be the correct answer!

Writing in another file with javascript

I have a php script (just for calculation) and a html file. Let's say the php file has finished its calculation and the solution is 10. The following line is in the body of the just mentioned html file:
<div id="here"></div>
Now I want the php file to write the 10 into the html. I thought of adding a few lines of javascript at the end of the php to make the job. The question is if this is even possible with something like (index.html).getElementById(here).innerHTML or something. Both files are in the same folder and setting the proper permission shouldn't be a problem.
I know I could put everything in one file but this is part of a bigger project. I just adapted my problem on this simple example to avoid that you need to read plenty of lines.
Your Script should look like this to get response from PHP
<script>
function loadDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("here").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "yourphp.php?q=" + str, true);
xmlhttp.send();
}
</script>
Hope this solves your problem
ref: http://www.w3schools.com/ajax/ajax_php.asp
PHP is server-side and Javascript is client-side. I don't recommend you to use embedded PHP but you should take a look at Ajax Requests.
Here's some documentation

what is wrong with my javascript structure

I am really new on javascript. I want to read xml from an url and want to parse it on html. I have html and javascript codes like that:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function loadXMLDoc(filename)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else // code for IE5 and IE6
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",filename,false);
xhttp.send();
return xhttp.responseXML;
}
xmlDoc=loadXMLDoc("http://www.w3schools.com/dom/books.xml");
x=xmlDoc.getElementsByTagName("title")[0];
y=x.childNodes[0];
document.write(y.nodeValue);
</script>
</body>
</html>
What is wrong ? thanks
This is the standard method to do this task:
Since people keep going along the path of trying to use cross domain for something other than JSONP... IT WILL NOT WORK!
The following code below is an example of what will work, as your server is allowed to get content from other network locations being its more controlled.. Your browser on the other hand can only receive JSONP or PLAIN TEXT... Most google results should explain this as well..
YOUR ONLY OPTION
Is to use a PROXY of some form to obtain what your trying to access, So you only have three choices here.
Use JSONP or Plain Text
Use a Proxy or some other method that is local to your server/website/script/page
Keep trying to use examples posted here after being told cross domain rules apply.
JAVASCRIPT:
function loadXMLDoc(sURL) {
$.post( "myproxy.php", { requrl: sURL }).done(function( data ) {
alert(data);
console.log(data);
document.write(data);
});
}
PHP: myproxy.php
<?php
header('Content-Type: application/xml; charset=utf-8');
$file = file_get_contents($_POST['requrl']);
echo $file;
?>
Please note that is you plan to use this with other types of content then you will need to change/remove the header line.
YOUR BROWSER ALLOWS YOU TO AJAX XML FROM OTHER WEBSITES
If this is the case, then you need to replace or update your web browser..
THE ABOVE SOLUTION IS NOT COMPLEX
This is virtually copy and paste code ready to go, The JS function will return the result/data/content in the three most know ways...
The PHP script is a copy and paste as well.. So if you have PHP installed.
All you would need to do is create a new text file in the same location as your html document and name it as "myproxy.php" and this example will work.
This is a proper XmlHttpRequest with a callback function to handle your XML:
<!DOCTYPE html>
<html>
<head></head>
<body>
<script type="text/javascript">
function loadXMLDoc(url){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
callbackFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function callbackFunction(response){
if (window.DOMParser){ // Non IE
var parser = new DOMParser();
var xml_doc = parser.parseFromString(response,"text/xml");
}else{ // Internet Explorer
var xml_doc = new ActiveXObject("Microsoft.XMLDOM");
xml_doc.async = false;
xml_doc.loadXML(response);
}
// Do something with your 'xml_doc' object variable here
console.log(xml_doc) // Debugging only.. to see the XML in the browser console for your own reference
var x = xml_doc.getElementsByTagName("title")[0]
var y = x.childNodes[0];
document.write(y.nodeValue);
}
// Call the function to begin code execution
loadXMLDoc('http://www.w3schools.com/dom/books.xml')
</script>
</body>
</html>
This is working code so you can just erase what you have and put this directly in place of it. Good luck!
If you're planning on hosting the file on your own server to access via XHR, the code I offered is intended for that. If w3schools.com had a 'Access-Control-Allow-Origin: *' header on the XML file your are requesting, it would also work. But they don't. So you need to have the XML file in a place where your browser's security will let you access it (same domain origin as your webpage). Otherwise your browser will continue to block the resource with a 'cross-origin-request-blocked' error in the console.

if (xmlhttp.readyState==4 && xmlhttp.status==200) in AJAX not executing

I was trying ajax on my page. But it is not working as if (xmlhttp.readyState==4 && xmlhttp.status==200) is always false. I have alerted the values of xmlhttp.readyState and xmlhttp.status. There values are always 1 and 0 respectively for xmlhttp.open event and 4 & 0 respectively for xmlhttp.close event.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function captcha_check()
{
var code = document.getElementById("captcha").value;
var url = "http://www.opencaptcha.com/validate.php?img='.$captcha_name.'.jpgx&ans="+code;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function() {
alert(xmlhttp.readyState + " " + xmlhttp.status);
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("captcha_error").innerHTML=xmlhttp.responseText;
return false;
}
}
xmlhttp.open("GET","captcha_check.php?img=abc.jpg&ans="+code,true);
xmlhttp.send();
}
</script>
What the issue may be and how can I solve it and make the AJAX functioning. Thanks in advance.
The correct order of calls is:
new XMLHttpRequest
xhr.open()
xhr.onreadystatechange = ...
xhr.send()
In some browsers, calling .open clears any event handlers on it. This allows for clean re-use of the same XHR object, which is supposedly more memory-efficient (but that really doesn't matter if you code properly to let the GC do its job)
So, simply put the .open call before the onreadystatechange assignment and you should be good to go.
Even though your code is working perfectly, as mentioned in the comments, since your already included jQuery try:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function captcha_check() {
var code = document.getElementById("captcha").value;
var url = "http://www.opencaptcha.com/validate.php?img='.$captcha_name.'.jpgx&ans="+code;
jQuery.get("captcha_check.php?img=abc.jpg&ans="+code", function(data) {
alert("Load was performed.");
console.log(data);
});
}
</script>
It almost sounds like you are making an AJAX request from a page loaded in the browser directly from the file system, rather than from a Web Server. Since you are issuing a GET request, browser caching might be an issue as well. Try appending a timestamp to the URL each time so the URL is unique:
xmlhttp.open("GET", "captcha_check.php?img=abc.jpg&ans=" + code
+ "&__cachebuster__=" + new Date().getTime());
Secondly, you need to escape the code variable to make it safe for a query string:
xmlhttp.open("GET", "captcha_check.php?img=abc.jpg&ans=" + escape(code)
+ "&__cachebuster__=" + new Date().getTime());
Lastly, please check for any occurences of $_POST in your captcha_check.php file, as this would indicate you should be issuing a POST request, not a GET request.
If:
You are loading a page in the browser directly from the file system, AJAX requests will fail
You enter non query string safe characters for the code, then you end up with an invalid URL, and AJAX requests will fail
The captcha_check.php file requires a POST request and you issue a GET request, the AJAX request will fail.
xmlhttp.open("GET","captcha_check.php?img=abc.jpg&ans="+code,true);
Please check file path, maybe its wrong path.

Ajax refresh does not refresh the Java script

I have a JSP page that refreshes every 5 seconds Using ajax.
The page i am calling having javascript that is not getting refreshed .
Please tell me how to achieve that.
Below is the code i am using to refresh that page .
refresh is the name of the div where i am displaying the data.
<script type="text/javascript">
function AutoRefresh() {
var xmlHttp;
try {
xmlHttp = new XMLHttpRequest(); // Firefox, Opera 8.0+, Safari
} catch (e) {
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); // Internet Explorer
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("No AJAX");
return false;
}
}
}
xmlHttp.onreadystatechange = function () {
//alert("hi");
if (xmlHttp.readyState == 4) {
document.getElementById('TotalRoutes').innerHTML = xmlHttp.responseText;
setTimeout('AutoRefresh()', 10 * 1000); // JavaScript function calls AutoRefresh() every 3 seconds
}
}
xmlHttp.open("GET", "QAGENIE.jsp", true);
xmlHttp.send(null);
}
</script>
Here js files in the QAGENIE.jsp page is not getting refreshed on the ajax call
I think you are not calling AutoRefresh function first time. so nothing will be execute. and if you are calling from outside of your code which you gave here, then please post whole web page code in question.
setTimeout(AutoRefresh,5000); for every 5 seconds
if (xmlhttp.readyState==4 && xmlhttp.status==200)
window.onload = AutoRefresh();
When you call document.getElementById('TotalRoutes').innerHTML=xmlHttp.responseText;, script tags inside the "QAGENIE.jsp" are not executed, that's why:
js files in the QAGENIE.jsp page is not getting refreshed.
Since the question is tagged with jQuery, you could try $.ajax and $.html. Like this:
function AutoRefresh(){
$.ajax({
url:"QAGENIE.jsp"
})
.done(function(response){
$("#TotalRoutes").html(response);
setTimeout(AutoRefresh,10*1000);
});
}
AutoRefresh(); //call this to trigger the first call
$.html automatically parses and executes script tags in the response HTML.
There is 1 more thing to notice is browser cache, if your js files are cacheable (as it usually does by the cache response header from server), the js files may be served from the cached. If you need to always refresh with new js files, ensure your js files are not returned with a cache header, or try to append a random string at the end of the script tags. Like this:
<script src="yourFile.js?[randomstring]"></script>

Categories