Getting odd results through AJAX - php

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://

Related

AJAX post to php

Although i have followed the sample code from http://api.jquery.com/jQuery.post/ and of course Stackoverflow i couldnt find a solution to my problem.
I have a toggle image in html which everytime a user clicks on it,changes the image and update the column in the DB.Here is the code:
HTML
<input type="image" src="smileys/heart.gif" class="play" onclick="toggle(this,'<?php echo $ida;?>')"/>
AJAX
function toggle(el,al){
if(el.className=="play")
{
el.src='smileys/lol.gif';
el.className="pause";
$.post("update.php", { "hr": 1, "ida": al } );
}
else if(el.className=="pause")
{
el.src='smileys/heart.gif';
el.className="play";
$.post("update.php", { "hr": 0, "ida": al } );
}
console.log(al);
return false;
}
update.php
<?php
$host = "localhost";
$user = "user";
$pass = "pass";
$database = "db";
$heart=$_GET["hr"];
$ida=$_GET["ida"];
$con = mysql_connect($host,$user,$pass);
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db($database, $con);
mysql_query("UPDATE tablename SET heart='$heart' WHERE id='$ida'");
?>
The toggle function works well but the DB is not updated when a user clicks and the image.
I believe it has to do with the $.post function,not sending correctly the data to the php.
BTW if i do
http://domain.com/update.php?hr=1&ida=127
it works.
NOTE: I am using mysql and not PDO only for this example.
...and yes my code is messy and ugly,still learning.
Any help?
Thanks
Well, it's a _POST request and not an _GET, so, to capture its values you need to use $_POST instead $_GET.
Also, as i noticed, there's and _GET link, so you need to change your $.post with $.get.

Loading JSON using jQuery Mobile & Phonegap?

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.

Loading JSON in Phonegap?

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.

Sending ByteArray through as3 to PHP

The BLOB field (pic) is turning out as 0 Bytes when trying to send ByteArray through as3 to PHP, so i assume the PHP script or the HTTP_RAW_POST_DATA isn't working.
I think the Flash part is working, I have set a trace() to see if the bitmapdata is coming through and it seems it is, so I'm assuming its my php side. I'll post both parts of the code in hope someone here can fix it for me. Thanks.
AS3
private function export():void
{
var bmd:BitmapData = new BitmapData(600, 290);
bmd.draw(board);
var ba:ByteArray = PNGEncoder.encode(bmd);
trace(ba);
var _request:URLRequest = new URLRequest ("http://site.com/readimage.php");
var loader: URLLoader = new URLLoader();
_request.contentType = "application/octet-stream";
_request.method = URLRequestMethod.POST;
_request.data = ba;
loader.load(_request);
}
PHP
<?php
$username = "images";
$password = "password";
$host = "localhost";
$database = "images";
$link = mysql_connect($host, $username, $password);
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db ($database);
$query ="INSERT INTO main (pic) VALUES ('".$GLOBALS["HTTP_RAW_POST_DATA"]."')" or die(mysql_error());
$results = mysql_query($query, $link);
?>
$blob = file_get_contents('php://input');
This should work for you. This accesses PHP's raw input stream. It's more likely to work in some cases, apparently:
php://input allows you to read raw data from the request body. In case of POST requests, it preferrable to $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data.
You'll also want to ensure that you properly escape this data when placing it in the database:
$query = "INSERT INTO main (pic) VALUES ('" . mysql_real_escape_string($blob) . "')";
(It is also possible that $HTTP_RAW_POST_DATA's magic only works when you reference it directly instead of through the $GLOBALS array.)
Try breaking apart your whole process - if it's not working, start stripping away things before you get as far the sql insert...
First off, open up firebug or chrome/safari console and log your data being passed to your php page - then perhaps just start seeing what's being passed:
foreach (getallheaders() as $name => $value) {
echo "$name: $value\n";
}
If you have the console open, it should log the echo's to that.

javascript, php, cookies

the application returns a value "1" in the database instead of the mac address...
I'm able to document.write the output of the mac address, but not able to have it store in the database.
Is the program using the previous cookie? (but Ive deleted all the cookies from the pc)
but if i change the variable mac to string data, it keep refresh my webpage. Why is that so... (var mac="test data";)
Please help!
create_users.php
<script language="JavaScript">
function getMacAddress(){
document.macaddressapplet.setSep( "-" );
return (document.macaddressapplet.getMacAddress());
}
function setCookie(c_name,value) {
document.cookie = c_name + "=" +escape(value);
}
//var mac="test data";
var mac = getMacAddress();
setCookie('cookie_name',mac);
window.location = "checkAvailability.php";
</script>
<script type="text/javascript">
document.write(getMacAddress());
</script>
checkAvailiability.php
$dbhost = 'localhost';
$dbuser = 'root';
$dbname = 'registration';
mysql_connect($dbhost, $dbuser) or die("Could not connect database");
mysql_select_db($dbname);
$javascript_cookie_value = isset($_COOKIE["cookie_name"]) ? $_COOKIE["cookie_name"] : 1;
mysql_query("INSERT INTO test (mac) VALUES ('$javascript_cookie_value')");
Why not:
window.location = "checkAvailability.php?mac=" + mac;
and eliminate cookie problems?
I presume you've checked that the applet is behaving as you expect?
C.
Assuming that code appears in checkAvailability.php, then it keeps refreshing because you have window.location = "checkAvailability.php"; with no logic to stop it running — so every time it loads the page, it gets redirected to that URI.

Categories