What is the method for sending data to routes in vue.js 2 using the get method?

Here is the code snippet for my ajax request:

<script>
    new Vue({
        ...
        methods: {
            fetchItems: function (page) {
                var data = {page: page};
                this.$http.get('api/items', data).then(function (response) {
                    console.log(JSON.stringify(response))
                    this.$set(this, 'items', response.data.data.data);
                    this.$set(this, 'pagination', response.data.pagination);
                }, function (error) {
                    // handle error
                });
            },
            ...
        }
    });
</script>

My routes for the API are defined as follows:

Route::get('/api/items/', function () {
    dd(Input::get('page'));
    $results =  \App\Post::latest()->paginate(7);

    $response = [
        'pagination' => [
            'total' => $results->total(),
            'per_page' => $results->perPage(),
            'current_page' => $results->currentPage(),
            'last_page' => $results->lastPage(),
            'from' => $results->firstItem(),
            'to' => $results->lastItem()
        ],
        'data' => $results
    ];

    return $response;
});

After execution, when I check the console, the result is null, even though I have included dd(Input::get('page'));

It should display the page that was sent.

How can I resolve this issue?

Answer №1

Consider making the following adjustment:

dd(Input::get('page'));

Change it to:

return Input::get('page');

Using the dd method will display a raw HTML output of the dumped value and stop the execution, rather than formatting it as JSON. To ensure proper JSON formatting, use the return statement instead.

Answer №2

Here is a comprehensive example showcasing Vue.js code:

let app = new Vue({
    el: '#invoice',
    data: {
        form: new FormData(),
        errors: {},
        tax: 0
    },
    methods: {
    generateRandomSerial: function () {
      this.form.serial = Math.floor(Math.random() * 1000000) + 1;
    },
    sortDataByTax: function() {
        if(this.form.tax_id) {
          let url = '{{route('invoice.get_tax', null)}}';
          this.$http.get(url)
           .then(function(response){
              if(response.data) {
                  console.log(response.data)
              }
           });
        }
     }
 })

Below is the defined route:

Route::get('/fetch_tax/{tax_id}', function($tax_id)
{
    $tax = App\Tax::findOrFail($tax_id);
    if ($tax) {
        return response()
            ->json([
                'rate' => $tax->rate,
                'type' => $tax->type
            ], 200);
    } else {
        return response()
            ->json([
                'rate' => 0,
                'type' => 1
            ], 200);
    }
})->name('invoice.get_tax');

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Combining meshes in Three.js while preserving individual materials

I've been tackling a visualization project on a web server, and while I've achieved the desired look and functionality, the performance is not up to par. The project involves a large grid that models a space, with individual cubes displayed in di ...

Arrange objects in an array according to the order specified in another array

Here is my array of car makes: const makes = [ {id: "4", name: "Audi"}, {id: "5", name: "Bmw"}, {id: "6", name: "Porsche"}, {id: "31", name: "Seat"}, {id: "32", name: "Skoda"}, {id: "36", name: "Toyota"}, {id: "38", name: "Volkswagen"} ] Now, I want to o ...

Does Nativescript have a feature similar to "Hydration"?

It's been said that Phonegap offers an exciting feature called Hydration, which can lead to rapid and efficient deployments when combined with CD. Is it feasible to incorporate this concept into a Nativescript application? While I may not be well-ve ...

Expanding the Number of Arguments Sent to a Callback Function

I have a scenario where I am using a method that sends a POST request and then triggers a specific callback function to manage the response: myService.verify(id, verificationCallback); function verificationCallback(err, response) { ... } My query is two ...

The jQuery function for $(window).scroll is not functioning as expected

My challenge is getting the scroll to reveal my scrollTop value I've been working with this code: $(document).ready(function(){ console.log('Hello!'); $(window).scroll(function(){ console.log('Scrolling...'); var wScroll = ...

Encountering a post route error when utilizing async await has hindered my ability to add a new product

Recently, I attempted to update my post route using async await, and unfortunately made some mistakes. Now I'm unsure how to correct it properly. router.post('/', async (req, res, next)=> { try{ const updatedProduct = await ...

Vue.js <v-data-table> - Automatic sorting/ custom sorting options

I am trying to arrange the numerical data in a Vue.js data-table in descending order right from the start. I want it to look like the screenshot provided below. Screenshot of My Desired Result The data that needs to be arranged in descending order is the ...

Employ ImageMagic in a synchronous manner

Consider utilizing imagemagick Required to use imagemagick in a synchronous manner. Meaning the following code should execute only after the image conversion is complete (regardless of any errors). The only solution I can see involves using deasync: co ...

Validation of forms - Must include one particular word from a given set

I am in the process of utilizing Javascript to validate an input field with the specific formatting requirements outlined below: "WORD1,WORD2" The input must contain a comma separating two words, without any spaces. The first word (WORD1) can be any word ...

Is there a way for me to calculate the square of a number generated by a function?

Just starting out with Javascript and coding, I'm having trouble squaring a number that comes from a function. I've outlined below what I am trying to achieve. Thank you in advance for your help. // CONVERT BINARY TO DECIMAL // (100110)2 > ( ...

Insert Angular HTML tag into TypeScript

I am currently working on creating my own text editor, but I'm facing an issue. When I apply the bold style, all of the text becomes bold. How can I make it so that only the text I select becomes bold without affecting the rest of the text? Additional ...

jQuery breaks when working with ASP.NET forms

Essentially, it appears that using an ASP.NET page with the <form runat=server> tag can cause some jQuery scripts to break. To illustrate this issue, consider the following scenario: You have a simple webpage with only a checkbox, like so: <inpu ...

The CSS and JS codes are not successfully integrating into the webpage

I am encountering an issue with loading CSS and JS files onto my page. My project involves PHP and Xampp. The file structure is as follows: My Site - CSS - index.css - JS - index.js - Index.php (Apologies for the lack of a folder tre ...

I'm not entirely sure why I keep getting the error message stating "Cannot read property 'innerHTML' of null"

Having an issue with my JavaScript code where I am trying to insert a new table row into the HTML but keep getting an error message that says "Uncaught TypeError: Cannot read property 'innerHTML' of null" <!DOCTYPE html> <html lang=" ...

Take action upon being added to a collection or being observed

Consider the following scenario: I have an array called "x" and an Observable created from this array (arrObs). There is a button on the page, and when a user clicks on it, a random number is added to the array. The goal is to display the newly added value ...

How can I place an Object in front of an Array in JavaScript?

Currently, I am working on an Angular project where I need to modify a JSON array in order to display it as a tree structure. To achieve this, the objects in the array must be nested within another object. Desired format / output: this.nodes = [ { id ...

Tips for including a JSON file within the utils directory of a Node.js project

I have a JavaScript file located in the utils folder of my Node.js project. This JS file is responsible for retrieving data from a database. However, at the moment, I only have mock data stored in a local JSON file. Now, I need to figure out how to load th ...

"Learn the process of integrating Javascript files from the Angular assets folder into a specific Angular component or module (such as Angular 2, 4,

I have custom1.js, custom2.js, and custom3.js JavaScript files that I need to load into Angular components component1, component2, and component3 respectively. Instead of adding these files to the index.html globally, I want to load them specifically for e ...

In what way can I ensure that the value of currentIndex is consistently set to 0 before each calculation?

Is there a way to set the Value of currentIndex to always be 0? The calculation of (CRANK1 + CRANK2) + (DRANK1 + DRANK2) should result in (0 + selected amount), but it is currently calculating as (selected amount + selected amount). Any assistance would ...

Updating a class within an AngularJS directive: A step-by-step guide

Is there a way to change the class (inside directive) upon clicking the directive element? The current code I have updates scope.myattr in the console but not reflected in the template or view: <test order="A">Test</test> .directive("test", ...