XMLHttpRequest can get data to display on webpage - javascript

I am trying to retrieve data from a web page and then display it on my webpage, nothing fancy atm just display it so it cam be read, however I am not sure how to do this, this is what I have so far(Also sorry if I've not done the formatting properly I'm still new to this):
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<title> Night Out In Glasgow!!</title>
<link rel="stylesheet" type="text/css" href="StyleSheet.css">
<script src="pull.js"></script>
</head>
<body>
<form action = "">
<p><button type = "button" onclick ="getData()">Get The Data</button>
</p>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</body>
This is then my JS which is in a separate file called pull.js, which I have linked to in my HTML, hope this clears up any confusion form original post.
/*jslint node: true, browser: true */
"use strict";
/*jslint node: true, browser: true */
"use strict";
function getData(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","http://ratings.food.gov.uk/OpenDataFiles/FHRS776en- GB.xml");
xmlhttp.onreadystatechange = checkData;
xmlhttp.send(null);
function checkData() {
if(xmlhttp.status == 4){
if(xmlhttp.status == 200){
//We've got a response
alert(xmlhttp.responseXML);
}
}
else{
//Somethings went wrong
alert("Error: " + xmlhttp.status + ": " +xmlhttp.statusXML);
}
}
}

Try it in this order:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","...");
xmlhttp.onreadystatechange = {
if(xmlhttp.status == 4){
if(xmlhttp.status == 200){
...
};
xmlhttp.send();

I'm not sure with your case, but the same origin policy restricts contents retrieved via XMLHttpRequest to be accessed from a website with different origin. Go check this StackExchange answer

Related

How to call a function from html button

I'm trying to call a function from a button in the html body when onclick. This function sends the id to a php for processing some information.
The problem is that when I press the button, it is not calling the function. Can anyone tell me what I'm doing wrong?
Thank you
This is the code,
<html>
<head>
<title>Carrental</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<script>
function delete(id){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var available = this.responseText;
}
};
xhttp.open("GET", "add_delete_session.php?action=delete&id="+id, true);
xhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="delete(9)">Erase</button>
</body>
</html>
delete is an operator. You cannot use it as the name of a variable.
Rename the function.
You need to change the delete to another name function , delete is an operator , you can see the list of operators here : Expressions and operators
function ajaxCall(id){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var available = this.responseText;
}
};
xhttp.open("GET", "add_delete_session.php?action=delete&id="+id, true);
xhttp.send();
}
</script>
</head>
<body>
<button type="button" onclick="ajaxCall(9)">Erase</button>
</body>
You cant call the function delete. Just Rename it :)
The problem is delete is operator in JavaScript
The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.
So your code try to delete the object or element mentioned after it and is not calling method you wrote.
As per example in #Pluto https://stackoverflow.com/a/62086635/124891
You have to rename the method and call it.

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');

Not getting a response on MDN AJAX example

I previously attempted to interact with PHP using AJAX (1st time using Javascript to any significant degree) and had no success, so I tried to start with the basics using a Mozilla Developer Network example as a test:
Example - https://developer.mozilla.org/en-US/docs/AJAX/Getting_Started
That isn't working either even though I copy-pasted it straight from the site with only one change (setting the url to my test page, running on XAMPP). When I click the button to run the MDN script, the resulting output is the alert "There was a problem with the request".
I'm using Firebug to check the result, and it shows a "200 OK" code for Status. If I understand the script correctly, shouldn't that not lead to an error message?
Here is the code from the example (along with the code from the Foundation framework I was using, in case that's somehow the issue):
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Foundation | Welcome</title>
<link rel="stylesheet" href="css/foundation.css" />
<script src="js/vendor/modernizr.js"></script>
</head>
<body>
<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
Make a request
</span>
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation.min.js"></script>
<script type="text/javascript">
(function() {
var httpRequest;
document.getElementById("ajaxButton").onclick = function() { makeRequest('http://localhost:8000/pages/test.html'); };
function makeRequest(url) {
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
return false;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', url);
httpRequest.send();
}
function alertContents() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
</body>
And here is the code for the test HTML page that I made:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
Test
</body>
</html>
Where am I going wrong?
EDIT - Adding the original PHP script being referenced. I originally tried to use an altered version of the MDN script on this but likewise couldn't get it to work:
<?php
require ('includes/config.inc.php');
require (MYSQL);
$u = NULL;
$P = NULL;
$u = mysqli_real_escape_string ($dbc, $_GET['username']);
$p = mysqli_real_escape_string ($dbc, $_GET['password']);
$q = "SELECT user_id FROM users WHERE (username='$u' AND password=SHA1('$p')) AND active IS NULL";
$r = mysqli_query ($dbc, $q) or trigger_error("Query: $q\n<br />MySQL Error: " . mysqli_error($dbc));
if (#mysqli_num_rows($r) == 1) { // A match was made.
$a = 'True';
print json_encode($a);
} else { // No match was made.
$a = 'False';
print json_encode($a);
}
?>
2ND EDIT - Thanks for the suggestion about the console log, that did it. All I needed to do was enable CORS and now it works fine.

Retrieving data from server database in IBM worklight

I am developing an app in IBM worklight. By Ajax I have to Connect to website and retrieve data from it but it gives thisd error:
Uncaught TypeError: Cannot call method 'getElementsByTagName' of null at file:///data/data/com.Test/files/www/default/Test.html:80
How can I fix it? My code is this
<!DOCTYPE HTML>
<html>
<head>
<script>window.$ = window.jQuery = WLJQ;</script>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport"
content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0">
<link rel="stylesheet" href="css/Test.css">
<script>
function loadXMLDoc()
{
var xmlhttp;
var txt,x,i;
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)
{
xmlDoc=xmlhttp.responseXML;
txt="";
// x=xmlDoc.getElementsByTagName("Id");
var table = xmlDoc.getElementsByTagName("table");
var tds = table.getElementsByTagName("td");
alert(tds);
for (var i = 0; i < tds.length; i++) {
alert(tds[i].innerHTML);
}
/* for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br>";
} */
document.getElementById("myDiv").innerHTML=txt;
}
}
xmlhttp.open("GET","http://www.marketing.com/msb_en.html",true);
xmlhttp.send();
}
</script>
</head>
<body id="content" style="display: none;">
<h2>MCollection:</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">collection</button>
<!--<input type="button" value="button name" onclick="window.open('https://www.google.com.pk')" /> -->
<!--application UI goes here-->
<script src="js/initOptions.js"></script>
<script src="js/Test.js"></script>
<script src="js/messages.js"></script>
</body>
</html>
and my line 80 this is
var table = xmlDoc.getElementsByTagName("table");
It looks like xmlDoc is null when you try to use. Make sure your server is returning what you are expecting and that you are accessing the data in the response properly.
A couple of suggestions not directly related to your question. jQuery is already loaded in your app. You may want to consider using its AJAX functionality rather than using XMLHttpRequest directly.
Also if you're using Worklight, you could consider using an HTTPAdapter instead of AJAX all together. If you're not leveraging the functionality that Worklight provides beyond just a browser to write your code in then maybe you should look at other options for your platform.

Phonegap and restful web service

I want to retrieve data from restful webservice that returns xml. I'm using phonegap.
I have tried this code, it gives me result on InternetExplorer but not on my phone gap app!
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>PhoneGap</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script type="text/javascript" charset="utf-8" src="js/Config/phonegap-0.9.3.js"></script>
<link rel="stylesheet" href="css/jquery/jquery.mobile-1.0a1.min.css" />
<link rel="stylesheet" href="css/Style.css" />
<script src="js/Config/jquery-1.4.3.min.js"></script>
<script src="js/Config/jquery.mobile-1.0a1.min.js"></script>
<script type="text/javascript">
function getDescription() {
var url = 'http://localhost/prestashop/api/customers/2';
req = new XMLHttpRequest();
req.onreadystatechange = processRequest;
req.open("GET", url, true);
req.send(null);
}
function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
alert ( "Not able to retrieve description+"+req.responseText );
parseMessages();
} else {
alert ( "Not able to retrieve description+"+req.responseText+"vide" );
}
}
}
function parseMessages() {
response = req.responseXML.documentElement;
itemDescription = response.getElementsByTagName('lastname')[0].firstChild.data;
alert ( itemDescription );
}
</script>
</head>
<body>
<button onClick="getDescription()">Ajax call</button>
</body>
</html>
it returns req.status = 0!!
Try with
var url = 'http://localhost/prestashop/api/customers/2?PHP_AUTH_USER="password"&ws_key="login"';
Try changing this line:
if (req.status == 200) {
into:
if (req.status == 200 || req.status == 0) {
on mobile devices running from the file:// protocol you often get a status of 0 when there is a successful request.
What result do you get in Chrome? Chrome and the Android Browser (along with Safari and the BlackBerry Browser) are all based on WebKit.
Have you added access origin to your phonegap.xml file?
Is there any particular reason you're not using jQueryMobile for your AJAX? Are you able to get a successful response using jQM?

Categories

Resources