Retrieving data from server database in IBM worklight - javascript

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.

Related

XMLHttpRequest can get data to display on webpage

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

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.

get request works in browser, not in PhoneGap Build

I've looked at other examples on so and it looks like I'm doing everything right but obviously I am missing something. When run on my desktop it runs great. Once bundled into an app via PhoneGap Build, it no longer works :( wondering if anyone can spot why. All its really doing is picking out unique items from an xml response and listing them. Thanks
Mike
<!DOCTYPE HTML>
<html>
<head>
<title>TestApp</title>
<script type = "text/javascript" charset = "utf-8" src = "cordova-2.3.0.js"></script>
<!-- Jquery stuff -->
<meta name = "viewport" content = "width = device-width, initial-scale = 1">
<link rel="stylesheet" href="jquery/jquery.mobile-1.4.0.min.css" />
<script src="jquery/jquery-1.10.1.min.js"></script>
<script src="jquery/jquery.mobile-1.4.0.min.js"></script>
<script type = "text/javascript">
function onBodyLoad(){
//pre-loads data
loadXMLDoc('http://login.etherios.com/ws/DiaChannelDataFull');
}
function loadXMLDoc(url) {
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) {
var lastXBee=0;
var adChannel=0;
txt="<table border='0' width='%100'><tr><th>title</th></tr>";
x=xmlhttp.responseXML.documentElement.getElementsByTagName("DiaChannelDataFull");
for (i=0;i<x.length;i++) {
xx=x[i].getElementsByTagName("ddInstanceName"); {
if (lastXBee!=xx[0].firstChild.nodeValue) { // if not a reading from same , start new row
try {
txt=txt + "<tr>";
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er) {
txt=txt + "<tr>";
txt=txt + "<td> </td>";
}
var lastXBee=xx[0].firstChild.nodeValue;
var sameRow="No";
}
else {}
}
}
txt=txt + "</table><br />";
document.getElementById('currentStatus').innerHTML=txt;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body onload = "onBodyLoad()">
<h4>Current Status:</h4>
<!-- **** Call to getRequestList.js file *** -->
<button onclick="loadXMLDoc('http://login.etherios.com/ws/DiaChannelDataFull')">Refresh Sensor Data</button>
<div id="currentStatus"></div>
<br />
</body>
</html>
I gave up on this and decided to go in another direction.

ajax can't get response text from php

I've created an html and a php file. The php links to a database (either my localhost or the university's database online), and the html uses AJAX to partially update a tag's content:
<html>
<head>
<title>iNote</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<script type="text/javascript">
function pullMore(){
var xmlhttp;
if (window.XMLHttpRequest){ // code for IE7+, Firefox, Chrome,etc.
xmlhttp = new XMLHttpRequest();
}else{ // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 /*&& xmlhttp.status ==200*/){
document.getElementById("more").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET","1.php",true);
document.getElementById("more").innerHTML = "<p>notenter</p>";
xmlhttp.send();
}
</script>
<div id="Checklist"></div>
<div id="Note"></div>
<div id="more" onclick="pullMore()">
<p>Click to Replace Content Here</p>
</div>
</body>
</html>
However, no matter how I modified the php's content, (even when I changed it to a simple echo "<p>please show this!!</p>";), the xmlhttp.status ==200 cannot be satisfied, and "notenter" is displayed on screen.
If I quote out the condition and leaving only xmlhttp.readyState == 4, the message in <div> would be replaced, but only by blank space...and if the php code is the full one for accessing database, EVERYTHING after echo, including all the codes and brackets, would be outputted...
Can anyone help me? I've been debugging for hours and still can't figure out where's the problem...Thank you so much!

How to read json file located in project folder in iPhone PhoneGap using Javascript

I have to read a JSON file from folder that is located in a project.
I am using the following code:
var obj = "www/places.json";
How can I read a JSON file located in project folder www in iPhone PhoneGap using Javascript?
You would read it just like it is on your server.
Solution 1 - jQuery
If jQuery usage is not a problem then use it like this:
//Load categories object JSON
jQuery.getJSON("categories.json", function(data){
// data is yours parsed object
});
Example :
HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"/>
<script src="http://www.fajrunt.org/js/jquery-1.9.1.min.js"></script>
<title>Read JSON Demo</title>
<script>
jQuery.getJSON("categories.json", function(data){
alert(data.balance);
});
</script>
</head>
<body>
Read JSON Demo
</body>
</html>
JSON file :
{"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"}
Solution 2 - Pure javascript
If you want to use only vanilla javascript then this is a solution for you
var xmlhttp;
var jsonObject;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
jsonObject = JSON.parse(xmlhttp.responseText);
alert(jsonObject.balance);
}
}
xmlhttp.open("GET","categories.json",true);
xmlhttp.send();
Example :
HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no"/>
<title>Read JSON Demo</title>
<script>
var xmlhttp;
var jsonObject;
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
// code for IE6, IE5
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
jsonObject = JSON.parse(xmlhttp.responseText);
alert(jsonObject.balance);
}
}
xmlhttp.open("GET","categories.json",true);
xmlhttp.send();
</script>
</head>
<body>
Read JSON Demo
</body>
</html>
JSON file :
{"balance":1000.21,"num":100,"nickname":null,"is_vip":true,"name":"foo"}
I had same problem and got through with following snippet:
dojo.ready(function(){
var xhrArgs = {
url: "file:///Users/Desktop/configJSON.txt",
handleAs: "json",
load: function(data){
targetNode.innerHTML = data;
// Your data from JSON
alert("Name : "+data.fields[0].name+" Type : "+data.fields[0].type+" Alias : "+data.fields[0].alias
+" Editable : "+data.fields[0].editable);
},
error: function(error){
// targetNode.innerHTML = "An unexpected error occurred: " + error;
alert("An unexpected error occurred: " + error);
}
}
// Call the asynchronous xhrGet
var deferred = dojo.xhrGet(xhrArgs);
});
</script>
</head>
<body>
<div id="licenseContainer"></div>
<body>

Categories

Resources