What is the best way to transfer information from a view to a controller in Laravel using AJAX?

I am facing an issue with sending data from the view to the controller in Laravel version 7 I am sending data from a form and ul li elements I have an array of data in JavaScript

Here is my HTML code:

<ul name="ali" id="singleFieldTags" class="tagit ui-widget ui-widget-content ui-corner-all">
    <li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
        <span class="tagit-label">reza</span>
        <a class="tagit-close">
            <span class="text-icon">×</span>
            <span class="ui-icon ui-icon-close"></span>
        </a>
    </li>
    <li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
        <span class="tagit-label">ali</span>
        <a class="tagit-close">
            <span class="text-icon">×</span>
            <span class="ui-icon ui-icon-close"></span>
        </a>
    </li>
    <li class="tagit-new">
        <input type="text" class="ui-widget-content ui-autocomplete-input" autocomplete="off">
    </li>
</ul>


     <form id="form" method="post" action="/save_new" enctype="multipart/form-data">
        @csrf

        <div class="form-group">
            <label for="title">Title</label>
            <input type="text" name="title" class="form-control">
        </div>

        <div class="form-group">
            <label for="choose-file" class="custom-file-upload" id="choose-file-label">
                Click Here to Upload Image

            </label>
            <br/>
            <br/>
            <label >No Image Selected!</label>
            <input name="uploadDocument" type="file" id="choose-file"
                   accept=".jpg,.jpeg,.pdf,doc,docx,application/msword,.png" style="display: none;" />
        </div>

        <div class="form-group">
            <label for="title">Description</label>
            <textarea name="meta_description" class="form-control"></textarea>
        </div>

        <div class="form-group">
            <label >Keywords</label>
            <input name="tags" id="mySingleField" value="reza,ali" type="hidden" disabled="true">
            <ul name="ali" id="singleFieldTags"></ul>
        </div>

        <button type="submit" onclick="myF()" class="btn btn-success pull-left">Save</button>



    </form>

In my JavaScript:

 <script type="text/javascript">
  function myF() {
        var data2 = [];
        var inputs = $(".tagit-choice");

        for (var i = 0; i < inputs.length; i++) {
            data2[i] = $(inputs[i]).text();
        }

           $.ajax({
            url:'/save_new',
            type: 'POST',
            dataType:'json',
            // data: JSON.stringify(data2),
            data: JSON.stringify(data2),
            contentType: 'application/json; charset=utf-8',
                    success: function( data ){
                        console.log('ok');
                        console.log(data);
                    },
                    error: function (xhr, b, c) {
                        console.log('error');
                        console.log("xhr=" + xhr + " b=" + b + " c=" + c);
                    }
        });
    }

When I send data using AJAX, I encounter an error in the console.

Error reza:263:37
xhr=[object Object] b=error c=

But in the request JSON, I see:

0   "reza×"
1   "ali×"

Please assist me. Thank you!

My controller:

public function save_new(Request $request){
//        dd($request->all());

dd($request->getContent());

}

My route:

Route::POST('/save_new','Backend\AdminPostController@save_new')->name('save_new');

Edit:

My problem has been resolved. Thank you all!

var fd = new FormData();
var file = $("#form input[name=uploadDocument]")[0].files;
fd.append('file', file[0]);
fd.append('title', $("#form input[name=title]").val());
fd.append('description', $("#form textarea[name=meta_description]").val());
fd.append('tags', JSON.stringify(data2));

$.ajax({
    type: 'post',
    url: '/ok2',
    contentType: false,
    processData: false,
    data: fd,
    success: function(response) {
        
    },
    error: function  (response) {},
});

Answer №1

When it comes to sending data via jQuery, one basic method is to use ajaxSetup within the document.ready function to ensure smooth operation.

$.ajaxSetup({
     headers: {
       'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
     }
 });
 

$('#form').on('submit',function(){
    $.ajax({
    type:'post',
    url:$("#form").attr('action'),
    data:$("#form").serializeArray(),
    success:function(data){
        //response
        console.log(data);
      }
  });
});

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

Eliminate the standard blue border that appears when control-clicking on table elements

I've encountered this question before, but unfortunately none of the solutions provided have worked for me. Some things I've attempted are: Using event.preventDefault() - did not produce the desired result. Removing user-select from CS ...

Ways to implement the function provided in the website using javascript

Exploring the world of JavaScript functionality as a beginner, I am eager to try pasting dynamic data into HTML. I came across a helpful link providing instructions on how to achieve this using a table format. However, despite my best efforts, I am strugg ...

Designing a login system with MEAN stack architecture?

I am currently in the process of building a web application using the MEAN stack (MongoDB, Express, AngularJS, and node.js). Specifically, I am working on implementing a login system and securing certain routes in my Angular app so that they are only acces ...

Retrieve the quantity information from a JSON object

Hello everyone! I am new to programming and need help. How can I retrieve the 'qty' value of 0 using JSON and PHP from the following data: {"XXXXXX":[],"XXXXXX":[],"total":[{"assetref":"","qty":0,"raw":0}]} I have attempted the following code: ...

How can I convert a string field type to an array within a MongoDB array without losing the original value?

Here is the original document I am working with a database named "test" that has a collection named "testing". Within this collection, there is a document that contains an array called "methods" which includes an object at index 0 (and potentially more ob ...

Obtain the Ajax URL from a different webpage

I have been exploring various methods to access the ajax function of a website. Here is the code snippet I am working with: $.ajax({ type: 'POST', url: 'sched', //more code here.. }); It's worth noting that in the UR ...

A guide to implementing a dynamic limit in ng-repeat using AngularJS

I'm looking to dynamically set a limit in my ng-repeat. The goal is to limit the number of items displayed to 1 when the window width is less than 750px. Below is the function in my controller: $scope.$watch('window.innerWidth', function() ...

Oops! RangeError [MESSAGE_CONTENT_TYPE]: The content of the message must be a string that contains at least one character

Can someone help me troubleshoot my regular send command? I keep encountering an error message even after following suggestions from previous answers. Here is the error: RangeError [MESSAGE_CONTENT_TYPE]: Message content must be a non-empty string. at ...

To encounter an "undefined" response in the following route of an express application, utilize the next('route') function

const express = require('express') const app = express() app.get('/user/:uid', (req, res, next) => { if (req.params.uid === 'lai9fox') next('route') else next() }, (req, res, next) => { res.send(`<h1& ...

Dealing with the element not present error in Protractor can be managed by using various

Is there a way to achieve similar Exception handling in Protractor as we can with Selenium webdriver in Java? When dealing with element not found exceptions, what is the most effective approach to handle them using Protractor? ...

Inserting a custom text box underneath the Anything Slider

I am currently incorporating the Anything Slider into a website project. The main purpose of the slider is to showcase videos, but I would like to include a description text box beneath it that dynamically changes based on the selected tab. This snippet de ...

Working with handleChange and onSubmit functions in pure JavaScript without any libraries

Currently developing my initial app, which is a login/register form using JS/Node.js/MySQL. I am facing issues with connecting my form to the database in order to store user data. I haven't utilized "handleChange" or "onSubmit" functions as I am not e ...

Issues with the functionality of AngularJS routing system

angular.module('Stations', ['ngRoute']) .config(function ($routeProvider) { $routeProvider .when('/documents/:stationId', { templateUrl: '/Scripts/Modules/checklist/views/index.html', ...

How can the values from the scale [-60, -30, -10, 0, 3, 6, 10] be converted to a decimal range of 0-1 through

Thank you for helping me with so many of my issues. <3 I'm certain that someone has already solved this, but I'm unsure of the specific mathematical term (I've attempted reverse interpolation and others, but with no luck) so I am present ...

Trouble with event.preventDefault functionality

This snippet of code I'm working on is pretty basic, nothing too intricate. $("input#send").submit(function(event){ event.preventDefault(); $.ajax({ type: 'POST', url: add.php, data: data, succe ...

What is the best way to make img-fluid function properly within Bootstrap Carousel?

I've been struggling to make my carousel images responsive by using the img-fluid tag, but I haven't had any success. I've attempted using !important and display: block, but nothing seems to work. I'm not sure what's causing the is ...

Using JavaScript to parse JSON data generated by PHP using an echo statement may result in an error, while

I am facing an issue with parsing a JSON string retrieved from PHP when the page loads. It's strange that if I send an AJAX request to the same function, the parsing is successful without any errors. The problem arises when I attempt to do this: JSON ...

Avoiding unnecessary re-renders of a parent component caused by a child component

I'm facing rendering problems and would greatly appreciate any assistance. I attempted to use useMemo and useCallback, but it resulted in the checkbox breaking. Within a component, I am displaying information from an object. Let's consider the fo ...

A guide to retrieving the timezone based on a specific address using the Google API

I need to utilize the Google API time zones, which requires geocoding the address to obtain the latitude and longitude for the time zone. How can I achieve this using a value from a textarea? Here are the 2 steps: Convert the textarea value into a geoc ...

Transferring data from JavaScript to PHP with the help of AJAX

I am encountering issues with my code, as I cannot seem to successfully send coordinates from JavaScript to PHP using AJAX. Although I can retrieve values from JavaScript into a textbox, the values are not being transferred to PHP. Any assistance on resolv ...