Isolating JavaScript Ajax codes in a Laravel 8 js file results in functionality issues

Having recently delved into the world of Ajax, I've encountered some issues. Allow me to do my best in explaining the problem at hand.

  • Currently, I'm engaged in a Laravel 8 project.
  • In this project, users are given the choice to select an image, with CropperJS handling this functionality.
  • Everything functions smoothly until I try separating the JavaScript and Ajax codes into distinct files, at which point I encounter an error message stating: "The POST method is not supported for this route. Supported methods: GET, HEAD, PATCH." How can I ensure that the Ajax call works seamlessly in separate files?

Routes

Route::get('/image/create', 'ProfileImage\CreateController@create')->name('image.create');
Route::post('/image/store', 'ProfileImage\StoreController@store')->name('image.store');

Controller

public function create()
    {
        return view('pages.image.create');
    }


public function store(StoreProfileImageRequest $request, ProfileImage $profileImage)
    {
        $profileId = auth()->user()->profile->id;
        $validated = $request->validated();
        $image = $validated['image_name'];

        $this->profileImageRepositoryInterface->storeImage($profileImage, $profileId, $image, $validated);


        session()->flash('success', 'Uw afbeelding is succesvol opgeslagen.');

        return response()->json(
            [
                'status' => 'success',
                'message' => 'my message.',
                'url' => route('profile.index')
            ]);   
    }

Form

<form class="text-left"
                              data-form-output="form-output-global"
                              data-form-type="contact"
                              method="post"
                              enctype="multipart/form-data"
                        >
                            @csrf

                            <div class="member-block-body">
                                <label for="upload_image">
                                    
                                </label>
                                <input type="file" name="image_name" class="image" id="upload_image">
                            </div>

                            <span class="invalid-feedback ct_invalid_feedback" role="alert"gt;
                                <strong id="ajax_image_error"></strong>
                            </span>
                        </form>

Modal

<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalImageCropper" aria-hidden="true">
    <div class="modal-dialog ct_modal_lg modal-dialog-centered" role="document"gt;
        <div class="modal-content"gt;
            <div class="modal-header"gt;
                <h5 class="modal-title"gt;
                    @lang('Afbeelding aanpassen voordat u deze uploadt.')
                </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"gt;
                    <span aria-hidden="true">
                        x
                    </span>
                </button>
            </div>
            <div class="modal-body"gt;
                <div class="ct_img_container"gt;
                    <div class="row"gt;
                        <div class="col-md-8"gt;
                            <img src="" id="sample_image" alt="">
                        </div>
                        <div class="col-md-4"gt;
                            <div class="ct_cropper_image_preview"gt;</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="modal-footer"gt;
                <button type="button" id="crop-image" class="btn btn-primary"gt;
                    @lang('Opslaan')
                </button>
                <button type="button" class="btn btn-secondary" data-dismiss="modal"gt;
                    @lang('Annuleren")
                </button"gt;
            </div"gt;
        </div"gt;
    </div"gt;
</div"gt;

Javascript custom_function.js

$(document).ready(function () {
    let $modal = $('#modal');
    let image = document.getElementById('sample_image');
    let cropper;

    $('#upload_image').change(function (event) {
        let files = event.target.files;
        let done = function (url) {
            image.src = url;
            $modal.modal('show');
        };

        if (files && files.length > 0) {
            reader = new FileReader();
            reader.onload = function (event) {
                done(reader.result);
            };
            reader.readAsDataURL(files[0]);
        }
    });

    $modal.on('shown.bs.modal', function () {
        cropper = new Cropper(image, {
            aspectRatio: 1,
            viewMode: 3,
            preview: '.ct_cropper_image_preview'
        });
    }).on('hidden.bs.modal', function () {
        cropper.destroy();
        cropper = null;
    });

    $('#crop-image').click(function () {

        $('#ajax_image_error').text('');

        canvas = cropper.getCroppedCanvas({
            width: 600,
            height: 600
        });

        canvas.toBlob(function (blob) {
            url = URL.createObjectURL(blob);
            let reader = new FileReader();
            reader.readAsDataURL(blob);
            reader.onloadend = function () {
                let base64data = reader.result;
                $.ajax({
                    url: '{{ route("image.store") }}',
                    method: 'POST',
                    data: {
                        '_token': '{{ csrf_token() }}',
                        image_name: base64data
                    },
                    success: function (data) {
                        if (data.status === 'success') {
                            window.location = data.url;
                            $modal.modal('hide');
                            $('#image-preview').attr('src', base64data);
                        }
                    },
                    error: function (data) {
                        if (data.status === 422) {
                            let response = $.parseJSON(data.responseText);
                            $.each(response.errors, function (key, val) {
                                $('#' + 'ajax_' + key + '_error').text(val[0]);
                            });
                        }
                    }
                });
            };
        });
    });
});

https://i.sstatic.net/8U54t.png

Answer №1

Thank you for the helpful suggestions. I was able to resolve the issue.

$.ajax({
                    url: '/image/store',
                    // url: '{{ route("image.store") }}',
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                    },
                    data: {
                        // '_token': '{{ csrf_token() }}',
                        image_name: base64data
                    },
                    success: function (data) {
                        if (data.status === 'success') {
                            window.location = data.url;
                            $modal.modal('hide');
                            $("#image-preview").attr("src", base64data);
                        }
                    },
                    error: function (data) {
                        if (data.status === 422) {
                            let response = $.parseJSON(data.responseText);
                            $.each(response.errors, function (key, val) {
                                $("#" + "ajax_" + key + "_error").text(val[0]);
                            });
                        }
                    }
                });

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

Displaying HTML Tags in jQuery JSON Response

Whenever I execute the following code: <html> <head> </head> <body> <?php $value = isset($_GET['send_request']) ? $_GET['send_request'] : false ; if ($value) { echo $value; return ...

Incorporating an Angular 2 Directive within the body tag of an

My goal is to create a custom directive that can dynamically add or remove a class from the body element in HTML. The directive needs to be controlled by a service, as I want to manage the visibility of the class from various components. Question: How ca ...

Adjust the size of the logo as the user scrolls

Currently, I am implementing a JavaScript feature that allows my logo to shrink when the user scrolls down and grow when they scroll up. To achieve this effect, I am utilizing the jQuery functions addClass and removeClass. However, I have encountered som ...

Trigger ng-click after ng-model updates

Is there a way to create an ng-click function that will only execute after the value of the ng-model in a scope variable changes? In my scenario, I have a list of analysis objects within a list called analyses, each with an include boolean attribute used f ...

Experiencing an infinite loop due to excessive re-renders in

I'm receiving an error and unsure of the reason. My goal is to create a button that changes colors on hover. If you have a solution or alternative approach, please share! import React, {useState} from 'react' function Login() { const ...

Exploration of undefined issues in Jquery, Ajax, and JSON parsing

Why am I having trouble accessing field.set_url? http://jsfiddle.net/W4xBJ/ $(document).ready(function(){ $("button").click(function(){ $.getJSON("https://api.deckbrew.com/mtg/cards?color=red&color=blue&rarity=rare&name=fire",function(r ...

problem with transmitting information through $.ajax

I'm facing a frustrating issue with the $.ajax()... function in my PHP code. I am unable to retrieve the data sent by the ajax request. <?php if ($_POST){ include 'Bdd_connexion.php'; $filiere = $_POST['filiere']; ...

Cease the continuous scrolling of the display element now

I'm having trouble with my progressbar animation when scrolling. It seems to run multiple times instead of just once. I apologize if there's an error in my code. Could someone please assist me? This is the code I am using: <div class="demo- ...

Guide to include particular data from 2 JSON objects into a freshly created JSON object

I have extracted the frequency of countries appearing in an object (displayed at the bottom). The challenge I am facing is that I require geocode information to associate with country names and their frequencies, so that I can accurately plot the results o ...

Performing a jQuery GET request using an AJAX call to retrieve data from

I have a situation where I am using jQuery's $.get() method to fetch data from an external PHP file. The issue I am facing is that when refreshing two external files, the HTML for the second file (messages.php) refreshes and then refreshes again 300ms ...

Is there a comparable solution like Fabric in Javascript or Node.js?

One thing that I really appreciate about Fabric is how it simplifies the deployment process to multiple servers, especially with its strong support for SSH. But since our project is based on node.js, it would be ideal if we could achieve a similar function ...

How can I receive a response from node.js-express and send it back to AJAX?

Although I am comfortable in PHP, I decided to learn node.js in order to enhance the efficiency of my chat application. As a beginner in node.js, I am currently facing a specific issue. My goal is to send a request to node.js from AJAX using jQuery and re ...

I receive an [object HTMLCollection] as the output

I am currently working on recreating a login page and I want it so that when the button is clicked, it displays the name you entered, but instead, it returns [object HTMLCollection]. My expectation was to have the name displayed as entered. var nombre ...

Choose all the checkboxes that use Knockout JS

Struggling with implementing a "select all" checkbox feature as a Junior developer on a complex project utilizing knockout.Js and Typescript. I can't seem to figure out how to select all existing checkboxes. Here is the HTML: <td> <inp ...

if considering an integer value of 0 as equivalent to null

I am struggling with using axios to send data to an API in react. Despite the server successfully receiving the values, my code is not entering the if block as expected. Interestingly, when I make the same request from a rest client, it works perfectly. He ...

Is there a way to modify a specific key value in all embedded objects using Mongoose?

I'm currently working on a chat application and I'm facing a challenge with implementing the 'seen' functionality. I need to update all chat messages in the database by setting the 'seen' column to true. Here is the schema st ...

Modifying information in a single array in Vue JS has a ripple effect on

I'm really struggling to understand what the ... want with this Vue component! Can someone please help me out? Here is my code: var groupadding = new Vue({ el: '#groupAdd', data:{ currentFullData: [], localData: [] }, method ...

Unable to Trigger Virtual Click Event on Calendar in JavaScript

My workplace utilizes a custom web application with a date picker/calendar that I am attempting to modify programmatically. The app is built in Vue, which has added complexity to my task. Despite exhaustive efforts, I have been unable to select or inject d ...

I'm sorry, but we were unable to locate the /bin/sh

After running a command using execSync that runs with sh, I observed the following: spawnSync /bin/sh ENOENT bin is now included in the PATH environment variable. Any ideas on this issue? ...

Error: React cannot render objects as children

I am encountering an error that I cannot seem to figure out. The issue seems to be with the following line of code: <p className="bold blue padding-left-30">{question}</p> Specifically, it does not like the usage of {question} in the above pa ...