What is preventing the AJAX from saving the data in the database?

PIC I want to ensure that when I hit enter, the input data is successfully saved to the database.

The Controller:

public function saveData(Request $request){
    $data = Data::create([
        'user' =>  Auth::user()->id,
        'receiver' => $request->receiver_id,
        'content' => $request->message,
        'is_Saved' => 0,
    ]);
    $data->save();
}

The form:

<div class="card-footer">
<form id="data_form">
    <div class="input-group">
        <div class="input-group-append">
            <span class="input-group-text attach_btn"><i class="fas fa-paperclip"></i></span>
        </div>
        <input type="text" name="message" id="message_input" class="form-control type_msg" placeholder="Type your message...">
    </div>
</form>

The ajax code:

$(document).on('keyup', '.input-group input', function (e) {
        var message = $(this).val();
        var url = '{{ url('data') }}';
        // check if enter key is pressed and message is not empty also receiver is selected
        if (e.keyCode == 13 && message != '' && receiver_id != '') {
            $(this).val(''); // empty the text box on pressing enter

            var datastr = "receiver_id=" + receiver_id + "&message=" + message;
            $.ajax({
                type: "post",
                url: '/data', 
                data: datastr,
                cache: false,
                success: function (data) {
                    console.log(data)
                },
                error: function (jqXHR, status, err) {
                },
                complete: function () {

                }
            })
        }
    })

The Route:

Route::post('data', [ConsultationController::class, 'saveData']);

However, the data is not being saved in the database without any error notification. How can this issue be resolved? Please Help :)

I attempted deleting the If statement in the ajax code, which resulted in a 500 Internal Server ErrorPIC:

POST http://127.0.0.1:8000/data 500 (Internal Server Error)
send    @   jquery.min.js:2
ajax    @   jquery.min.js:2
(anonymous) @   consultation?message=adfadf:399
dispatch    @   jquery.min.js:2
v.handle    @   jquery.min.js:2

Answer №1

Make sure to include all the necessary columns in the $fillable property of the Message model.

Answer №2

Everything in your code seems to be correct, but it's important to remember that Laravel requires a CSRF token for every post / put / delete request to validate. You can find more information on this security measure in the Laravel documentation.

Make sure to include this in your AJAX request:

            $.ajax({
                type: "post",
                url: '/message', // Remember to set up this post route
                data: {
                    receiver_id,
                    message,
                },
                headers: { // Add this
                 'X-CSRF-TOKEN': 
                   $('meta[name="csrf-token"]').attr('content')
                },
                cache: false,
                success: function (data) {
                    console.log(data)
                },
                error: function (jqXHR, status, err) {
                },
                complete: function () {

                }
            })

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

Issue with two Ajax forms

Having some trouble with my ajax forms and can't seem to figure out the issue. Essentially, I have two contact forms on the same page that use the same code, with the only difference being their placement - one at the top and one at the bottom. The p ...

Creating and adding nested div elements with the power of JavaScript

My goal is to utilize JavaScript for updating the CSS layout as the webpage loads. Below is the code I have been working on: var container = 0; // Total UI Container var containerTitle = 0; // Title Container var article = 0; var articleTitle = 0; var ...

What is the best way to simulate DynamoDB promise functionality with Jest?

Looking for a solution without using any libraries (as they haven't worked in my case). How can I make it work for that promise returned by the dynamodb query? Check out the code to be tested below: const isUrl = require('is-url'); const ...

Could not connect: AJAX Request denied?

I am currently hosting a Digital Ocean server that runs on a MEN stack composed of MongoDB, Express, and Node. The registration form can be accessed at: When attempting to choose an option from the dropdown menu, I encounter the following error message: G ...

Sharing real-time data components in Vue 2.0 with others

Update: I've recently implemented VUEX to efficiently manage and store all my data. I'm currently facing an issue with data synchronization between components in a container. Although each component's data is stored within the container, it ...

What is the process for attaching text or labels to an object, similar to applying decals?

Check out this website: On this site, you can create text, add it to objects like a decal, and then click "Ok" to confirm. Is there a way to make this effect visible on the design? Many thanks in advance! ...

Uncovering the unique properties of custom Items in MUI v5 - RichTreeView: A Step-by-Step Guide

Can custom item properties received asynchronously with MUI - RichTreeView be exposed inside a custom treeItem? For instance, how can the customProperty1 and customProperty2 be accessed within the CustomTreeItem? The console.log to props only shows defaul ...

Creating a custom AngularJS HTTP interceptor that targets specific URLs

Is there a way to configure an $http interceptor to only respond to specific URL patterns? For example, I want the interceptor to only intercept requests that match "/api/*" and ignore any other requests. ...

Using the dot operator to load an image

Is it possible to using the dot operator to load an image? Let's talk about this as a sample image URL <img src={{GET_PROFILE_DATA.googleProfileData.fullName}} alt="profile" class="home-screen-profile-image"> Take note of the unusual looking ...

Postpone an automatic action in React

I'm currently working on adding a fade out animation to a page change in React, but I need to delay the click event before the page actually transitions. Here's the code snippet I have so far: export default function Modal({setTopOf}) { const ...

Utilize fileSystem in an API Route when working with NextJS deployed on Vercel

I am facing an issue with using fileSystem methods like readdirSync on an API Route in NextJS. It functions properly locally but returns a 500 status code when deployed on Vercel. Here is the error message from Vercel's Function Logs: catch Error: EN ...

Implementing dynamic dropdown population in Angular 2 based on selection from another dropdown

I am relatively new to Angular 2 and currently facing a challenge in populating a dropdown menu based on the selection from another dropdown menu from MongoDB. The Issue: While I can successfully load the rooms, I encounter a problem when trying to load t ...

Is there a way to identify the breakpoints of a header that has a changing number of menus?

I am currently designing a customizable header for a web application, where the admin has the ability to add or remove menus as desired. For instance: https://i.sstatic.net/37IeG.png Or https://i.sstatic.net/zbIPd.png The breakpoints for these two navigat ...

Remove item from jQuery's "raw text" HTML

Suppose I have the following JavaScript string: var string = '<div id="div1"><div id="div2"></div></div>'; Is it possible to utilize jQuery in order to create a new string as shown below? var newString = '<div i ...

Print out - find elements by class name in the console

I'm currently learning how to use HTML5 Drag and Drop. I have a table created with PHP that generates HTML elements. echo "<li class='elements' id='".$row['id']."' draggable='true'>".$row['element_n ...

Enhancing Rails with AJAX for Seamless File Upload

My current challenge involves a form placed within a modal box, featuring an upload field. Upon submission, error messages are displayed without the modal closing. However, if an error occurs and there is already a file uploaded in the field, the request ...

Implementing dynamic data transfer to a Bootstrap modal in Laravel by utilizing jQuery's post method

My goal is to dynamically pass data to a bootstrap modal. I aim to achieve this by sending the data-id through a jQuery post request. Within my view, I have a 'users' section with a list of users. Upon clicking the 'details' button, I i ...

How can HTML and CSS be linked to display images independently?

Check out this code: body{ background-image:url('http://wallpoper.com/images/00/31/33/51/black-background_00313351.jpg'); } div.header{ background-color:#F0F8FF; text-align:center; padding:3px; ...

The validation for the start and end dates in the datepicker is not functioning properly when

I have integrated a bootstrap date picker into my website. However, I am encountering an issue where the end date validation does not update when I change the start date after the initial selection. <script type="text/javascript" src="htt ...

Is it possible to transfer a value when navigating to the next component using this.props.history.push("/next Component")?

Is there a way I can pass the Task_id to the ShowRecommendation.js component? recommend = Task_id => { this.props.history.push("/ShowRecommendation"); }; Any suggestions on how to achieve this? ...