Hello i am getting an error TypeError: data is null i can't find the error.

js

<script>
$(document).ready(function()
{
username='<?php echo $_GET['public_username']; ?>';
apiBaseUrl='<?php echo $base_url; ?>';

singleArtist(apiBaseUrl,username);

});

function singleArtist(apiBaseUrl,username)
{
    var html ='';
    var encodedata=JSON.stringify({"username":username});
    var url=apiBaseUrl+'api/singleArtist'; 
    ajaxPost(url,encodedata, function(data) {
        if(data.length)
        {
            $.each(data, function(i,data)
            {
                html += 'dddddd';
            });
            $('#singleArtist').html( html );
        }
    });
}
</script>

php

function singleArtist()
{
$request = \Slim\Slim::getInstance()->request();
$data = json_decode($request->getBody());
$username=$data->username;
    $sql = "SELECT * FROM users WHERE username=:username ";
    try {
        $db = getDB();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("username", $username,PDO::PARAM_STR);
        $stmt->execute();
        $singleArtist = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo '{"singleArtist": ' . json_encode($singleArtist) . '}';
    } catch(PDOException $e) {
        echo '{"error":{"text49":'. $e->getMessage() .'}}'; 
    }

}

My guess would be "Line 17" of the above Javascript.

If no "data" is passed to the function (which is in Line 16), then data will be a NULL Object, which does not have a "length" method.

Exception thrown: most likely in line 17 of the Javascript.
Root cause: most likely in line 16: no "data" is passed over to the function.

It should be a value passed. When i put the sql script on phpmyadmin it returns tha value as wanted

Why not put a console.log right before

if (data.length ...

between existing line 16 and line 17 which echoes the details of data?

sorry for the delay maba001 i did

console.log(data)
            if( data.length )

and on the console JS returns this null

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.