Calisto Calisto - 7 months ago 7
SQL Question

How to get a single mysql value and output it to an ajax call?

I'm trying to get a number from a mysql line then outputting it to ajax. the number can't be a string because I will multiply it in ajax. This is what i have so far. I'm not sure what to do from here.

ajax:

$(document).ready(function()
{
$("#btnCalc").click(function()
{
var user = $("#txtUser").val();
var amount = $("#txtAmount").val();
var category = $("txtCat").val();
var number = $("txtNum").val();
var result = '';

$.get("code/value.php",
{
ID:user,
amount:amount,
result:result

},function(query)
{
if ( user > 0 and user < 30 ){
alert(result);
}
else{
alert( 'invalid user ID');
}
});
});

});


php:

<?php

$userID = $_GET["ID"];
$amount = $_GET["amount"];
$category = $_GET["category"];
$num = $_GET["number"];

require "../code/connection.php";

$SQL = "select userAmount from user where userID= '$userID'";

$reply = $mysqli->query($SQL);

while($row = $reply->fetch_array() )
{


}

if($mysqli->affected_rows > 0){
$msg= "query successful";
}
else{
$msg= "error " . $mysqli->error;
}

$mysqli->close();

echo $msg;
?>

Answer

Pretty straightforward - you just grab the value from the row and cast it as a float.

while($row = $result->fetch_array() )
{
    $msg = floatval($row['userAmount']);
}
if($msg > 0) {
    echo $msg;
} else {
    echo "error" . $mysqli->error;
}

$mysqli->close();

And one small change in your ajax call:

    $.get("code/value.php",
    {
        ID:user,
        amount:amount,
        result:result

    },function(query)
    {
        alert(query);
    });
});
Comments