I use a $.getJSON
request (onload) to access data from my DB passing a url to my front controller. The app is based on model view controller framework (own creation). The url in the ajax request (/purchases/index) calls the purchases controller and executes the index action.
The purchases controller uses a "user" model to access db and fetch the data.
About functionality. The user first call my website, then needs first to login and then ajax request will be executed.
The problem is, when user has logged in and ajax request is executed, my website is redirected to /purchases/index. A route where I only use for calling a controller an action (nothing to display). Here only my echo json_encode
is displayed
How to avoid this redirection, and just fetch the data in json format?
I have tried redirecting from php side, redirecting from js side, using login data for conditioning ajax behavior.
If I manualy erase the url and go back to my webroot, then I can see the data fetched in js console
JS Code
$.getJSON('/purchases/index', function (res) {
console.log(res);
});
Php Code
public function index($purchases = [])
{
$user = Auth::getUser();
$userPurchases = User::userPurchases($user->id_db);
if (! empty($userPurchases)) {
$purchases[] = $userPurchases[0]->user_id_db;
foreach ($userPurchases as $item) {
$purchases[] = $item->product_name_db;
}
echo json_encode($purchases);
}
}
Cheers