I have a MySQL database with a column of numeric value. When I query this database in PHP and echo the mysql_result back to jQuery, the values returned appear to have superfluous line breaks and spaces (according to Firebug and experiments with alert()).
The resultant variable appears to work as I had expected when placed into an element with innerhtml, but I can't get logical or mathematical functions to work with it, even after attempting to clear out any of the extra characters and running parseInt...
Some sample code is below, but I'm probably doing something quite simple wrong.
Any ideas?
PHP "loadxp.php"
<?php session_start();
include("dbconnect.php");
//retrieve userid from session variable
$user = $_SESSION['userid'];
$query = "SELECT xp FROM breadusers WHERE userid='$user'";
$link =@mysql_query($query);
if(!$link){
die('Could not query:' . mysql_error());
}
echo mysql_result($link, 0);
?>
Javascript:
function showXP(){
var xP;
var level;
//jQuery AJAX load XP
$.get("scripts/loadxp.php", function(data){
xP = data;
//Display XP
$('#xpDisplay').html(xP);//NB: WORKS AS EXPECTED
//Calculate level
level = calculateLevel(xP);
//Display level
$('#levelDisplay').html(level);//Always NaN
});
}
function calculateLevel(xP){
var level;
var xPInt;
xP = xP.replace(/(\r\n|\n|\r| )/gm,"");//Attempt to strip out line breaks and spaces
xPInt = parseInt(xP,10);//Always seems to return "NaN"
alert("xP value: \"" + xP + "\" of type: " + typeof(xP) + "\nxPInt value: \"" + xPInt + "\" of type: " + typeof(xPInt));//xP is described as String "0", xPInt Number "NaN"
if ( xP == 0 ) {
level = 1;
} else {
level = Math.floor(1+Math.sqrt((xP/125) + 1));
}
return level;
}