In the Controller, the `getContent` function is configured to display only the token

When trying to send an array of objects in JSON format using AJAX, I'm facing an issue where only the token is being received when accessing $request->getContent. It appears that the data is not being sent properly. Can anyone assist me with this problem?

The form in createPage.blade.php

<form action="/invoices/submitInvoice" method="post" id="my-form">
   {{ csrf_field() }}
   TABLE STRUCTURE CODE GOES HERE
   <button type="submit">Send</button>
</form>
<button onclick="myCreateFunction()">Add</button>

Sending logic in sendGood.js

let counter = 0,
    nameContainer = [],
    priceContainer = [],
    obj = {},
    objArr = [];

$(function(){
  $('#my-form').submit(function(e){
    let elements = document.querySelectorAll("#my-form input[type=text]");

    // Loop over inputs and gather values
    for (let i = 0, element; element = elements[i++];) {
      if(element.type === "text"){
        if(element.value){
          if(element.className === "goodName") 
            nameContainer.push(element.value);
          else 
            priceContainer.push(element.value);
        }
      }
    }

    // Push to object array to be sent via AJAX
    for(let i = 0; i < nameContainer.length; i++){
      obj.name = nameContainer[i];
      obj.price = priceContainer[i];
      objArr.push(obj);
      obj = {};
    }

    let route = $('#my-form').data('route');
    $.ajax({
      type : 'POST',
      url : url('/invoices/submitInvoice'),
      data : {dataInput : JSON.stringify(objArr)},
      contentType: 'application/json; charset=utf-8',
      dataType : 'json',
      success: function(Response){
        console.log("daw",Response);
      }
    });
    e.preventDefault()
  });
});

InvoiceControllerWeb.php

public function invoiceCreate(Request $request){
   dd($request->all());
}

Result

^ array:1 [▼
  "_token" => "hEfjKsDHZadG3G5fCIgEJWcrNrFpv6G4PtjUPzJA"
]

Answer №1

After some trial and error, I managed to find a solution to my issue. It turns out, the problem lied in my route definition. I made a simple change by replacing "action" with "data-route", and then placed the route helper within my createPage.blade.php.

<form data-route="{{ route('company::invoices::makeInvoice') }}" method="post" id="my-form">
   {{ csrf_field() }}
   HERE IS MY TABLE STRUCTURE CODE
   <button type="submit">Send</button>
</form>
<button onclick="myCreateFunction()">Add</button>

Next, I updated my Ajax request to include the route variable in the URL.

let route = $('#my-form').data('route');
$.ajax({
    type : 'POST',
    url : route,
    data : {dataInput : JSON.stringify(objArr)},
    contentType: 'application/json; charset=utf-8',
    dataType : 'json',
    success: function(Response){
    console.log("daw",Response); 
  }
});

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

I am interested in running this script periodically using Ajax, ensuring that the page does not need to be reloaded

How can I implement a script in Javascript Ajax to run at specific intervals without having to reload the page? Here is the code snippet: include("databaseCONNECTION.php"); $seconds=1; $sql = "SELECT * FROM " . $dbDatabase .".chat ...

Looking for a script that can be executed on every individual ID, not just the most recent one triggered

Currently, I am working on a task manager that requires data retrieval from a database. Each task in the manager also needs to display a modal with specific details, including a map with a marker pinpointing its location. However, I have encountered an iss ...

The Bootstrap carousel controls now add the carousel ID to the address bar instead of just moving to the next slide

I can't figure out why my carousel isn't working. The id of the carousel is showing up in the webpage's address, which usually happens when the 'bootstrap.js' file is missing, but I have included it. Can anyone help me troubleshoo ...

having difficulty sorting items by tag groups in mongodb using $and and $in operators

I'm currently trying to execute this find() function: Item.find({'tags.id': { $and: [ { $in: [ '530f728706fa296e0a00000a', '5351d9df3412a38110000013' ] }, { $in: [ ...

When the Protractor configuration is executed, it displays the message "The requested webpage cannot be accessed."

Testing protractor on a vanilla.js app and encountering an error when running protractor basicConf.js The following error is occurring: This webpage is not available ERR_CONNECTION_REFUSED Here is the test script in use: describe('foo', fun ...

The vue transition elements vanish while in the midst of the animation phase

While using Vue Transition during page navigation, I encountered a problem. Involving a table with components, when transitioning to a new page, some components from the table disappear, causing the table to re-render and blink mid-transition. It took me s ...

Executing database queries in a synchronous manner in JavaScript

let positionConfig = require('setting'); function retrieveConfig(element) { let setting; positionConfig.find({element: element}, function (err,docs) { console.log(docs[0].current); // show the value setting = docs[0].curr ...

Guide on effectively exporting an NPM module for all browsers:

I have developed an NPM module which looks like this: class MyModule { // code here }; I am interested in making the export of MyModule universal, so that users can easily import it using any of the top 3 popular methods in the Browser: Using ES6 I ...

What possible reason is causing ag grid to overlook the defaultExcelExportParams option that was provided?

Here is my React ag grid code snippet. I'm trying to implement the processCellCallback function, but unfortunately, I am not seeing the console.log output in the browser console when exporting excel. Any suggestions on what might be causing this issue ...

AngularJS single page applications experiencing issues with loading scripts and stylesheets upon page reload

Homepage Setup : <ng-view></ng-view> Angular Routing Configuration : when('/', { url: '/', templateUrl: 'site/home', controller: 'indexController' }). when(&apos ...

Rescuing a nested window results in the salvation of the main window (JavaScript)

I'm currently working on a Javascript code that generates a "save-friendly" version of a webpage. child = window.open("","child");<br> child.document.write(htmlPage); The "htmlPage" consists of the basic HTML content of the page witho ...

Searching for specific elements within a certain range based on their

I currently have a table that consists of rows and columns, each containing specific attributes: <tr attr-y="1"><td attr-x="1">...</td><td attr-x="2">...</td>...</tr> <tr attr-y="2"><td attr-x="1">...</td ...

Discover how to verify the existence of an image within your local system by implementing AJAX technology

I have an image located in D:\img\need.png and I need to check if it exists or not. When attempting to do so with the following code, the error method is always called. $.ajax({ url:'http://www.himansuit.com//modiyojana.jpg', ...

Redux - Preventing Overwriting of Product Quantity in Cart by Creating a New Object

Is there a way to address the issue where adding the same product multiple times to the cart creates new objects instead of increasing the quantity? switch (action.type) { case actionTypes.ADD_TO_CART: const product = state.products.find((p) = ...

Error: Trying to access the 'element' property of an undefined value while attempting to submit a form

After constructing an HTML div via PHP, I encountered an issue where clicking "Submit" should trigger a form submission and execute a JS function. However, upon submission, Chrome's JS console displayed the error: Uncaught TypeError: Cannot read prop ...

Utilizing AJAX to send RSS feeds to a Django view

I'm fairly new to using ajax. Here's the scenario I'm dealing with: I'm working on a side project that involves displaying news and scores for various sports. To achieve this, I'm utilizing rss feeds from different sources. In my D ...

An issue has arisen with the TypeScript function classes within the React Class, causing a compile error to be thrown

I am currently in the process of transitioning a React object from being a function to a class. This change is necessary in order to save the state and bind specific functions that I intend to pass to child components. Unfortunately, during compilation, I ...

I'm curious if the response order will mirror the URL order in my situation

QUERY: Upon reviewing the following link: Promise.all: Order of resolved values I am doubtful about its relevance to my specific scenario. Can I always expect responses to be in the same order as urls? EXAMPLE: var urls = []; for (var i = 0; i < d ...

Fill input text fields with values based on dropdown selection and start with 2 input fields pre-filled

Initially, the issue is that there are 2 input text fields displayed. Depending on the selection from a drop-down menu ranging from 2 to 6, additional input fields should be added or removed. Here's my code: function addElements(selectElement) { va ...

What is the synergy between Ajax and JSF, and how do their lifecycles seamlessly integrate with one another?

I have experience with JSF 1.2 but am new to JSF 2.0. It appears that JSF 2.0 effortlessly integrates ajax functionality through the use of <f:ajax>, but I am still unclear on how this works. I am curious to understand what makes these two powerful t ...