Phonegap and restful web service - javascript

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?

Related

JavaScript and CSS files won't work in html (spring boot app)

I have a problem with a html file not 'loading' js and css files properly. This is my html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Create new snippet</title>
<script src="static/js/send.js"></script>
<link rel="stylesheet" href="static/css/button.css">
</head>
<body>
<textarea id="code_snippet" placeholder="//write your code here"></textarea><br/>
<button type="submit" onclick="send()">Submit</button>
</body>
</html>
It is supposed to take some input into the textarea tag and send it to a database when you click on the button. However, the function send() doesn't work at all. Also, the linked CSS doesn't work as well. This is my project structure:
This is the send() function:
function send() {
let object = {
"code": document.getElementById("code_snippet").value
};
let json = JSON.stringify(object);
let xhr = new XMLHttpRequest();
xhr.open("POST", '/api/code/new', false)
xhr.setRequestHeader('Content-type', 'application/json; charset=utf-8');
xhr.send(json);
if (xhr.status != 200) {
alert("Something went wrong!");
} else if (xhr.status == 200){
alert("Success!");
}
}
This function works fine when I put it inside of script tag
You should make sure the links are relative or absolute to the home directory.
/absolute path
and use without "/" for relative path
try to access css and js file links from browser.

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

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.

How can I create function on ajax event (onreadystatechange)

I am very much new in ajax .
Trying to understand through the tutorial
trying code :
<DOCTYPE html PUBLIC" ..//w3c//DTDXHTML 1.0 strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>ajax</title>
<script language="javascript" type="text/javascript">
xmlhttp = new XMLHttpRequest();
function getScores() {
xmlhttp.onreadystatechange() = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('scores').innerHTML = xmlhttp.responseText;
} else {
document.getElementById('scores').innerHTML = "<strong>Sonal Goyal</strong>"
}
}
xmlhttp.open("GET", "https://www.learntoprogram.tv/baseball.php", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="score"></div>
<input type="button" value="get scores!" onclick="getScores()" />
</body>
</html>
where I am lacking?
Your code looks fine to me except that you have a spelling mistake in you input-divContainer id.
To find out what is the error output xmlhttp data in your else
clause
xmlhttp.onreadystatechange() = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('scores').innerHTML = xmlhttp.responseText;
} else {
document.getElementById('scores').innerHTML = xmlhttp.status;
}
}

Categories

Resources