0

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;
            }

2 Answers 2

1

Short answer: use JSON. PHP:

$xp = (int)mysql_result($link, 0);
echo json_encode($xp);

JavaScript:

$.getJSON('scripts/loadxp.php', function(xp) {
  alert(xp);         // 1
  alert(typeof xp);  // number
});

It's worth noting that you can send any number of native types back and forth using JSON. Strings, numbers, booleans, null, arrays, and objects are all supported.

Sign up to request clarification or add additional context in comments.

9 Comments

@Nathan This sounds great, but having tried to implement it, it doesn't seem to work - the getJSON function doesn't seem to advance past the query itself. Firebug says the query occurs and gets the number back, but it doesn't look like jQuery recognises it as a success.
@Hal Are you able to see the AJAX response in something like Firebug? Is it possibly getting an error?
@Hal Wow -- I wonder if the mystery characters are even messing up the JSON parsing. Is this output available anywhere that I can look at?
@Nathan I'm not sure exactly what you're looking for, but here's some copy-pasta from firebug: Response Headersview source Date Fri, 11 Mar 2011 23:25:30 GMT Server Microsoft-IIS/6.0 X-Powered-By ASP.NET, PHP/5.2.6 Expires Thu, 19 Nov 1981 08:52:00 GMT Cache-Control no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma no-cache Content-Type text/html Content-Length 9 RESPONSE: 100
@Hal Ah. Your original regexp will strip those out. You could try using your first JS $.get(), then pass the sanitized result to $.parseJSON() to get a number back. You should dig into your PHP files and look for any extra newlines or spaces before the first <?php tags in them. Something is echoing this out and screwing things up.
|
0

I notice you are missing quotes around the first value in the xP.replace() line, that might be the reason it doesn't work in JS.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.