Issue with Laravel: Fetch API does not allow updating multiple records simultaneously

Having an issue updating multiple records at once. Only the first record is getting updated while the rest are not.

Using the fetch API for AJAX calls and sending array data successfully, as confirmed in the browser's dev tools.

When attempting to save them in a foreach loop, only the first record gets updated.

In controller:

 public function approveComment(Request $request)
    {
      if ($request->ajax()) {
          $ids = $request->json()->all();
            foreach ($ids as $id) {
                $comment = Comments::find($id);
                $comment->comment_status = 1;
                $comment->save();
            }
    return response()->json("successful");
      } else {
          $comment = Comments::find($request->input('comment_id'));
          $comment->comment_status = 1;
          $comment->save();
          return back();
      }
    }

AJAX call example:

ajax.put('comments/approve',token,ids)
      .then(data => data.json())
      .then(log => console.log(log))
      .catch(err => console.log(err))

Definition of put method in AJAX class:

 async put(url, token, data) {

        const response = await fetch(url, {
            headers: {
                "Content-Type": "application/json",
                "Accept": "application/json",
                "X-Requested-With": "XMLHttpRequest",
                "X-CSRF-Token": token
            },
            method: "put",
            credentials: "same-origin",
            body: JSON.stringify(data)
        });
        return response;
    }

Answer №1

Identifying the issue;

 public function approveComment(Request $request)
    {
      if ($request->ajax()) {
          $ids = $request->json()->all();
            foreach ($ids as $id) {
                $comment = Comments::find($id);
                $comment->comment_status = 1;
                $comment->save();
   //  return response()->json("successful"); (previously located here)
            }
    return response()->json("successful"); (now correctly placed here, not inside loop)
      } else {
          $comment = Comments::find($request->input('comment_id'));
          $comment->comment_status = 1;
          $comment->save();
          return back();
      }
    }

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

Working with Thymeleaf and DatePicker to establish a minimum date

Looking to establish a minimum selectable date in my datepicker using Thymeleaf. Attempted code: <label th:utext="#{${name}}" th:for="${name}" class="control-label"></label> <div class="input-group input-group-prepend"> <span cla ...

JQuery form not triggering the submit event

Currently, I am facing some issues with my code while trying to trigger on submit event on a form and validate it. The main problems I encountered are that the onsubmit event is not being triggered, and the input field of type email is not validated proper ...

What is the best method for incorporating jQuery code into a separate file within a WordPress theme?

I'm fairly new to working with Javascript/jQuery, so please be patient with me. Currently, I'm in the process of creating a custom WordPress theme where I've been using jQuery to modify the main navigation menu generated in my header file ( ...

title not displaying in jquery colorbox

Struggling to showcase a link title within a colorbox using PHP. The link is added via an ajax response or php echo. PHP: echo "<a onclick=\"parent.\$.colorbox({ href:'inc/get_movie_details.php?m=". $row->XD_ID ."' , width:800 , ...

Utilizing and saving JSON data in JavaScript

I am currently working on developing a 2D, top-down RPG game inspired by Zelda for the web... My plan is to organize dialog in JSON format... Right now, I have the JSON data stored in an external JavaScript file called js/json.js: function getJson() { ...

What could be causing JavaScript fetch to only send OPTIONS requests instead of the expected calls?

I'm having an issue with my AJAX request using javascript fetch. It's only sending an OPTIONS call and not proceeding to make further calls. What's strange is that the response header seems fine, and $.ajax is working as expected. Check out ...

Is there a way I can send money to a designated user using their userID in Codeigniter?

Beginner here. I'm aiming to extract the ID of the person I am planning to transfer funds with. For instance, His userID = 4. The userID in my database's userID column should also be set to 4. Please refer to the screenshot provided below for a c ...

AJAX request: No values are being returned by $_GET

After spending hours trying to figure this out... I've been working on using AJAX to grab values from a jQuery slider within an <input> tag. The AJAX request is not failing (see code below), and when I use console.log to check the variable I&ap ...

Having trouble accessing data beyond the login page using Node/Express

Currently in an unusual situation. I am developing a backend and frontend that connects to a third-party RESTFUL API managing some hardware. The third-party API is hosted on your local system as a webserver, meaning HTTP requests are directed to "localhost ...

Attempting to access the SESSION variable before it has been defined

Currently, I am facing an issue where the SESSION variable is appearing before it has been defined. My website, Index.php, has a design with a frame. Within Index.php, there is code that looks like this: <div id='message2' onclick="closeNoti ...

Tips for making sure a header is consistently at the top of every page during printing

I need help with my website - I have a table that is quite tall and spans across multiple pages when printing. Is there a way to make the header row appear on top of each page when printing? ...

Ajax comes back with a JSON object that includes additional properties such as readyState, responseText, status, and status

When I make an ajax call to parse a JSON object, the object is retrieved perfectly. However, when I try to return the object, it adds 4 additional properties: readyState, responseText, status, and statusText to my JSON object. The JSON object that I want: ...

Connecting Node.js and Express with MySQL database

Today is my first time working with Node (Express) js, and I'm attempting to connect to a MySQL database. Here is the code snippet I found for my app.js file. app.js var express = require('express'), mysql = require('mysql'); // ...

Is there a way to exclude the element from being displayed when using ngIf in AngularJS?

Is there a way in Angular to conditionally add an element to the DOM without having it always added, even when its evaluation is false? I am looking for an alternative method to ngIf. ...

What are the semantics behind implementing Basic Authentication in AngularJS and Spring Boot?

Currently going through a tutorial that involves AngularJS and Spring Security. The AngularJS navigation controller triggers an authenticate function upon page load: var authenticate = function(credentials, callback) { var headers = credentials ? { ...

Unable to retrieve scope variable within AJAX call

I am currently in the process of running a loop function that contains an AJAX request within it. However, I am facing difficulties with the success function on the AJAX not being able to access a counter variable outside of the loop function. var upda ...

Retrieve the index from the Select element in Laravel instead of the displayed value

I have a Form::select drop down filled from database table and need to save the index in my database. This is what my view looks like: {!! Form::open(["url"=>"devices" ,"files"=>"true"]) !!} Name : {!! Form::text("device_name") !!} Category: {!! ...

Trigger an event in Vue.js 3 Composition API when a Component becomes visible

In my application, I have components that are toggled between visibility using buttons and variables like v-show="variable." These components function as separate web pages within the app, similar to browsing different pages on a website. What I& ...

Context failing to refresh value upon route changes

My current context setup is as follows: import { createContext, ReactNode, useState } from "react"; type props = { children: ReactNode; }; type GlobalContextType = { name: string; setName: (value: string) => void; }; export const Glob ...

Make ng-repeat trigger function again in data binding

I am currently utilizing the ng-repeat directive within a table to display a list of items along with their respective prices. The price is dynamically linked to itemPrice(item), which has been defined in my controller. This function calculates the price ...