Having trouble accessing variables using the put method in Laravel with XMLHttpRequest

I am struggling to save my image data using XMLHttpRequest. Although I can send json data and see them in the developer console, I am unable to access them on the server side as the $request appears to be null.

Below are snippets of my JavaScript code:

 document.querySelectorAll('.galeri-cart').forEach(function (image) {
    image.addEventListener('click',function () {

// update stuff

document.getElementById('submit_button').addEventListener('click',function () {
      let xhr = new XMLHttpRequest(),
          token = document.head.querySelector("[name=csrf-token]").content;
      xhr.open('PUT','images/update/'+id,false);
      xhr.setRequestHeader('X-CSRF-TOKEN',token);
      xhr.onload = function () {
             swal("Updated successfully", {
                  icon: "success",
                    });

                   };
     let data = {};
         data.alt = altInput.value;
         data.url = urlInput.value;

     xhr.send(JSON.stringify(data))
              })
         })
     });

And here is a snippet from my controller:

public function updateMedia(Request $request, $id) {
   $image = Media::find($id);
   $image->image_alt_name = $request->input('alt');
   $image->image_path = $request->input('url');
   $image->save();

   return json_endcode($request);
    }

This is how the route looks like (under the images prefix):

Route::put('update/{id}',['as'=>'media.update','uses'=>'MediaController@updateMedia']);

Can you provide any advice or point out what might be going wrong? I appreciate your help.

Answer №1

There is a mismatch between the URL used in the AJAX request and the one defined in the Laravel route.

AJAX ---> "api/data/update/"
Laravel Route ---> "data/update/"

Answer №2

  xhr.open('PUT','images/update/'+id,false);

The URL specified includes the directory `images`, however, your 'web.php' file does not show this directory in the path. Please make sure to adjust the URL accordingly.

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

Having trouble accessing the initial two elements of an array while generating a Fibonacci series in JavaScript

Attempting to generate a Fibonacci sequence that always starts with [0, 1] using basic JS has proven challenging. The current implementation of the function does not properly return the first two items in an array when calling the corresponding n number. F ...

Item 'unreachable' displayed in Firefox console

I am working with several divs that have the class='class_name'. I have also defined var A = document.getElementsByClassName('class_name'); console.log(A[0]); Upon checking in the Chrome console, it displays: <div class="class_n ...

Update the Laravel timestamp setting to automatically default to one year in the future

Many discussions have focused on setting the default value of a timestamp column to the current datetime using CURRENT_TIMESTAMP. However, my query is about how to set the default to the CURRENT_TIMESTAMP + 1 year. I attempted the following code but encou ...

Implementing Axios interceptor is a common practice in Vue.js applications to central

Hello everyone, I'm facing a problem with the interceptor in VueJS. I can't seem to figure out where the issue lies and it's driving me crazy... I've gone through various tutorials and read numerous posts on stackoverflow, but everythi ...

Troubleshooting Problems with Retrieving Data Using jQuery and

Having trouble fetching information from a JSON file, as the data variable is empty. I have already downloaded the JSON file, so it's not an issue with the server connection. Can anyone point out where I might be going wrong? function handle_geolocat ...

Switch the checked status of an input dynamically using jQuery function

It seems like I might be overlooking something quite obvious, but I can't figure out why this jquery function is behaving inconsistently. HTML: <label id="income_this_tax_year"> <div class="left"> <p>Have you had Self-Employm ...

Accessing cell values within a table using JavaScript

I am having some trouble with extracting unique IDs from the input text areas in the first column of an HTML table. These IDs are dynamically assigned using JavaScript. Can someone help me with this issue? Below is the HTML code for my table: <table id ...

Encountering a BAD REQUEST error while attempting to access the Okta API from a C# MVC application

I have been experimenting with creating a sample application using the Okta platform to generate users. Despite making API calls, I consistently encounter a "BAD REQUEST" response when running my C# MVC application on Visual Studio 2013 update 5 towards my ...

Change the div attribute when clicking on a corresponding link

For the full code, please visit: https://plnkr.co/edit/6TTLVcsXLV7C1qXSMQV0?p=preview Here is an angular ui bootstrap accordion with nested panels: <uib-accordion close-others="oneAtATime"> <div ng-repeat="sub in subdivisions"> < ...

What might prevent an onSubmit event from triggering the execution of "checkTheForm()"?

Despite consuming a substantial amount of information on the internet, I still find myself puzzled by why my code isn't functioning as expected. I acknowledge that there are numerous tutorials out there guiding me to use <form action="index.html" o ...

When integrating AngularJS $http with WordPress, the desired response may not always be achieved

I recently implemented a wp_localize_script for ajax in my WordPress project: wp_localize_script('cb_admin_js', 'cbAjax', array('ajax_url' => admin_url( 'admin-ajax.php' ))); As part of testing, I used an $http. ...

Infinite Scrolling in React: Troubleshooting Issues with the dataLength Parameter

A function called newsFeed is utilized within the useEffect hook to make a request to an endpoint for fetching posts made by the logged in user and users they follow. The retrieved data is then saved to the state: const [posts, setPosts] = useState([]) con ...

How can I sort by the complete timestamp when using the Antd table for dates?

I have an item in my possession. const data: Item[] = [ { key: 1, name: 'John Brown', date: moment('10-10-2019').format('L'), address: 'New York No. 1 Lake Park', }, { ...

Looking to include a data-* attribute within a div element for the utilization of a third-party JavaScript library like React or Next.js?

let speed = '{ "speed": 0.2 }'; <div className="section jarallax h-100vh" data-jarallax={speed} style={{backgroundImage: "url('/images/header-bg.jpg')"}} id="home"> </div> <Script src="./js/parallax.js" strate ...

The "Key" function from Object.keys does not yield true when compared to an identical string

Object.keys(data).forEach((key) => { bannerData[key] = data[key][0]; console.log(key); if (key == "timestamp") { labels.push(data[key]); console.log("wtf"); console.log(labels); ...

Dynamic Filtering with jQuery List

I'm attempting to create a dynamic filter list on keypress event. For example, if I type "It" into the input field, the elements that do not match this value will be hidden. I'm unsure if the code structure I have implemented below effectively ac ...

Display Issue with Header Row in React Data Table Component - Full Text Not Visible

Hey there! I've been working with a neat npm package called react-data-table-component. However, I've run into a bit of trouble trying to adjust the width of the table header text. Take a look at the issue here: https://i.sstatic.net/AzqNw.png ...

The image is being loaded onto the canvas and is being resized

Currently, I am facing an issue with loading images into a canvas element as the image seems to be scaled in some way. To provide some context, I have multiple canvases on my webpage and I want to load images into them. Since the dimensions of the canvas ...

Mastering the art of implementing dynamic template variables in TinyMCE

After exploring the 'full' example and conducting research on the Wiki and moxie forums, I have yet to find a solution. I am attempting to implement what the wiki states is possible, but encountered an issue when replacing the 'staffid' ...

How about placing a particle on the top layer of a mesh at a random location?

I am struggling to place a particle on the top side of a custom mesh using Three.js. Most tutorials I've come across only demonstrate adding particles to cubes or spheres, leaving me with no solution for my unique shape. How can I successfully positio ...