Ajax implementation using javascript - javascript

I want to implement a simple AJAX script which tries to display data stored in a xml file. I tried this following code but on press of the button the page seems static and nothing responds back. The script doesn't display the xml contents.
<!DOCTYPE html>
<html>
<head>
<title>XML</title>
<script>
function myfun() {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else {
req = new ActiveXObject("Microsoft.req");
}
req.onreadystatechange = function() {
if (req.readyState === 4 && req.status === 200) {
document.getElementById("myid").innerHTML = req.responseText;
}
}
//req.overrideMimeType('text/xml');
req.open("GET", "myxml.xml", true);
req.send();
}
</script>
</head>
<body>
<div id="myid">This will change</div>
<input type="button" value="submit" onclick="myfun()" />
</body>
</html>
XML:
<?xml version="1.0" encoding="UTF-8" ?>
<student>
<id>100</id>
<name>tamizh</name>
</student>

Related

Fetch file in Python. flask code coming from javascript

This is my javascript function which is routing a csv file to /uploader.
function getData() {
var csv=document.getElementById('myFile').files[0];
var formData=new FormData();
formData.append("uploadCsv",csv);
var request = new XMLHttpRequest();
//Open first, before setting the request headers.
request.open("POST", "/uploader", true);
//here you can set the request header to set the content type, this can be avoided.
//The browser sets the setRequestHeader and other headers by default based on the formData that is being passed in the request.
request.setRequestHeader("Content-type", "multipart/form-data"); //----(*)
request.onreadystatechange = function (){
if(request.readyState === XMLHttpRequest.DONE && request.status === 200) {
console.log(request.response);
}
}
request.send(formData);
}
My python function does get invoked to the app routing part seems to correct. However the request.files length is 0.
This is the python code -
#app.route("/uploader", methods=["POST"])
def post_javascript_data():
f = request.files["uploadCsv"]
print(f)
return "OK"
In the picture below you can see the request.files length remains 0. What am I doing wrong here?
The solution is to not manually set the header for the content type. This is set automatically.
The following is an example with XMLHttpRequest and alternatively with fetch.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<!-- Using XMLHttpRequest -->
<form name="upload-form-1">
<input type="file" name="upload-csv" accept="text/csv" />
<input type="submit" />
</form>
<script type="text/javascript">
(function() {
let form = document.querySelector("form[name='upload-form-1']");
form.addEventListener(
"submit",
(event) => {
event.preventDefault();
let xhr = new XMLHttpRequest();
xhr.open("POST", "/uploader");
xhr.onload = function() {
if(this.status === 200) {
console.log(this.response);
} else {
console.error(`Error ${this.status} occurred.`)
}
}
xhr.send(new FormData(event.target));
},
false);
})();
</script>
<!-- Using Fetch -->
<form name="upload-form-2">
<input type="file" name="upload-csv" accept="text/csv" />
<input type="submit" />
</form>
<script type="text/javascript">
(function() {
let form = document.querySelector("form[name='upload-form-2']");
form.addEventListener(
"submit",
(event) => {
event.preventDefault();
fetch("/uploader", {
method: "POST",
body: new FormData(event.target)
}).then(resp => {
console.log(resp);
}).catch(err => {
console.error(err);
});
},
false);
})();
</script>
</body>
</html>
from flask import abort, make_response, request
#app.route('/uploader', methods=['POST'])
def uploader():
if 'upload-csv' in request.files:
f = request.files['upload-csv']
# Use the object of the type werkzeug.FileStorage here.
return make_response('')
abort(400)
Have fun implementing your project.

AJAX can't load JavaScript in another page

Why can't AJAX load another HTML page with JavaScript? It loads HTML,CSS,PHP etc... but not JavaScript. Is AJAX supposed to work like that? If so how can I load another HTML page that contains JS with AJAX?
A simple example what I mean
a.php
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "b.php", true);
xhttp.send();
}
</script>
</body>
</html>
b.php
<!DOCTYPE html>
<html>
<body>
<h1>b</h1>
<script>
document.write("Hello World!");
</script>
</body>
</html>
Screenshot of response:
Because the javascript code you'll get via ajax is a simple string and not executed. You have to eval() the code in the script tag like:
Example:
<script id="helloworld">
document.write("Hello World!");
</script>
JS:
var jsCode = document.getElementById('helloworld').textContent;
eval(jsCode);
Edit by request:
if (this.readyState == 4 && this.status == 200) {
var demoElement = document.getElementById("demo");
demoElement.innerHTML = this.responseText;
var scriptTags = demoElement.getElementsByTagName('script');
for(i = 0; i < scriptTags.length; i++) {
eval(scriptTag[i].textContent);
}
}

Update the changed value in the physical XML File

I am trying to update certain attributes of my xml file using javascript.
I am able to set new value by calling setAttribute() method, but unable to reflect it in the physical file.
I am very much new to html javascript. Please help.
Below I am posting my HTML as well as xml file code.
Html code:
<!DOCTYPE html>
<html>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<body>
<p id="demo"></p>
<script>
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "http://10.21.64.222/LoadBreakSwitch/vbn.xml", true);
xhttp.send();
function myFunction(xml) {
var x, i, txt, xmlDoc;
xmlDoc = xml.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("Ping");
x[0].setAttribute("CommValue","1122222");
txt +=x[0].getAttribute("CommValue")+"<br>";
document.getElementById("demo").innerHTML = txt;
}
</script>
</body>
</html>
xml file code:
<?xml version="1.0" encoding="utf-8"?>
<LBSCommands>
<Ping Commkey="A3070000AA00A4" CommValue="A309008001043101A4"/>
<Frequency Commkey="A3070300AD00A4" CommValue="A309038001013101A4"/>
<SwitchStatus Commkey="A3071D01C800A4" CommValue="A3091D8101014C01A4"/>
<SwitchLockStatus Commkey="A3071E01C900A4" CommValue="A3091E8101004C01A4"/>
<SetFrequency01 Commkey="A308130001BF00A4" CommValue="A309038001013101A4"/>
</LBSCommands>

Ajax Post versus GET

I am trying to implement an AJAX Example which perfectly works with the GET request, but I am not able to transmit via POST. What am I doing wrong ? The POST object received by PHP is always empty. Thanks for any advice!
HTML & JavaScript:
<html>
<head>
<title> Create a new user</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
function checkUser(){
xhttp = new XMLHttpRequest();
xhttp.open("POST","usercheck.php",true);
xhttp.onreadystatechange = function () {
if (xhttp.readyState == 4 && xhttp.status == 200) {
var data = xhttp.responseText;
alert("Benutzer" + data);
}
}
xhttp.send("username=" + encodeURIComponent(document.getElementById("username").value));
}
</script>
</head>
<body>
<p>User:</p><br>
<input type="text" id="username" name="username">
<button onclick="checkUser();"> Check </button>
</body>
</html>
PHP Code:
<?php
$usernames = array("admin", "gast", "paul");
$validate_pattern = "/^[a-z0-9]{4,20}$/";
if (!isset($_POST["username"])) {
die("{valid:false,message:false}");
}
if (in_array($_POST["username"], $usernames)) {
die("{valid:false,message:'Username is used!'}");
}
if (!preg_match($validate_pattern, $_POST["username"])) {
die("{valid:false,message:'Username wrong.'}");
}
echo "{valid:true,message:false}";
?>
I found the bug in the code. I missed to set the request header, which was not part of the tutorial unfortunately:
xhttp.setRequestHeader('Content-Type','x-www-form-urlencoded');

How do I save HTML form data to an XML file using JavaScript?

I am making a blog in which users can leave comments on my posts. I used JavaScript to read the data from the XML file and display it in a div element. However, I can't get the page to save new comments to the XML file, and then rewrite the div contents based on the changed XML file. I know how to edit the XML file, but how do I save it? (Sorry, the code's a little messy)
Source Code:
index.html:
<!DOCTYPE html>
<html lang = "en-US">
<head>
<title>Blog</title>
<script src = "loadXML.js">
</script>
<script>
function addComment1(form)
{
var xmlDoc = loadXMLDoc("one.xml");
var use = form.user1.value;
var com = form.comment1.value;
}
</script>
<meta charset = "utf-8"/>
</head>
<body>
<h1>Posts</h1>
<br/>
<!-- A Post -->
<h2>Comments:</h2>
<div>
<p>
<script>
var xmlDoc = loadXMLDoc("one.xml");
var cap = xmlDoc.getElementsByTagName("content");
for (i = 0; i < cap.length; i ++)
{
document.writeln(xmlDoc.getElementsByTagName("user")[i].firstChild.nodeValue + ":<br/>");
document.writeln(xmlDoc.getElementsByTagName("content")[i].firstChild.nodeValue + "<br/><hr/>");
}
</script>
</p>
<form name = "form1">
<input type = "text" name = "user1"/>
<input type = "text" name = "comment1" />
<input type = "submit" value = "Submit" onclick = "addComment1(this.form)"/>
</form>
</div>
</body>
</html>
one.xml:
<?xml version="1.0" encoding="utf-8"?>
<comment>
<user>Gabe Rust</user>
<content>Hello World!</content>
</comment>
loadXML.js:
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;
}
function loadXMLString(txt)
{
if (window.DOMParser)
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(txt,"text/xml");
}
else // code for IE
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.loadXML(txt);
}
return xmlDoc;
}

Categories

Resources