KotjengOren
KotjengOren

Reputation: 79

JS Fetch Single Record From Laravel Controller

I work in laravel and trying to get the response from the page. This is the controller in question:

public function counter($id)
{
    $toSearch = $id * 10000;
    $latest = User::where('counter', '>=', $toSearch)->get()->last();
    $res = $latest['counter'] % $toSearch;
    return $res;
}

As you can see the result that been returned by the controller is a single record and I am desperate to getting that record in to the Java Script File in the separate file than my blade view. I don't want to access the data base from JS and just trying to get that single record.

This is the function that is responsible for returning the result:

function counter(id) {
    let data;
    // Please Help Me Here 
    return data;
}

The returned value from this function will be used for another function.

The way the algorithm work is calling the function counter form the JS file which the result will be handled by the controller by somewhat using fetch or anything.

Note: the result must be in integer <- perhaps there is another thing to do to convert it to integer / number.

Upvotes: 0

Views: 798

Answers (1)

tokkerbaz
tokkerbaz

Reputation: 397

I see 2 options of solving your problem:

1. Send variable to blade template and then with js retrieve it.

2. Make ajax request to retrieve the data, you need to create separate route, so the route only return result via JSON.

Both variants are having their cons and pros. For someone its easier second, forelse first. I'll try to write both down below:

1. Sending data to Blade - for this one you need to know where that counter will be used, if you trying to use it globally, then you might attach to body or footer/header as like:

<body data-counter="{{App\Http\Models\User::calculateCounter($user_id)}}">

its just example, your real code might be different. For above code you need to create public static function in User model and put your code there in Model. Also you have to pass $user_id variable and recieve it in User model. Or You may use controller file to acheive, though result would be the same ($user_id needs to send).

Then, in your js file's function:

    function counter() {
      return parseInt(document.body.dataset.counter);
    }

2. Ajax request - you may have async await issue, if yes, then try to learn more about "returning response async XMLHTTPRequest". It might be tricky. In your js function:

    function counter(id){
          const xhttp = new XMLHttpRequest();
          xhttp.open("GET", `/getCounterOfUser/${id}`);
          xhttp.addEventListener('load', function (event) {
             if (event.target.responseText && event.target.status == 200) {
                 return parseInt(JSON.parse(event.target.responseText));
             } else {
                 return 0;
             }
          });
          
          xhttp.addEventListener(' error', function (event) {
             // Define what happens in case of error
          });
          xhttp.send();
    }

And you need to create new route:

Route::get('/getCounterOfUser/{id}', [App\Http\Controllers\Your_Controller::class, 'counter'])

Also you need to return JSON in your controller's function:

public function counter($id)
{
    $toSearch = $id * 10000;
    $latest = User::where('counter', '>=', $toSearch)->get()->last();
    $res = $latest->counter % $toSearch;
    return response()->json($res);
}

Upvotes: 1

Related Questions