Error encountered during the execution of the store method in Ajax CRUD operation

Greetings, I'm encountering an error in my AJAX code every time I try to execute the store function https://i.sstatic.net/SW86I.jpg

Below is my controller:

public function store_batch(Request $request)
{
    $rules = array(
        'batch_name'=>'required:max:20|unique:batches,batch_name',

      );
    $validator = Validator::make ( Input::all(), $rules);
    if ($validator->fails()){
       return Response::json(array('errors'=> $validator->getMessageBag()->toarray()));
    } else {
        $batchs= new Batch();
        $batchs->batch_name=$request->input('batch_name');
        $batchs->save();

        return response()->json($batchs);
     }

}

Here is my view:

<div class="form-group row add">
   <div class="col-md-8">
      <input type="text" class="form-control" id="batch_name" name="batch_name"
         placeholder="Enter some name" required>
      <p class="error text-center alert alert-danger" hidden></p>
   </div>
   <div class="col-md-4">
      <button class="btn btn-primary" type="submit" id="add">
      <span class="glyphicon glyphicon-plus"></span> ADD
      </button>
   </div>
</div>
{{csrf_field()}}
<div class="table-responsive text-center">
   <table class="table table-borderless" id="table">
      <thead>
         <tr>
            <th class="text-center">#</th>
            <th class="text-center">Name</th>
            <th class="text-center">Actions</th>
         </tr>
      </thead>
      @foreach($batchs as $batch)
      <tr class="batch{{$batch->id}}">
         <td>{{$batch->id}}</td>
         <td>{{$batch->batch_name}}</td>
         <td><button class="edit-modal btn btn-info" data-id="{{$batch->id}}"
            data-name="{{$batch->batch_name}}">
            <span class="glyphicon glyphicon-edit"></span> Edit
            </button>
            <button class="delete-modal btn btn-danger"
               data-id="{{$batch->id}}" data-name="{{$batch->batch_name}}">
            <span class="glyphicon glyphicon-trash"></span> Delete
            </button>
         </td>
      </tr>
      @endforeach
   </table>
</div>
</div>
</div>

This is my JavaScript code:

<script>
    $(document).ready(function() {
    $(document).on('click', '.edit-modal', function() {
        $('#footer_action_button').text("Update");
        $('#footer_action_button').addClass('glyphicon-check');
        $('#footer_action_button').removeClass('glyphicon-trash');
        $('.actionBtn').addClass('btn-success');
        $('.actionBtn').removeClass('btn-danger');
        $('.actionBtn').addClass('edit');
        $('.modal-title').text('Edit');
        $('.deleteContent').hide();
        $('.form-horizontal').show();
        $('#fid').val($(this).data('id'));
        $('#n').val($(this).data('name'));
        $('#myModal').modal('show');
    });
    $(document).on('click', '.delete-modal', function() {
        $('#footer_action_button').text(" Delete");
        $('#footer_action_button').removeClass('glyphicon-check');
        $('#footer_action_button').addClass('glyphicon-trash');
        $('.actionBtn').removeClass('btn-success');
        $('.actionBtn').addClass('btn-danger');
        $('.actionBtn').addClass('delete');
        $('.modal-title').text('Delete');
        $('.did').text($(this).data('id'));
        $('.deleteContent').show();
        $('.form-horizontal').hide();
        $('.dname').html($(this).data('batch_name'));
        $('#myModal').modal('show');
    });

    $('.modal-footer').on('click', '.edit', function() {

        $.ajax({
            type: 'post',
            url: '/setup/batch/edit',
            data: {
                '_token': $('input[name=_token]').val(),
                'id': $("#fid").val(),
                'batch_name': $('#n').val()
            },
            success: function(data) {
                $('.item' + data.id).replaceWith("<tr class='item" + data.id + "'><td>" + data.id + "</td><td>" + data.batch_name + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-name='" + data.batch_name + "'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-name='" + data.batch_name + "' ><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
            }
        });
    });
    $("#add").click(function() {

        $.ajax({
            type: 'post',
            url: '/setup/store',
            data: {
                '_token': $('input[name=_token]').val(),
                'batch_name': $('input[name=batch_name]').val()
            },
            success: function(data) {
                if ((data.errors)){
                  $('.error').removeClass('hidden');
                    $('.error').text(data.errors.batch_name);
                }
                else {
                    $('.error').addClass('hidden');
                    $('#table').append("<tr class='item" + data.id + "'><td>" + data.id + "</td><td>" + data.batch_name + "</td><td><button class='edit-modal btn btn-info' data-id='" + data.id + "' data-name='" + data.batch_name + "'><span class='glyphicon glyphicon-edit'></span> Edit</button> <button class='delete-modal btn btn-danger' data-id='" + data.id + "' data-name='" + data.batch_name + "'><span class='glyphicon glyphicon-trash'></span> Delete</button></td></tr>");
                }
            },

        });
        $('#name').val('');
    });
    $('.modal-footer').on('click', '.delete', function() {
        $.ajax({
            type: 'post',
            url: '/demo/delete',
            data: {
                '_token': $('input[name=_token]').val(),
                'id': $('.did').text()
            },
            success: function(data) {
                $('.item' + $('.did').text()).remove();
            }
        });
    });
});

</script>

Answer №1

One potential cause for this issue could be if the correct Route has not been defined.

Another possibility is that you are trying to access the get route using a post request. Additionally, make sure to verify both the URL and Method.

You may also want to inspect the Network Tab in your browser's developer tools for further insights.

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

Fill the drop-down menu with the present day's date, month, and year

I'm new to this, so please bear with me. I have some html and jQuery code: $(document).ready(function() { var d = new Date(); var month = d.getMonth() + 1; var year = d.getFullYear(); $("#month").val(month); $("#year").val(year) ...

Tips for automatically closing one sub menu while selecting another sub menu

I am working on a code snippet to manage the menu functionality. My goal is to ensure that when I click to open one submenu, any other currently open submenus should automatically close. ;(function($) { // Ensuring everything is loaded properly $ ...

`How can I customize the appearance of individual selected <v-list-item> across various sub-groups?`

As a newcomer to Vuetify and Vue in general, I am struggling to solve a specific issue. I need to create multiple sub-groups where only one option can be selected within each "parent" list. Consider an array of cats: options:["Crookshanks", "Garfield", " ...

MUI full screen dialog with material-table

Issue: When I click a button on my material-table, it opens a full-screen dialog. However, after closing the dialog, I am unable to interact with any other elements on the screen. The dialog's wrapper container seems to be blocking the entire screen. ...

React JS BlueprintJS Date Range Picker not functioning as expected

I am struggling to implement a DateRangePicker using BlueprintJS on my component, following the instructions in the documentation. I also want to include a RangePicker similar to the one shown in this screenshot. I have successfully installed all the nece ...

Updating parameters in Node.js with mongoose

script.js var mongoose = require('mongoose'); var Schema = mongoose.Schema; var scriptSchema = new Schema({ status: {type: String, default: 'INCOMPLETE'}, code: String, createdDate: {type: Date, default: Date.now}, user: {t ...

Using an AngularJS directive to trigger a function with ng-click

Everything is working well with my directive, but I would like to utilize it within ng-click. Unfortunately, the function inside the link is not getting triggered. Here's the link to the code snippet. <div ng-app="editer" ng-controller="myCtrl" ...

Display an icon button when a user edits the text in a text field, and make it disappear once clicked on

Figuring out how to incorporate a v-text-area with an added button (icon) that only appears when the text within the text area is edited, and disappears once it is clicked on, has proven to be quite challenging. Below is a simplified version of my code to ...

Creating Tree diagrams with pie charts using D3

Has anyone tried creating a D3 pie component within each node of a tree? I've managed to build the tree and a single pie separately, but I'm struggling to combine them. My JSON data looks like this: window.json = { "health": [{ "value" ...

What are the potential disadvantages of relocating the login logic from the 'signIn()' function in NextAuth.js?

My experience with NextAuth.js for the first time has led me to realize that signing in using the Credentials provider can be a bit tricky when it comes to error handling. It seems like the default implementation should resemble something along these lines ...

Encountering issues with formData in nextjs 13 due to incorrect data type

In my NextJS application, I am using the dataForm method to retrieve the values from a form's fields: export async function getDataForm(formData) { const bodyQuery = { ....... skip: formData.get("gridSkip") ...

The submission of the Jquery form is not successful

I am struggling with a form on my page. I want to disable the submit button and display a custom message when submitted, then use jQuery to actually submit the form. <form> <input type="text" name="run"/> <input type=&quo ...

Include an Open OnClick event in the React/JSX script

We have a dynamic menu created using JavaScript (React/JSX) that opens on hover due to styling. My inquiries are: Instead of relying on CSS for the hover effect, where in the code can I implement an OnClick event to trigger the menu opening using Java ...

Turning JSON data into an array format, omitting the keys

Can someone help me with a query that will retrieve a specific column from the database and return it in this format: [ { "tenantName": "H&M" }, { "tenantName": "McDonalds" } ] I would like to transform ...

Is it considered acceptable to modify classes in a stateless React component by adding or removing them?

My stateless component functions as an accordion. When the container div is clicked, I toggle a couple of CSS classes on some child components. Is it acceptable to directly change the classes in the DOM, or should I convert this stateless component to a ...

NPM issue: unable to locate module 'internal/fs' in Node.js

Encountering NPM error after updating to Node version 7.x. npm is now non-functional and the cause remains unidentified. Possible reason for the issue could be - npm ERR! Cannot find module 'internal/fs'. The output generated when execu ...

AngularJS Service Implementing the Pub/Sub Design Pattern

I've been browsing for solutions to a problem and stumbled upon an answer provided by Mark Rajcok angular JS - communicate between non-dependend services However, I am struggling to fully grasp his explanation, particularly this part: angular.forEa ...

zingcharts with multiple lines on x axis representing time

I am facing a rather interesting challenge with plotting data. I want to create a chart where time is the x-axis scale and multiple lines are plotted, each with varying time intervals between data points. While zingcharts has provided documentation on gene ...

Locating elements with Selenium Webdriver using xpath

<a style="color:White;" href="javascript:__doPostBack('dnn$ctr674$Case$gvCaseSearchDetails','Page$777')">777</a> Can anyone help with writing an xpath for the HTML code above? The goal is to locate elements using the identi ...

Is it possible to include a border/stroke on a Raphael picture?

Currently, I am attempting to enhance a Raphael image element by adding either a border, stroke, or drop shadow. My end goal is to create an animated glowing border effect. Previously, I successfully implemented this on traditional HTML elements using Java ...