0
votes

I am using jQuerydatables and server side scripting with php and mysql. I have modified the script found here:

https://legacy.datatables.net/examples/data_sources/server_side.html

and I have included an if-else which is wrapped around the entire script.

The goal is to only allow results to be returned if the user posted a valid token from my db.

So I have that bit set up. But I am unsure how to handle the error message to the user.

Right now, when a user passes in an invalid token, my website (using datatables) throws up the error invalid JSON response.

I assume this because it is expecting iTotalRecords etc in the JSON returned.

I am wondering if anyone knows how to achieve this. I haven't been able to find any examples.

Algorithm:

if (postedToken exists in db){
   return datatables JSON
}
else{
   return json in such a way that I can provide an alert to the user that their   session has expired
}

and datatable initialisation:

"sAjaxSource": "mydatatablescript.php?token=<?php echo $token;?>

EDIT:

I was returning a valid JSON but I was missing a few parameters which must be required i.e. 'iTotalRecords' => 0, 'iTotalDisplayRecords' => 0, 'aaData' => [], 'sEcho' => 0.

Now I am not getting the error message described in the question. I see there is a "fnDrawCallback" parameter I can include in the datatable initialisation. I suspect here I can check my message param and alert if necessary but I just don't know how to access the JSON from within that function?

1
Why don't you return just empty JSON? - sitilge
@sitilge I need to be able to prompt the user that their session has expired. That would be different to them searching for something in the table which has no results. i.e. the table has a filter option which uses the script provided and that can return no results but that doesn't mean that the user has to log out and back in - user2363025
Well, return empty json and parse the response with js/jquery on client side. - sitilge
@sitilge see edited question please - user2363025

1 Answers

1
votes

As you have seen already, you need to return valid json in any case if your client-side is expecting that.

You could do that using for example something like:

if (postedToken exists in db){
   return datatables JSON
}
else{
   return json_encode(array('success': false, 'message': 'session has expired'));
}

You should probably add these same keys / parameters when the call is successful as well so that you can easily check in your javascript function what the result of the operation is.