fguru
fguru

Reputation: 71

php json data return jquery

Looking for a best solution:

$.getJSON("InsertData.php", {fullName:val1, course_id:course_id, occupation:val2}, function(data) {
        $.each(data, function(i, user) {
            //alert(user.aryA.status);
            if(user.aryA.status == 'true'){
                currentPosition = 2;
                checkData();
                nextSlide();
            }else{
                 nextSlide();
            }
        });

    })

Here is php code:

    mysql_select_db("db", $con);

    $Query="SELECT * from table WHERE fullName='".$fullName."' and course_id='".$cid."'";
    $result = mysql_query($Query);
    $totalRecords = mysql_num_rows($result);
    if($totalRecords) {
        while ($row = mysql_fetch_array($result)) {
                $returnData[]=array(    //for Json data array
            'userName' => $row['fullName'],
            'aryA' => array(
                'status' => $row['status']
                )
            );
        }

    }

    if(!$totalRecords) {
        $insertQuery="INSERT INTO table (fullName,course_id,occupation) VALUES ('".addslashes($fullName)."','".addslashes($cid)."','".addslashes($d3)."')";
        $result1 = mysql_query($insertQuery);

    }else{
        if($stat == "true"){$value = 1;}
        }

mysql_close($con);

echo json_encode($returnData);

So In first case when I hit the php through jquery it saves data in database but give me error or length. Because $returnData is empty. Is there a way if $totalRecords is false, how to send json_encode to say there is no data or any value through json_encode to my jQuery function.

Thanks in advance.

Upvotes: 0

Views: 531

Answers (2)

pmandell
pmandell

Reputation: 4328

Just setup an else statement, and add a 'success' key to your array:

if($totalRecords){
    while ($row = mysql_fetch_array($result)) {
            $returnData[]=array(    //for Json data array
        'success'=>'true',
        'userName' => $row['fullName'],
        'aryA' => array(
            'status' => $row['status']
            )
        );
    }
}else{
    $returnData = array('success'=>'false');
}

Then check the value of 'success' in your jQuery.

Also, you really shouldn't be using mysql_*.

Upvotes: 1

JOE LEE
JOE LEE

Reputation: 1058

$returnData = array(); //add this
 $totalRecords = mysql_num_rows($result);
if($totalRecords) {
while ($row = mysql_fetch_array($result)) {
        $returnData[]=array(    //for Json data array
    'userName' => $row['fullName'],
    'aryA' => array(
        'status' => $row['status']
        )
    );
}

}
else
{
$returnData[] = 'no Record'; //add this
}

Upvotes: 0

Related Questions