Basically I have a php script located on a sever that generates a JSON file listing places from a mysql database. Using jQuery Mobile I am developing an application to display these places. My code works in Chrome & Safari, however when I port it over to Phonegap it doesn't work. I have searched all over the internet but can't find an answer :(.
The php file for generating JSON (json.php):
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "xxx";
$password = "xxx";
$database = "xxx";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT * FROM places ORDER BY name ASC";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
My Javascript file located within my app (Loads JSON and displays it):
$('#places').bind('pageinit', function(event) {
getPlaces();
});
function getPlaces() {
var output = $('#placeList');
$.ajax({
url: 'http://www.mysite.com/json.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var place = '<li><a href="">'+item.name+'<span class="ui-li-count">'
+ item.checkins+'</span></a></li>';
output.append(place);
});
$('#placeList').listview('refresh');
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
The HTML looks like this:
<div data-role="content">
<h3>Places</h3>
<ul data-role="listview" id="placeList" data-inset="true">
</ul>
</div><!-- /content -->
This code works in Chrome & Safari, however when run in the xCode simulator with Phonegap it doesn't load the JSON.
Any help would be much appreciated :)
I don't think the problem has anything to do with the server code (PHP), unless you are producing invalid JSON. The question should be tagged with JavaScript rather than PHP. Anyway, there is an excellent article describing a very similar type of application. It even includes sample code. Have a look:
Sample Application using jQuery Mobile and PhoneGap
Dude,
That's server side script it won't run unless its hosted on a server with those languages implemented. I'm running into a similar problemn One suggestion was to implmented the AJAX to fetch the data from a php site an return the data. I'm look'n to just forward the whole page over too a Safari webview window (which you have to set in phonegap permissions). Problem there is I get all the Safari chrome on the top and bottom trying to figure out how to trim that so I don't have to recode with AJAX to pull PHP data server side.
Related
So I'm making a simple login/registration web application but I keep getting the following error:
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/login.html Line Number 37, Column 3:
and
XML Parsing Error: no root element found Location: file:///C:/xampp/htdocs/EdgarSerna95_Lab/php/login.phpLine Number 37, Column 3:
here is my login.php
<?php
header('Content-type: application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "jammer";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
header('HTTP/1.1 500 Bad connection to Database');
die("The server is down, we couldn't establish the DB connection");
}
else {
$conn ->set_charset('utf8_general_ci');
$userName = $_POST['username'];
$userPassword = $_POST['userPassword'];
$sql = "SELECT username, firstName, lastName FROM users WHERE username = '$userName' AND password = '$userPassword'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$response = array('firstName' => $row['firstNameName'], 'lastName' => $row['lastName']);
}
echo json_encode($response);
}
else {
header('HTTP/1.1 406 User not found');
die("Wrong credentials provided!");
}
}
$conn->close();
?>
I've done some research about xml parsing errors but I still cant manage to make my project work, ive tried with Google Chrome and Firefox
AHA! Got this today for a reason which will make me look pretty silly but which might one day help someone.
Having set up an Apache server on my machine, with PHP and so on... I got this error... and then realised why: I had clicked on the HTML file in question (i.e. the one containing the Javascript/JQuery), so the address bar in the browser showed "file:///D:/apps/Apache24/htdocs/experiments/forms/index.html".
What you have to do to actually use the Apache server (assuming it's running, etc.) is go "http://localhost/experiments/forms/index.html" in the browser's address bar.
In mitigation I have up to now been using an "index.php" file and just changed to an "index.html" file. Bit of a gotcha, since with the former you are obliged to access it "properly" using localhost.
I had same situation in Spring MVC Application as it was declared as void, changing it to return String solved the issue
#PostMapping()
public void aPostMethod(#RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body);
}
To
#PostMapping()
public String aPostMethod(#RequestBody( required = false) String body) throws IOException {
System.out.println("DoSome thing" + body);
return "justReturn something";
}
Assuming you are working with javascript, you need to put a header in front of echoing your data:
header('Content-Type: application/json');
echo json_encode($response);
Make sure you're php server is running and that the php code is in the appropriate folder. I ran into this same issue if the php was not there. I also recommend putting your html in that same folder to prevent cross-origin errors when testing.
If that is not the issue, ensure that every SQL call is correct in the php, and that you are using current php standards... Php changes quickly, unlike html, css and Javascript, so some functions may be deprecated.
Also, I noticed that you may not be collecting your variable correctly, which can also cause this error. If you are sending variables via form, they need to be in proper format and sent either by POST or GET, based on your preference. For example, if I had a login page for a maze game:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<form class="modal-content animate" method="post">
<div class="container">
<label><b>Username</b></label>
<input type="text" id="usernameinput" placeholder="Enter username" name="uname" required>
<label><b>Password</b></label>
<input type="password" id="passwordinput" placeholder="Enter Password" name="psw" required>
<button onclick="document.getElementById('id01').style.display='block'">Sign Up</button>
<button type="button" id="loginsubmit" onclick="myLogin(document.getElementById('usernameinput').value, document.getElementById('passwordinput').value)">Login</button>
</div>
</form>
JavaScript
function myLogin(username, password){
var datasend=("user="+username+"&pwd="+password);
$.ajax({
url: 'makeUserEntry.php',
type: 'POST',
data: datasend,
success: function(response, status) {
if(response=="Username or Password did not match"){
alert("Username or Password did not match");
}
if(response=="Connection Failure"){
alert("Connection Failure");
}
else{
localStorage.userid = response;
window.location.href = "./maze.html"
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
var response = xhr.responseText;
console.log(response);
var statusMessage = xhr.status + ' ' + xhr.statusText;
var message = 'Query failed, php script returned this status: ';
var message = message + statusMessage + ' response: ' + response;
alert(message);
}
}); // end ajax call
}
PHP
<?php
$MazeUser=$_POST['user'];
$MazePass=$_POST['pwd'];
//Connect to DB
$servername="127.0.0.1";
$username="root";
$password="password";
$dbname="infinitymaze";
//Create Connection
$conn = new MySQLi($servername, $username, $password, $dbname);
//Check connetion
if ($conn->connect_error){
die("Connection Failed: " . $conn->connect_error);
echo json_encode("Connection Failure");
}
$verifyUPmatchSQL=("SELECT * FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$result = $conn->query($verifyUPmatchSQL);
$num_rows = $result->num_rows;
if($num_rows>0){
$userIDSQL =("SELECT mazeuserid FROM mazeusers WHERE username LIKE '$MazeUser' and password LIKE '$MazePass'");
$userID = $conn->query($userIDSQL);
echo json_encode($userID);
}
else{
echo json_encode("Username or Password did not match");
}
$conn->close();
?>
It would help if you included the other parts of the code such as the html and JavaScript as I wouldn't have to give my own example like this. However, I hope these pointers help!
So I built the code for a web application on WAMP (my first time using any server stuff) and a test database we made looking at the client's databases. When trying to implement, we have run into a lot of trouble. They are using an enterprise server (NOTE: I have no idea what I am talking about here) and MSSQL where I just used localhost, root, and no password on WAMP with MYSQL. I have no idea how to help them get the product implemented. It works fine on my computer but for them, it says Bad Request 400 when I have AJAX print out the error text.
ajax request
$.ajax({
type: "GET",
url: "getJobList.php",
data: "hline="+lineLabel[currentLine],
dataType: "json",
success: function(data){
//do successful stuff
}
}
php file
<?php
include "config.php";
$con = mysql_connect($host);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$hline=$_GET["hline"];
if (empty($hline)){
echo "1"; //default rate
}
else{
$db=mysql_pconnect($host, $user, $pass);//connect to local database
mysql_select_db($databaseName, $db);//select the database you want to use
if (!$db){
echo ("error connecting to database");
}
else{
//connection successful
$sql = " SELECT partparameters.cspc,processingrate,setuptime,lotsize,duedate,duetime,homeline
FROM jobs
INNER JOIN partcoding
ON jobs.partnumber=partcoding.partnumber
INNER JOIN partparameters
ON partcoding.cspc=partparameters.cspc
WHERE homeline = '$hline'
ORDER BY duedate,duetime ASC";//sql string command
$result=mysql_query($sql) or die (mysql_error());//execute SQL string command
//result contains rows
$arr = array();
$num = 0;
while($rows = mysql_fetch_array($result))
{
$array[$num] = $rows;
$num++;
}
echo json_encode($array);
}
}
?>
php config file
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "gmdata1";
?>
Any ideas? Thanks in advance!
EDIT: Fixed a stray parenthesis that I mistyped when posting. Also if it makes a difference I developed on Chrome and the Users are using Firefox. I dont think it should make a difference though because they render the same.
EDIT 2:
Request URL:
http://usmmcsa0wwt01/ProdSched/getJobList.php?hline=G%20%201
Request Method:
GET
Status Code:
HTTP/1.0 400 Bad Request
Request Headers
15:24:24.000
X-Requested-With:XMLHttpRequestUser-Agent:Mozilla/5.0 (Windows NT 6.1; rv:20.0) Gecko/20100101 Firefox/20.0Referer:http://usmmcsa0wwt01/ProdSched/index.phpHost:usmmcsa0wwt01Connection:keep-aliveCache-Control:max-age=0Accept-Language:en-US,en;q=0.5Accept-Encoding:gzip, deflateAccept:application/json, text/javascript, */*; q=0.01
Response Headers
Δ2ms
Server:CIMPLICITY-HttpSvr/1.0Date:Mon, 22 Apr 2013 19:24:24 GMT
This is what I get in their firefox console inspect HTTP request
Your data is wrong. To pick up $_GET["hline"] you either want hline="+lineLabel[currentLine] in the URL (not recommended) or format the data correctly.
data: {"hline": lineLabel[currentLine]},
Try this -
$.ajax({
type: "GET",
url: "getJobList.php",
data: {"hline": lineLabel[currentLine]},
dataType: "json",
success: function(data){
//do successful stuff
}
}
Related to: Query Database through Javascript / PHP
This question is related to my above question. I fixed the PHP script to the one as mentioned in one of my answers; I attempted to use $.getJSON to no avail. So I stuck with my original method of getting a response from the server:
function getDatabaseRows()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
alert(xmlHttp.responseText);
}
}
xmlHttp.open("POST", "myDomain.com/subDirectory/getRowCounts.php", true);
xmlHttp.send(null);
}
When the alert runs, it acts as if it is a text file, and gets the entire contents of my PHP script. It doesn't run the script, it merely grabs a text-copy of it off of the server. My script (which is linked in the earlier question) is:
$rowCounts = array();
$dbhost = 'host';
$dbuser = 'host';
$dbpass = 'host';
$dbase = 'host';
$fields = array(
'MaxTID' => array('tab' => 'TransData', 'col' => 'TID'),
'MaxSID' => array('tab' => 'FullData', 'col' => 'SID'),
'MaxFID' => array('tab' => 'SalamanderData', 'col' => 'FID'),
'MaxOID' => array('tab' => 'OthersData', 'col' => 'OID')
);
$con = mysql_connect($dbhost, $dbuser, $dbpass) or die('Error connecting to mysql');
mysql_select_db($dbase, $con) or die(mysql_error());
foreach ($fields as $id => $info) {
$sql = "SELECT MAX({$info['col']}) FROM {$info['tab']}";
$result = mysql_query($sql, $con);
if (!$result) die('Could not query:' . mysql_error());
$rowCounts[$id] = mysql_result($result, 0);
}
echo json_encode($rowCounts);
mysql_close($con);
Any clue as to why my AJAX script returns a text-copy of the PHP script on the server; and not the JSON results I am looking for?
EDIT:
Pointing my browser to the PHP script returns:
{"MaxTID":"1","MaxFID":null,"MaxSID":"3","MaxOID":"1"}
$.getJSON is jQuery, so you would need to include it in your page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script>
$.getJSON('http://myDomain.com/subDirectory/getRowCounts.php', function(response) {
console.log(response);
});
</script>
Javascript is going to pull down whatever the http server gives it. So if the http server is not configured correctly to process your server-side script I.E. php, then you're going to get the contents of the file instead of the processed html output from running the php script. Contact your server admin to get it fixed, and verify that you are using a .php extension on your file and not .txt.
Found the solution.
The problem arrises from the fact that I was working on a network share drive ....which also happened to be living on the web server.
So whenever I went to test the script, it would fetch my file like so:
file:////mySubDomain.myDomain.com/getRowCounts.php ... Which obviously can't work, considering it isn't being served by the server.
Fixed by changing file://// to http://
I want to return JSON data from a resulted SQL statement in a PHP script upon pressing Submit button, but I receive null instead.
I'll be using the returned JSON to filter-show markers on my Google Map, but for now I just want to get the data back across to my jQuery page from PHP script so I can manipulate/use it.
Submit button:
HTML
<input type="submit" id="filter" value="Filter" />
JS
$('#myform').on('submit', function(e) {
e.preventDefault();
var myData = $('#myform').serializeArray();
$.getJSON('myscript.php', myData, function(json){
alert(json);// actually filter for later
});
});
PHP script:
// action is a hidden form control I use to check if form was submitted
if(isset($_POST["action"])){
if(isset($_POST["color"]) && isset($_POST["zipcode"])){
// try to open a connection to a MySQL server
$connection = mysql_connect($host, $username, $password) or die("Could not connect" . mysql_error());
// select the active MySQL database to work with
$db_selected = mysql_select_db($database, $connection) or die("Can\'t use db:" . mysql_error());
$query = 'sql statement to return resutls based on what color and zipcode was provided';
$result = mysql_query($query) or die("Can\'t do that: " . mysql_error());
}
// close connection to the database
echo json_encode($result);
mysql_close($connection);
}
You can't return the result object of a mysql_query call directly. You first have to parse it with functions like mysql_fetch_array or alike (PHP docu).
...
$result = mysql_query($query);
if ( $result === false ) {
die("Can\'t do that: " . mysql_error());
}
$retVal = array();
while( $row = mysql_fetch_array( $result ) ) {
$retVal[] = $row;
}
...
echo json_encode( $retVal );
EDIT
According to the jQuery spec for getJSON (link), the data is sent using GET parameters and not using POST. So you would have to change all the $_POST appearances in your PHP code to either $_GET or $_REQUEST.
Besides this, you should return some error messages if your variables are not set. Right now (according to your code) just an empty document is returned.
Before the echo you should declare the returned content type:
header('Content-Type: application/json');
If you want to check for the receival of the data you can use:
$.ajax({
url: url,
data: myData,
success: function(json) {},
error: function(json) {} // this should allow you to check if data is received (but since the content type is set to text/html and $.getJSON expectr application/json it won't be a success)
});
Basically I have a php script located on a sever that generates a JSON file listing places from a mysql database. Using jQuery Mobile I am developing an application to display these places. My code works in Chrome & Safari, however when I port it over to Phonegap it doesn't work. I have searched all over the internet but can't find an answer :(.
The php file for generating JSON (json.php):
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "xxx";
$password = "xxx";
$database = "xxx";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT * FROM places ORDER BY name ASC";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
My Javascript file located within my app (Loads JSON and displays it):
$('#places').bind('pageinit', function(event) {
getPlaces();
});
function getPlaces() {
var output = $('#placeList');
$.ajax({
url: 'http://www.mysite.com/json.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var place = '<li><a href="">'+item.name+'<span class="ui-li-count">'
+ item.checkins+'</span></a></li>';
output.append(place);
});
$('#placeList').listview('refresh');
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
The HTML looks like this:
<div data-role="content">
<h3>Places</h3>
<ul data-role="listview" id="placeList" data-inset="true">
</ul>
</div><!-- /content -->
This code works in Chrome & Safari, however when run in the xCode simulator with Phonegap it doesn't load the JSON.
Any help would be much appreciated :)
This has probably something to do with the whitelisting, Apple has no faith in any type of uncontrollable data (like iframes or feeds). So they reject every external connection.
Take a look at phonegap.plist in your project rootfolder (xcode) and add your website url to the array 'ExternalHosts'. This will probably work fine after.