get request works in browser, not in PhoneGap Build - javascript

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.

Related

How to load a script in a php file called from a Ajax Request?

I have this JavaScript:
<script>
if (str == "") {
document.getElementById("txtHint1").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "/npsmart/umts/action_plano/?q=" + query1, true);
xmlhttp.send();
}
</script>
And this JavaScript call a page called getuser.php.
This is the code of getuser.php:
<!DOCTYPE html>
<html>
<body>
<p id="dumb"></p>
<script>
document.getElementById("dumb").innerHTML = "WORK";
</script>
</body>
</html>
What I would like is only to change the paragraph content, called dumb, to WORK. But when I call the page and it loads, my paragraph content keep null.
It's like my Ajax Call Request don't execute the Script Tag.
EDIT:
I have already solved my problem with this simple but genious solution:
function showUser() {
if(query_num == 2){
if (str == "") {
document.getElementById("txtHint1").innerHTML = "";
return;
} else {
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 (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
eval(document.getElementById("runscript").innerHTML);
}
};
xmlhttp.open("GET","/npsmart/umts/action_plano/?q="+55555,true);
xmlhttp.send();
}
And in my getuser.php file:
<script type="text/javascript" id="runscript">
document.getElementById("dumb").innerHTML = "WORK";
</script>
I just putted the : eval(document.getElementById("runscript").innerHTML); in my function and then in the php file I called this script using this:
<script type="text/javascript" id="runscript">
So thanks everybody =)
Hope this post can help other people.
JS is not executed automatically from a script embedded in the response.
Since getuser.php is a PHP script there's no need to use JS and have the browser set the paragraph content. Use PHP itself:
<!DOCTYPE html>
<html>
<body>
<p id="dumb"><?php echo 'WORK'; /* or anything else */ ?></p>
</body>
</html>
Otherwise you'll have to use JS eval on the returned AJAX response to have the browser run the JS returned from your script. But I recommend against this.

Pass PHP variable to Javascript function whitin an AJAX request possible?

I try to pass a variable from Javascript (when choosing some option in a form) to a PHP file which calls a SQL query.
The SQL query (a string) should be handed over to a Javascript function and the function should be executed. Everything in one click. Is that somehow possible?
I tried that with a AJAX request but when I use this for my last step:
var javascriptstring;
$.getJSON('getstring.php', function(data) {
javascriptstring = data.value;
});
I get the exception: Uncaught TypeError: Cannot set property 'innerHTML' of null
And it prints out "undefined"
.HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
function showString(time) {
if (time=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getstring.php?q="+time,true);
xmlhttp.send();
var javascriptstring;
$.getJSON('getstring.php', function(data) {
javascriptstring = data.value;
});
document.write(javascriptstring);
}
</script>
</head>
<body>
<form>
<select name="somestring" onchange="showString(this.value)">
<option value="">No string selected</option>
<option value="1">String 1</option>
</select>
</form>
<br>
<div id="txtHint"><b>String will be listed here...</b></div>
</body>
</html>
PHP
<?php
$q = intval($_GET['q']);
$con = pg_connect("host=localhost port=5432 dbname=Twitter user=postgres password=****");
if (!$con) {
die('Could not connect: ' . pg_errormessage($con));
}
$sql="SELECT * FROM tswholeworld WHERE createdat > (NOW() - INTERVAL '".$q."hour');";
$result = pg_query($con,$sql);
$string = "";
while($row = pg_fetch_assoc($result)){
$lat = $row['latitude'];
$lon = $row['longitude'];
$string .= "new google.maps.LatLng({$lat}, {$lon}), ";
}
echo '{"value": "'.$string.'"}';
pg_close($con);
?>
I guess this much amount of AJAX should suffice. Actually document.write replaces the whole DOM with the current. I have removed that and modified your function. Also I have removed the native Ajax code since you already have jQuery so no point in adding that big code. This small function will get the JSON data and print the value that the server is sending
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
function showString(time) {
if (time=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
$.getJSON('getstring.php?q='+time, function(data) {
document.getElementById("txtHint").innerHTML = data.value;
});
}
</script>
Edit: Please close the external script tags
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
//your script
</script>
Keep the Javascript function definition in head or before the select tag. like below -
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript'>
function showString(time) {
if (time=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
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) {
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getstring.php?q="+time,true);
xmlhttp.send();
var javascriptstring;
$.getJSON('getstring.php', function(data) {
javascriptstring = data.value;
});
document.write(javascriptstring);
}
</script>
</head>
<body>
<form>
<select name="somestring" onchange="showString(this.value)">
<option value="">No string selected</option>
<option value="1">String 1</option>
</select>
</form>
</body>
</html>
You forget to close script tag
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>// close include external javascript tag
Then you call your function inside script tag
<script>
function showString(time) {
-----Your code----
</script>

Getting user input for ajax post request?

I am going through the Ajax tutorial at:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
They have this example for submitting request to a server:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","demo_post2.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
</body>
</html>
The problem I have with the above example is that the values for fname and lname are hardcoded. How can allow a user to enter different values for fname and lname via a <form> tag and still be able to use ajax javascript code?
created jsfiddle example for the same:-
http://jsfiddle.net/c2S5d/24/
added two inputs for fname and lname and fetched there values and set into the params.(As of now commented the code for ajax send) try above given link and enter some values into the text boxed and see the alert)
code:-
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
alert("calle")
var xmlhttp;
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) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
var fname = document.getElementById('fname').value;
var lname = document.getElementById('lname').value
//xmlhttp.open("POST","demo_post2.asp",true);
//xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var param = "fname=" + fname + "&lname=" + lname;
alert(param)
//xmlhttp.send(param);
}
</script>
</head>
<body>
<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>
<input type='text' id='fname' />
<input type='text' id='lname' />
</body>
</html>

XMLHttpRequest cannot load http://localhost:8081/sample.xml. Origin null is not allowed by Access-Control-Allow-Origin.

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
var xmlhttp;
var txt,x,xx,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)
{
txt="<table border='1'><tr><th>Author</th><th>Title</th></tr>";
x=xmlhttp.responseXML.documentElement.getElementsByTagName("book");
for (i=0;i<x.length;i++)
{
txt=txt + "<tr>";
xx=x[i].getElementsByTagName("author");
{
try
{
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er)
{
txt=txt + "<td> </td>";
}
}
xx=x[i].getElementsByTagName("title");
{
try
{
txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
}
catch (er)
{
txt=txt + "<td> </td>";
}
}
txt=txt + "</tr>";
}
txt=txt + "</table>";
document.getElementById('txtCDInfo').innerHTML=txt;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="txtCDInfo">
<button onclick="loadXMLDoc('http://localhost:8081/sample.xml')">GetDetails</button>
</div>
</body>
</html>
I have written above lines of code for showing xml file data.And it was deployed in iis server.Whenever i wanted to access xml file,It is showing above error.Where am i doing wrong mistake.What i have to write in url position for getting xml file.If i write only file name like sample.xml.It showing error like Access denied.
this is because of the Same origin policy. you cannot use ajax to call external sites. if you really want to use, you have to use JSONP. Or you can use serverside proxy for this. means, call external site in the server side and do ajax call to the that webservice.
For more details see my answer on following question,
$.ajax call working fine in IE8 and Doesn't work in firefox and chrome browsers

Error in safari/IE Error x[i].getElementsByTagName("image")[1] is undefined

I am trying to display an RSS feed in HTML. It works on iPad, iPhone and chrome but not in internet explorer or safari. I get an error message saying
x[i].getElementsByTagName("image")[1] is undefined
Does anyone know how I can get this to work? It is using an Apple RSS feed to display apps from the App Store. The error is occurring at the first document.write. I am trying to display the returned results in a table also.
<html>
<head>
<title>RSS Apps</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<script type="text/javascript">
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://itunes.apple.com/au/rss/topfreeapplications/limit=10/xml?partnerId=1002&partnerUrl=http%3A%2F%2Fwww.s2d6.com%2Fx%2F%3Fx%3Dc%26z%3Ds%26v%3D3868801%26t%3D",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("feed");
for (i=0;i<x.length;i++)
{
document.write("<img src=" + x[i].getElementsByTagName("im:image")[1].childNodes[0].nodeValue +">");
document.write("</td><td>");
document.write("<img src=" + x[i].getElementsByTagName("im:image")[4].childNodes[0].nodeValue +">");
document.write("</td><td>");
document.write("<img src=" + x[i].getElementsByTagName("im:image")[7].childNodes[0].nodeValue +">");
document.write("</td></tr><tr><td>");
document.write("<font size=\"1\">" + x[i].getElementsByTagName("name")[1].childNodes[0].nodeValue+"");
document.write("</td><td>");
document.write("<font size=\"1\">" + x[i].getElementsByTagName("name")[2].childNodes[0].nodeValue+"");
document.write("</td><td>");
document.write("<font size=\"1\">" + x[i].getElementsByTagName("name")[3].childNodes[0].nodeValue+"");
}
</script>
</td></tr>
</table>
</div>
</body>
</html>
Updated code to handle "im:image" and the code now works in internet explorer and safari but not in chrome.
This will give a result. DEMO
Notice I access the entry elements and in the entries I access the im:image tags
UPDATE This works in IE8, Fx Safari and Chrome on XP
<html>
<head>
<title>RSS Apps</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var isIE = navigator.userAgent.indexOf('MSIE')!=-1;
var ns = {im:"http://itunes.apple.com/rss"}; // could be extracted from the root element's attributes
function getElems(obj,tagName) {
if (!obj.getElementsByTagNameNS) return obj.getElementsByTagName(tagName);
var prefix = "";
if (tagName.indexOf(":") !=-1) {
var parts = tagName.split(":")
prefix = parts[0];
tagName = parts[1];
}
if (prefix == "") return obj.getElementsByTagName(tagName);
return obj.getElementsByTagNameNS(ns[prefix], tagName);
}
window.onload=function() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://itunes.apple.com/au/rss/topfreeapplications/limit=10/xml?partnerId=1002&partnerUrl=http%3A%2F%2Fwww.s2d6.com%2Fx%2F%3Fx%3Dc%26z%3Ds%26v%3D3868801%26t%3D",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
var x=xmlDoc.getElementsByTagName("entry");
var html = "";
for (var i=0;i<x.length;i++) {
var entry = x[i];
var id =getElems(entry,"id")[0].textContent;
var nameTag = getElems(entry,"im:name");
var name = isIE?nameTag[0].text:nameTag[0].textContent;
html += '<a href="'+id+'">'+name+'<br/>';
var images = getElems(entry,'im:image');
for (var j=0;j<images.length;j++) {
html += '<img src="'+(isIE?images[j].text:images[j].textContent)+'"/>';
}
html+='</a><hr/>';
}
document.getElementById('content').innerHTML=html;
}
</script>
</head>
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<div id="content"></div>
</div>
</body>
</html>
UPDATE 2
jQuery version DEMO
$(document).ready(function() {
jQuery.support.cors = true; // IMPERATIVE for IE(8) support
$.ajax({
type: "GET",
url: "http://itunes.apple.com/au/rss/topfreeapplications/limit=10/xml?partnerId=1002&partnerUrl=http%3A%2F%2Fwww.s2d6.com%2Fx%2F%3Fx%3Dc%26z%3Ds%26v%3D3868801%26t%3D",
dataType: "xml",
success: function(xml) {
$(xml).find('entry').each(function(){
var id = $(this).find("id").text();
var title = $(this).find("title").text();
$("#content").append('<hr/>'+title+'<br/>');
var images = $(this).find("image");
if (images.length ==0) images = $(this).find("im\\:image");
$.each(images,function(){
$("#content").append('<img src="'+$(this).text()+'"/>');
});
});
}
});
});
There are definitely some issues with the foundation of your code. For instance, if you were to not hard-code in the index number of the image, such as:
x[i].getElementsByTagName("id")[2]
But instead actually confirmed they existed, that would avoid the error outright.
If I had to guess (and I do) regarding the issue with your specific error, I would assume it's because the image elements have im: namespace prefixes, and that perhaps the browsers throwing errors aren't recognizing the getElementByTagName as the tagname after the namespace.
This is, of course, only a guess. I would recommend using nested loops for each item you are trying to output, as this will isolate the problem, prevent fatal errors, and be easier to maintain and expand later.
Edit:
Does the following work:
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://itunes.apple.com/au/rss/topfreeapplications/limit=10/xml?partnerId=1002&partnerUrl=http%3A%2F%2Fwww.s2d6.com%2Fx%2F%3Fx%3Dc%26z%3Ds%26v%3D3868801%26t%3D",false);
xmlhttp.send();
var feed = xmlhttp.responseXML;
var entries = feed.getElementsByTagName("entry");
for (i = 0; i < entries.length; i++)
{
entry_id = entries[i].getElementsByTagName("id")[0];
entry_image = entries[i].getElementsByTagName("image")[0];
entry_name = entries[i].getElementsByTagName("name")[0];
entry_item = document.createElement("li");
entry_figure = document.createElement("figure");
entry_figure_img = document.createElement("img");
entry_figure_img.setAttribute("src", entry_image.firstChild.nodeValue);
entry_image_figcap = document.createElement("figcaption");
entry_figure.appendChild(entry_figure_img);
entry_link = document.createElement("a");
entry_link.setAttribute("href", entry_id);
entry_link_name = document.createTextNode(entry_name.firstChild.nodeValue );
entry_link.appendChild(entry_link_name);
entry_image_figcap.appendChild(entry_link);
entry_figure.appendChild(entry_image_figcap);
entry_item.appendChild(entry_figure);
document.body.appendChild(entry_item);
}

Categories

Resources