"Troubleshooting Laravel 5: Why isn't the Ajax post Method Working in

Currently, I am diving into Ajax using JavaScript and aiming to implement an Ajax post method in Laravel 5.4. Below are the snippets from my various files...

Routes

Route::group(['prefix' => 'admin'],function(){
    Route::post('/ccat','PagesContrpllerController@ccat')->name('ccat');
    Route::resource('/products' , 'ProductController');
});     

ProductCategoryController

public function ccat(Request $request){
    return 'hello this is post method';
}

JavaScript

function sendfunc(name , level , parent){
    let xhr = new XMLHttpRequest(); 
    xhr.onreadystatechange = function(){
        if (xhr.readyState == 4 && xhr.status==200) {
             console.log(this.responseText);
         }
    }

    xhr.open("POST", "ccat", true);
    xhr.setRequestHeader("Content-type", "application/x-www-formurlencoded");
    xhr.send("fname=Henry&lname=Ford");
}

Upon running the script, I anticipate seeing 'hello this is the post method' printed in the console but instead encounter:

POST http://localhost:8000/admin/product/ccat 404 (Not Found)

Confused by this unexpected result, I tried adjusting the URL to: http://localhost:8000/admin/ccat` which unfortunately led to:

POST http://localhost:8000/admin/ccat 500 (Internal Server Error)

Your insights on resolving this issue would be greatly appreciated! Thank you for your understanding amidst any coding mishaps. :)

Answer №1

I realized my error was the absence of the csrf_token, so I made sure to include it in the header of the page by adding:

<meta name="csrf-token" content="{{ csrf_token() }}" />  

I then accessed the csrf_token in javascript and sent it to the post route using the following code:

xhr.setRequestHeader("X-CSRF-TOKEN", document.head.querySelector("[name=csrf-token]").content )
;
and it worked perfectly. Hopefully, this will be helpful for someone else.

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

Guide on looping through a collection of objects that have child objects and generating a new custom object

I am currently working with an object list retrieved from an API. The response looks something like this: { "1/22/20": { "new_daily_deaths": 0, "total_cases": 1, }, "1/23/20": { "new_deaths": 0 ...

Locate identical values in Vuejs

When working with an array of objects, I need to check if a newly inserted object is a duplicate or not. this.duplicate = false; for(let item of this.items){ if(item.id && this.item.name === item.name) { t ...

Achieving two-way data binding using a Service in AngularJS - Step by step guide

Searching a JSON file, extracting data to create a table, and continuously monitoring for updates to display in real-time is a challenging task. Despite multiple attempts with AngularJS, achieving this has been elusive. Below is the code snippet: app.js ...

Tips for transforming an array of images (from an input field) into a JSON string

After creating an array of images using var a = Array.from(document.getElementById("id").files); I tried to generate a JSON string of that array using var b = JSON.stringify(a); However, all I get is an empty array. It seems like this issue is common w ...

Adjust Scale to Less than 1 in JVectorMap

I am in the process of developing a website that includes a full-size map using JVectorMap. The map currently occupies 100% of the width and height of the page, but I would like to add a border around it when fully zoomed out. However, when the map is zoom ...

Tips on saving JSON data in Laravel's MySQL database

I've been experimenting with storing data in a database as JSON, and noticed that the built-in notification table is able to do this. I've created a field of type "text" and am storing data like this (example) {"filenames":["D0BmpFOdyUp4YyA8tqp ...

Concealing a button in Vue.js and Laravel effortlessly

I am struggling to figure out how to hide the button when there is no data in the table in my Vue.js project. Since I am new to Vue.js, I would really appreciate any help or guidance on how to achieve this. If there is another way to accomplish this, pleas ...

What is the best way to include checkbox values with various names in a URL using Javascript?

There are checkboxes with different names under various side-menus, each having the same name within its respective side-menu. For example: <?php for($i=0; $i<=5; $i++){?> <input type="checkbox" name="second[]" value="<?php echo $i + 10 ...

Iterate over the array and generate a fresh array based on its elements

Let's take a look at this example array: $array = [ 'foodTypes' => [ 'pizza' => '120', 'burger' => [ 'calorie' => '50', 'sugar' => '10&apo ...

What is the best way to ensure Leaflet-Search functionality remains active even when a layerGroup is toggled off using L.control.layers

I am encountering challenges while using the Leaflet.Control.Search plugin by Stefano Cudini in conjunction with Leaflet's built-in function L.control.layers. When all layers are active, there are no issues with locating a specific area. However, wh ...

Integrate a PHP link into a Gatsby/React project

I've been attempting to connect my contact form page, contactpage.php, with my Gatsby application. In the navigation bar (found in the Components folder), I've added the following code: <div> <a className="int_link_about" ...

I'm struggling to understand how to interpret this. The v-tab function seems to be generating a button with various properties, but I'm unsure which specific property is related to

The V-tab below generates the button known as the right one on the v-app-bar: https://i.stack.imgur.com/DzNmq.png <v-tab :to="'/demo'" active-class="text--primary" class=&quo ...

Retrieve the data sent via ajax and process it on the php page

Requesting assistance with sending three parameters: organization name, location name, and building name to AJAX. Below is the code snippet I have prepared for this purpose. The objective is to display the values passed from AJAX on the page that needs exe ...

Display a div using data from a Model in MVC

I am working with a model List that has fields ContainerId (div id) and Code (HTML code), which I am passing to a Razor View. Can you suggest the most effective way to display the code from the model in the containerId? My initial thought is to utilize j ...

Changing the width of a label in jQuery Mobile

In an effort to enhance the appearance of all label tags within a jquery mobile form, we are aiming to adjust their widths based on the largest label. Below is a code snippet illustrating this for one specific field: ... <fieldset data-role="fieldconta ...

Pause animation when hovering over their current positions

I am working on a project with two separate divs, each containing a circle and a smiley face. The innercircle1 div is currently rotating with a predefined animation. My goal is to create an effect where hovering over the innercircle1 div will pause its rot ...

Iterating over an array within an if statement to validate if all elements meet the criteria

In my code, I have a variable named 'fieldCount' and it is currently set to 5 which represents the number of fields that I have. How can I refactor the following code without explicitly mentioning each index: if ( fields[0].checkValidity() &a ...

Tips for enlarging the tree view when running protractor exams. Check out this code excerpt below:

I have a code snippet below that represents one item out of many, each distinguished by ng-reflect-index. I am trying to write a test case to expand these nodes individually using Protractor. However, I am facing an issue in expanding the node using Prot ...

Provide Chai/Mocha with a selection of essential keys that need to be incorporated

It appears that running the following code: describe( 'Add Youtube', function () { it( 'should return the video data, including user, title and content fields', function ( done ) { this.timeout( 5000 ) request({ ...

Unable to show the number of rows in node.js

I'm currently attempting to execute this snippet of code using node.js in order to display the number of tables in a postgresql database: var pg = require('pg'); var conString = "postgres://login:pwd@localhost/DB"; var client = new pg.Clie ...