Problem with response in API

This public forum is for user-to-user discussions of PHPMaker. Note that this is not support forum.
Post Reply
sclg
User
Posts: 149
Location: UK

Problem with response in API

Post by sclg »

I'm following Example 4 in the Lookup Table API section to fill in a field on a page when a name is selected in another field.

My api_action is

    $app->get('/getMaxRef/{user_id}', function ($request, $response, $args) {
        $user_id = $args["user_id"] ?? null; // Get the input value
        if ($user_id !== null) {
            $response = $response->write(ExecuteScalar("SELECT MAX(refnum) AS maxref FROM firearms WHERE user_id = " . AdjustSql($user_id))); 
        return $response;
        }
    });

and the startup script is

$("#x_user_id").change(function() { 
    $.get(ew.getApiUrl(["getMaxRef", $(this).val()]), function(res) {
         if (res) {
            $("#x_refnum").val(res);
        }
    });
});

This works fine and returns a number - as long as the query returns a result. However, the query may well NOT return anything as there may be no records for some instances of user_id.

I'm having trouble capturing this case and it seems to be to do with the type of variable in $response.
If I add something to check this like....

if ($response !== null) {
   $response = $response + 1;
} else {
   $response = '1';
}

then it fails with...
"D:\wwwroot\lsrpc2024\vendor\slim\http\src\Response.php(351): Slim\Http\Response::write(): Argument #1 ($data) must be of type string, null given, called in D:\wwwroot\lsrpc2024\src\userfn.php on line 165"
...on the line with the d/b access call.
(Using console.log to get the error message in the startup script)

I want to end up with either the result of the lookup + 1 or - if nothing is returned, '1' but whatever I try I get type errors of some sort.

I'd welcome any advice.


arbei
User
Posts: 9384

Post by arbei »

Note that $response is the Response object, not a integer, you should increase the result of ExecuteScalar(...) instead, then use $response->write() to output your value.


sclg
User
Posts: 149
Location: UK

Post by sclg »

Thanks but I'm not sure what you mean by "increase the result of ExecuteScalar(...)"??


mobhar
User
Posts: 11727

Post by mobhar »

That means, you may increase the result or the output that returned by ExecuteScalar global function, that suits your needs.


Post Reply