Javascript loaded by an Ajax call doesn't execute? - javascript

I´m trying to implement html code with Ajax-get into my temp-page.
This works as it should, only the javascript isn´t executed as I expected. If I load the code independently in the browser, then the javascript executes as expected. If it's implemented with Ajax in my temp-page it doesn´t. Why?
Here is the html and javascript code I'm loading:
<link rel="stylesheet" type="text/css" href="/x/x/x/x/stylesheet.css">
<div id='content_Box'></div>
<script type="text/javascript" src="/x/x/x/x/javascript.js" charset="utf-8"></script>
And here is the ajax code which loads it:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
content_Box.innerHTML = "";
content_Box.innerHTML = this.responseText;
}
};
xhttp.open("GET", Pfad, true);
xhttp.send();
Thank you for your time!

Your problem is not with the ajax call.
The issue is that
content_Box.innerHTML = this.responseText;
doesn't cause any scripts to execute.
See Executing <script> elements inserted with .innerHTML for some code that looks at the text, finds the scripts, and executes them.

It may depend on what your js actually does.
Anyway you can call the functions once you have loaded the ajax response (in xhttp.onreadystatechange) to make sure to run them at least once also on the parts you got from the response.

Related

How to run PHP code in a JavaScript Function?

I am trying to make a function to open a webpage in the same tab as the one you are coming from, (think clicking on a bookmark in a tab). I have the page I want to go to and I know the PHP code to do what I want,
<?php
header("Location: example.php")
?>
I am wondering if there is a way for me to run PHP code in JavaScript so I can do what I want?
(Before anyone asks why I don't just run the code this way, it's because the situation I am in requires me to run the code through a JavaScript function)
You don't need PHP for page redirection. You can simply do this in pure javascript.
function gotoExample() {
window.location.href = './example.php';
}
Mixing PHP and javascript introduces complication to your code. Avoid that if possible.
There are various ways on how you can run a php script inside a js function. One way is via ajax.
//some js logic here
if (foo) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("GET", "http://foo.bar/path/to/a/script.php", true);
xhttp.send();
}
What happens on the above code is that when foo evaluates to true, than a XMLHttpRequest is called and a server side script written in php is executed.
However, in your case, it It is better to just handle a redirect on the client side rather than relying on PHP.
if (foo) {
window.location.href = 'http://foo.bar/path/to/a/script.php';
}
There are various ways on how to issue a redirect via js. The interned is huge. You'll find it with just a couple of searches.

Dom manipulations are not synchronized with javascript code on ajax request?

In my below code, I tried to stimulate how each statement gets executed line by line while processing synchronous ajax requests. I have sent two ajax requests synchronously introducing a delay between two requests. The problem is i'm getting "Request 1" in console but not getting the response text in my dom. After delay ends, and my second request ends, the first responseText is displayed and then second responseText is displayed in my dom.
Why My first ajax response text getting late to update in my dom, even though I got a response from server-side before the delay gets start?
index.html
-----------
<!DOCTYPE html>
<html>
<body>
<!--Calls the function synchronously(async=0/false) -->
<button type="button" onclick="loadDoc('ajax_info.txt')">Synchronous Operations</button>
<p id="result1"></p>
<p id="result2"></p>
</body>
<script type="text/javascript">
function loadDoc(url) {
console.log("Entered ");
ajax(1,url,"result1");
for(i=0;i<1000000000;i++){}
ajax(2,url,"result2");
console.log("Exit");
}
function ajax(requestNo, url, div) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(div).innerHTML = this.responseText;
console.log("Request " + requestNo);
}
};
xhttp.open("get", url, 0);
xhttp.send();
}
</script>
</html>
ajax_info.txt
--------------
This is the content from a txt file.
I think there is something wrong with your response. I used a publicly available fake endpoint to reproduce this, but it works as expected:
https://jsbin.com/kojowaneda/1/edit?html,js,console,output
The only diff between this code and yours, is the parameter of the function call:
<button type="button" onclick="loadDoc('https://jsonplaceholder.typicode.com/todos/1')">Synchronous Operations</button>
Also, you should use setTimeout for a timeout instead of a for loop.

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

Notify after Ajax call

Hope this is an nice easy one
I want to show a notify when an ajax function completes. My ajax is fine I just can't seem to get the notify to work. I have jquery and everything installed and I also have notify.js from http://notifyjs.com/.
Using the google developer tools I just get the error below all the time.
Uncaught TypeError: $.notify is not a function
Here is my ajax function. This works just fine exactly as I need just no notify is displayed :(
function MyAjaxFunction()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("mainpagemenu_myDiv").innerHTML = xmlhttp.responseText;
$.notify("Hello World"); // <- **** this is the thing I want to do
}
}
xmlhttp.open("POST", "/myaspfile.aspx", true);
xmlhttp.send();
}
I have linked in my files
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
and
<script src="/bootstrap/js/notify.js"></script>
Link to the following script
<script src="http://notifyjs.com/dist/notify-combined.min.js"></script>
at the top of the page (before using the Ajax function)

Adobe AIR and multiple XMLHttpRequests is being... weird

I'm making a small Adobe AIR app (my first) using HTML+Javascript. I need to run more than one asynchronous data request, but the second one didn't seem to be firing (note that the requests were not run concurrently originally). I tried stripping the program down to the bare minimum that exhibited problems, and at first only the first request fired, but then things got strange. Code and output follows:
<html>
<head>
<script type="text/javascript" src="AIRAliases.js"></script>
<script type="text/javascript">
function download(page) {
var url = "http://en.wikipedia.org/w/api.php?action=parse&format=xml&page=" + page;
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url,true);
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4) {
air.trace("Done");
}
}
xmlhttp.send(null);
}
function appLoad() {
download("Main Page");
download("Main Page");
}
</script>
</head>
<body onLoad="appLoad()">
</body>
</html>
Expected output:
Done
Done
Actual output:
C:\AIRSDK\apps\HelloWorld>adl HelloWorld-app.xml
Done
C:\AIRSDK\apps\HelloWorld>adl HelloWorld-app.xml
Done
C:\AIRSDK\apps\HelloWorld>adl HelloWorld-app.xml
Done
C:\AIRSDK\apps\HelloWorld>adl HelloWorld-app.xml
Done
Done
Done
Done
Done
Done
Done
Anyone seen anything like this before?
Simple answer, you shouldn't re-use xmlhttprequest objects (even if you don't realise you are because you're a complete noob at Javascript).
This line:
xmlhttp = new XMLHttpRequest();
Should be:
var xmlhttp = new XMLHttpRequest();

Categories