Do script from another file - javascript

im today stared learning some ajax technology and im done that when im pressing the button im getting text from another file with functions but they dont working.
My main file
<html>
<head>
<script>
function showHint(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "request/testa.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<button id="inp" style="background-color: #0000FF; color: #ffffff" onclick="showHint(this.value)">
Just do it!
</button>
<p><span id="txtHint"></span></p>
</html>
and in file which send me text (request/testa.php) is
test 2
<script>
document.getElementById("inp").value="You did it!";
document.getElementById("inp").style.backgroundColor="ffffff";
</script>
and tekst working fine, i got text "test 2" and script but that not works.

Writing javascript code into your page using innerHTML will not execute the script.
The easiest way around this is to use jQuery's load, which will execute the scripts for you.

You have to change something in testa.php. Put everything in a function or just remove the script tag.
function MyScript(){
document.getElementById("inp").value="You did it!";
document.getElementById("inp").style.backgroundColor="ffffff";
}
or
document.getElementById("inp").value="You did it!";
document.getElementById("inp").style.backgroundColor="ffffff";
After that you can replace the innerHTML in your showHint function for the eval function.
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
for
eval(xmlhttp.responseText);
but have in mind that the eval function opens the door for bugs or hacks.

Related

PHP file path not found when I have JavaScript run a PHP script with XMLHTTPREQUEST (404 error); what to do?

When I hit the button on the UI to have the JS communicate with PHP to pull up a "Hello world" page, I am getting a "{"timestamp":"2021-06-10T20:14:59.671+00:00","status":404,"error":"Not Found","message":"","path":"/hello.php"}" in the browser.
In the Eclipse console, it says: 2021-06-10 16:52:27.193 WARN 16688 --- [nio-8080-exec-1] o.s.w.s.r.ResourceHttpRequestHandler : Path with "WEB-INF" or "META-INF": projectname/src/main/webapp/WEB-INF/jsp/hello.php]
What do I do? Here's some code I have, and I have tried many file path formats where I refer to the PHP file. But it's all the same error!
Here's some of my code:
JSP page (just the Javascript part of it):
<button onclick=refreshData()>Say Hello</button>
<div id="content" />
<script type="text/javascript">
function refreshData(){
var display = document.getElementById("content");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "hello.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
display.innerHTML = this.responseText;
} else {
display.innerHTML = "Loading...";
};
}
}
</script>
PHP
<?php
print "<p>Hello World</p>";
?>
This is in Spring MVC using Eclipse. I have the JavaScript on a JSP file page. What do I do to fix this? Thanks!
I always use:
$('#content').load("hello.php");
Just be sure your .php file is in the same folder

Using button from another file

Good day! I'm new to web development and still studying.
I'm trying to create a simple counter using javascript.
index.html
<script src="test.js"></script>
<h1>Count </h1>
<p id="count">0</p>
<button onclick ="mycounter()">Add Count</button>
test.js
var counter = 0;
function mycounter(){
counter = counter + 1;
document.getElementById('count').innerHTML = counter;}
Now this code works perfectly fine. Is it possible to transfer that button to another html file and everytime that button is clicked from the other file, the count display on my index is updated?
Any help would be much appreciated. Thank you.
If you want to transfer part of your html in to another file and use it in a separate file, that is called templating. The usual pattern is to load the contents of the "other" file via XHR and add it to the DOM.
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("buttonholder").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}

Retrieve a variable from server using alert

this is my first attempt to retrieve a value using an alert box. Here what I am doing is having a file at the server and I want to retrieve that file value in an alert box.
Before that, I am able to get that value through a link. That working code is here-
<!DOCTYPE html>
<html>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "localhost:8080/TemperatureReading/", true);
xhttp.send();
</script>
<body>
test
</body>
Request data
</html>
Now, what am I trying to do is have that value in an alert box every time I hit that button.
That code is here---
First I added a return statement in the function so that a variable is returned inside it.
xhttp.send();
return variable;
Than, I added another function for alert box---
<script>
function myFunction() {
alert(variable);
});
</script>
and in the body, I added
<button onclick="myFunction()">Try</button>
But till now I am not succeeded in that.
I am not understanding what am doing wrong here.
Can anyone help me with this thing. Thank you in advance.
EDIT : I have edited the code. Also, I have to only create a HTML file. I am not generating the number. So, what I have to do is just give an HTML and with the help of retrieve value
Do this when you get the response:
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
if(window.localStorage){
window.localStorage.setItem['resp'] = JSON.stringify(xhttp.responseText);//set it here
}
}
now in the function where variable is required:
function myFunction() {
if(window.localStorage){
var resp = JSON.parse(window.localStorage.getItem['resp']); // get it here
alert(resp); // alert it here.
}
}

Call Javascript function after AJAX load

I know that these kind of questions pop up a lot on here. I usually am not the type to ask questions but this time I could not find a solution through searching.
I have boiled down my problem to a very small and simple environment:
I have 3 files:
Index.php:
<html>
<html xmlns="http://www.w3.org/1999/xhtml">
<script src="javascript.js"></script>
<head>
<title>Test</title>
</head>
<body>
<div>
<input type="button" value="Show" onclick="show('content','content.php');">
<script type="javascript/text">
show('content','content.php');
</script>
<br>
<div id="content"></div>
</div>
content.php
<div>CONTENT</div>
<input type="checkbox" id="checkbox" onclick="checkbox();">
<input type="text" id="textfield">
And javascript.js
function show(divcontainer,file){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(divcontainer).innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", file);
xmlhttp.send();
}
function checkbox(){
if(document.getElementById('checkbox').checked){
document.getElementById('textfield').value = "checked";
}
else{
document.getElementById('textfield').value = "unchecked";
}
}
When I press the button in index.php it loads the file content.php into the div container "content" via an ajax call. The file content.php has a checkbox and a textfield. When the checkbox is checked and unchecked it executes a javascript function that puts checked/unchecked in the textfield.
Simple enough and everything works fine.
Now what I want to do is to call the function checkbox() the moment that content.php is loaded. In this example it would mean that the textbox would already have the value "unchecked" and not only after the checkbox has been checked and unchecked again.
Putting the javascript code into the file content.php didn't do anything.
Somehow I feel that there must be a simple solution to this. I'm still pretty new to javascript though so I don't know the in and outs yet.
Any help would be greatly appreciated
Many thanks!
Try this
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById(divcontainer).innerHTML=xmlhttp.responseText;
checkbox();
}
if you´re new to JS you should definitely have a look at jQuery. Makes AJAX alot simpler.
$.ajax({
url: youURL,
success: function (){
//or whatever function you want to be called after success :)
}
});

XMLHttpRequest connection check

I am trying to write a streamlined version of a XMLHttpRequest demo script shown here:
http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_first
I'm only going to use this on iPad, so I don't have to check for older versions of IE, and so on. On button click, I want to check if the connection exists. Here's my entire html page, including JavaScript snippet:
<html>
<head>
<script>
var myURL = "http://www.google.com";
function testConnection(url) {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("Connected!");
} else {
alert("Not connected!");
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="testConnection(myURL)">Test Connection</button>
</body>
</html>
For some weird reason, even though I'm online, when I click the button, I get repeated "Not connected" alerts, and only after a while I get the "Connected" alert, followed by no alerts.
Looks like I messed up, but I can't see where. What should I change to make it work?
If you can use xhr2, you can learn stuff from this tutorial and rewrite your code to something like this:
function testConnection(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() { alert("Connected!"); }
xmlhttp.onerror = function() { alert("Not Connected"); }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
If you send request to another domain, you may get error even if it exists, if the target server has Same-Domain-Policy restriction (default). If the target server is on another domain, it must send header
Access-Control-Allow-Origin: *

Categories

Resources