Unable to send a post request via ajax in Laravel

I'm attempting to retrieve values from my table when clicked, here is the structure of my table:

@foreach($inventory as $p)
                  <?php 
                    $no++;

                    $typesql = DB::table('product_variant_pos')
                        ->where('id_product',$p->id)
                        ->select('type')
                        ->distinct()
                        ->get();
                  ?>
                    <tr >
                      <th scope="row"><?php echo $no;?></th>
                      <td style="width:100px;">
                        @if($p->featured_image != null || $p->featured_image != '')         
                          <img src="{{ 'Images/'.$p->featured_image }}" alt="{{ $p->featured_image }}" title="{{ $p->featured_image }}" width="100px">
                        @else
                          <h4>Nothing Image Upload</h4>
                        @endif                          
                      </td>
                      <td class="data-product" id="{{ $p->id }}" data-toggle="modal" data-target="#ModalProduct" >{{ $p->item_name }}</td>
                      <td>
                        @if(!is_null($typesql))
                            @foreach($typesql as $t)
                            <ul>
                            <?php 
                            $type = DB::table('product_variant_pos')
                                ->where('id_product',$p->id)
                                ->where('type',$t->type)
                                ->get();
                            ?>
                                <li>{{ $t->type }}
                                    <ul>
                                    @foreach($type as $j)
                                        <li>{{ $j->name }}</li>
                                    @endforeach
                                    </ul>
                                </li>
                            </ul>
                            @endforeach
                        @else
                        <?php 
                            $type = DB::table('product_variant_pos')
                                ->where('id_product',$p->id)
                                -&>get();
                            ?>
                                <li>{{ $t->type }}
                                    <ul>
                                    @foreach($type as $j)
                                        <li>{{ $j->name }}</li>
                                    @endforeach
                                    </ul>
                                </li>
                            </ul>
                        @endif
                      </td>
                      <td>{{ $p->category }}</td>
                      <td>{{ $p->stock }}</td>
                      <td>Rp. {{ $p->price }}</td>
                      <td>
                        <a href="product/edited/{{ $p->id }}">Edit</a>
                        |
                        <a href="product/delete/{{ $p->id }}">delete</a>
                      </td>
                    </tr>
                  @endforeach

and this is my JavaScript

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
    
    
    $('.data-product').click(function(e){
        
        var formData = {
            id: $(this).attr("id"),
        };
        
        var button_id = $(this).attr("id");
        
        $.ajax({
           type:'POST',
           url:'product/modal',
           data: formData,
           headers: {
                  'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
           },
           success:function(data) {
              $("#ModalProductTitle").html(data);
           },
           error: function (data) {
              console.log(data);
           }
        }); 
    });
    
} );
</script>

this script make value

The post method is not supported for this route.

I have tried similar code for another question but it did not work. I am working with the latest version of Laravel and PHP. I believe the issue may be related to CSRF() not being detected in my code, but I am unsure where I went wrong. Can anyone assist me in resolving this issue? Thank you!

Answer №1

Two options are available, please select one

  1. Update the route type to POST to match your AJAX type as POST
    Route::post('/product/modal', 'ProductController@Modal');
  2. Alternatively, update your AJAX type to GET since the route's type is GET

$.ajax({
    type:'GET',
    url:'/product/modal',
    data: formData,
    headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    },
    success:function(data) {
        $("#ModalProductTitle").html(data);
    },
    error: function (data) {
        console.log(data);
    }
});

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

Navigate through the router using query parameters in Angular 5

Encountering an issue with routing to a route containing query params. Here is the function in question: goToLink(link) { this.router.navigate([`${link.split('?')[0]}`, { queryParams: this.sortParams(link)}]); } Additionally, there is anoth ...

I prefer to keep PHP fatal errors hidden as they can interfere with the integrity of my JSON data

Whenever I make an AJAX call to a PHP script that outputs JSON, fatal errors in the PHP code ruin my beautifully formatted JSON output. The JSON string ends up being prefixed with ↵Fatal error: Call to undefined function iDontExist() in /path/to/place/w ...

MS Edge modifies the attribute's empty value to 1

I have written a JavaScript code to extract values from a list, but in the Windows Edge browser, it returns a value of 1 even when the actual value of the <li> tag is blank. For example: HTML Code <ul> <li value="">Test 1</li&g ...

The proper way to incorporate HTML within JSON in Django Templates for safe usage

What is the best way to securely display JSON data in a Django web application? In my Django server, I create JSON data and then display it in a Django template. Sometimes, this JSON data contains snippets of HTML. While this usually works fine, if the &l ...

What is the best method for effectively organizing and storing DOM elements alongside their related objects?

In order to efficiently handle key input events for multiple textareas on the page, I have decided to create a TextareaState object to cache information related to each textarea. This includes data such as whether changes have been made and the previous co ...

Code snippet for using Ajax with the Select Box onchange event

In my form, I have a select box with menu options (id, name) and another select box for categories (cid, cname). The category select box should only display categories based on the menu selected by setting the menu id to "url". Check out my code snippet ...

Alter regular expression matches within the new string replacement

I am having an issue with using regex to extract URLs from a text and then modifying all the matches within the replacement string using a function. Below is a simplified example of what I am trying to accomplish. Is it possible to achieve something lik ...

Just one piece of information was successfully added to the food ordering system database

As a beginner in using Ajax with PHP, I am seeking assistance. My issue revolves around a table called "table_menu" consisting of 5 columns: table_menu: menu_id menu_foodname menu_price menu_quantity menu_image In each of these columns, there ...

Unable to successfully import data from vue using vue-chartjs

Encountering an error in my Vue 2 project after compilation: Failed to compile. ./node_modules/vue-chartjs/dist/index.js 85:11-26 "export 'defineComponent' was not found in 'vue' The specific line in the above file triggering thi ...

Having trouble importing Material UI and working with ClickAwayListener

For my current project, I am utilizing material-ui to implement the functionality for changing passwords. In this root file, I am importing several child components: Personalize.js import React, { useContext, useState } from 'react'; import Cook ...

Managing messaging broadcasts for messenger bots by creating and retrieving unique identifiers

As a beginner using a starter project from glitch, I have a project set up at this link: I need help understanding how to obtain the message_broadcast_id and how to create it. This is how I usually create a normal message: function callSendAPI(messageDa ...

Images are not loading in NextJs image component on a Digital Ocean deployed application

I recently encountered an issue with my NextJs project. While using the NextJs Image Component for images, everything worked perfectly fine when running locally. However, after deploying the project on Digital Ocean, all the images served through the Next- ...

The issue of "google not being defined" is commonly encountered in an Angular Project when trying

I am utilizing Google Charts in my Angular project and I am looking to format the values in my chart. I came across this helpful documentation that explains formatters: https://github.com/FERNman/angular-google-charts#formatters Here is a snippet of my co ...

Error Message: Google Sheets Script encountered an issue while trying to align the cell content to the center using `

I seem to be encountering an issue with this particular script where it consistently generates the error mentioned in the title. Title: cell.setHorizontalAlignment(SpreadsheetApp.HorizontalAlignment.CENTER) function CustomFont() { // var spreadsheet ...

Ways to display the result in a new tab

I am using colorbox with a form that will be submitted to another website. I would like for the response from that web page to load in a new tab with a new URL. ...

Setting the color of an element using CSS based on another element's style

I currently have several html elements embedded within my webpage, such as: <section id="top-bar"> <!-- html content --> </section> <section id="header"> <!-- html content --> </section> <div id="left"> &l ...

Extract data from dynamically loaded tables using PhantomJS and Selenium Webdriver

I've been informed by everyone that I should be able to retrieve the table content using PhantomJS when working with JavaScript. However, despite my attempts, I have not been successful. My expectation was to obtain the table from the website Page 1 ...

Ensuring the presence of a key is essential when validating an array in Laravel. If the key is removed, the validation will

My controller receives an items array in JSON format under the items form key. [{ "sku": "w-hook-as1", "qty": 2, "cost_ex_tax": "34.22", "tax_rate": "0.2" }] Before processing, the JSON is decoded into an array: $request->merge([&apos ...

Encountered an error when attempting to use 'appendChild' on 'Node': the first parameter is not the correct type. It was able to work with some elements, but not with others

I'm currently working on a script that utilizes fetch to retrieve an external HTML file. The goal is to perform some operations to create two HTMLCollections and then iterate over them to display a div containing one element from each collection. Here ...

Obtain SVG icons seamlessly in Next.js

My goal was to dynamically retrieve SVG icons, and I discovered a method to achieve this. However, it seems like I have made some errors along the way. Can you point out where I am going wrong? Icon.js import React from "react"; import { ReactCo ...