Skip to content
Advertisement

Datatables throw invalid json error randomly

I am using Datatables plugin in my php project. For populating the table, I use ajax to load data from mysql database. It works, however, it periodically and randomly throws ‘Invalid Json’ error. What do you think is the problem? The following is the ajax block in datatables script:

ajax: {
       method: 'POST',
       url: "core.php",
       dataType: "json",
       dataSrc: "",
       }
   }

The following is also from my core.php file:

        if (isset($_POST['reports']) and $_POST['reports'] == true) {
        $reports = $db->getAllReports();
        echo json_encode($reports);
    }

What has really mixed me up is that the codes work, and invalid json error appears after I refresh the page for five or six times, or sometimes the very first time I open the page.

Advertisement

Answer

As it is clarified in datatables documentations, the ‘invalid Json’ error is what it signifies. that is, the json object send to datatables is wrong, and/or not what is expected. So, if you ever happen to run into a similar problem, try to diagnose the problem on the server-side and not datatables itself. Moreover, what caused problems in my case, and it would run you into problems is Phpstorm IDE. Phpstorm server intervenes with the local server or whatever, and gets the returned json data to be incomplete. So what you are going to do to solve the problem is to remove the phpstorm port in front of your localhost, that is, for instance, in this link http://localhost:63342/yoursite, you need to delete the ‘:63342’ from the link, and test your site with your Wamp or Xamp, and there would be no interventions from phpstorm and datatables will work properly.

All the best.

Good luck.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement