Storing selected elements from an array into a database using Laravel and Ajax

I have a query. I am working on saving arrays into a database but before doing so, I need to split the data and only save specific values. My approach involves using Ajax to pass the data to the controller.

Important note: The array sets can be more than 1, therefore each set needs to be divided and stored based on columns inside the database.

Below is the JavaScript code with Ajax:

Hotspot.prototype.saveData = function (data) {
        if (!data.length) {
            return;
        }

        // Get previous data
        var raw_data = localStorage.getItem(this.config.LS_Variable);

        var hotspots = [];

        if (raw_data) {
            hotspots = JSON.parse(raw_data);
        }
    
        // Append to previous data
        $.each(data, function (index, node) {
            hotspots.push(node);
        });
        console.log(hotspots);

        this.data=data;
        $.ajax({
            type:"POST",
            url:"/store",
            dataType:'json',
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            },
            data:{
                Title: JSON.stringify(hotspots),
                Message: JSON.stringify(hotspots),
                x: JSON.stringify(hotspots), 
                y: JSON.stringify(hotspots),
            },
            success: function(data){

                console.log(data,d);
            },
            error: function(data)
            {
                console.log(data);
            },
            
        });

        localStorage.setItem(this.config.LS_Variable, JSON.stringify(hotspots));

        this.element.trigger('afterSave.hotspot', [null, hotspots]);
    };

The Controller:

public function storePin(Request $request)
    {
       request()->validate([
           'Title' => 'required',
            'Message'  => 'required',
            'x'=> 'required',
            'y'=>'required',
       ]);

           dd($request);
             if ($request->all())
             {
                 $pin = new Pin();
                 $pin->Title=json_encode($request->input('Title'));
                 $pin->Message= json_encode($request->input('Message'));
                 $pin->x = json_encode($request->input('x'));
                 $pin->y =json_encode($request->input('y'));

                 $pin->save();

             }

    }

An example of the output:

Title: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
Message: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
x: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]
y: [{"x":58.333333333333336,"y":90.54545454545455,"Title":"hi","Message":"hi"}]

Based on this, I want to only save:

Title:only save title
Message:save message
x:save x
y save y

Answer №1

Simply pass the complete array of hotspots like this:

data: hotspots,

After that, in your model, handle any formatting and insert multiple hotspots:

// Implement some formatting for creating data array
$data = [];
foreach($hotspots as $hotspot){
    $data[] = [
        'Title' => $hotspot['Title'],
        'Message'  => $hotspot['Message'],
        'x' => $hotspot['x'],
        'y' => $hotspot['y'],
    ];
}

Pin::insert($data);

Answer №2

The issue seems to stem from the way data is being parsed into hotspots. The current approach involves looping through each entry in data and pushing the entire node into hotspots.

$.each(data, function(index, node) {
  hotspots.push(node);
});

Each property definition is referencing the complete hotspots object instead of its individual properties.

data: {
  Title: JSON.stringify(hotspots),
  Message: JSON.stringify(hotspots),
  x: JSON.stringify(hotspots),
  y: JSON.stringify(hotspots),
},

To resolve this, consider something like:

{
  Title: hotspots[0].Title,
  Message: hotspots[0].Message,
  x: hotspots[0].x,
  y: hotspots[0].y,
}

However, this solution overlooks crucial details. For instance, hotspots should actually be an array containing multiple hotspot objects. How can you determine which one to send for a single request?

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

Comparison of Chrome's compatibility with Bootstrap and Edge

Firefox Safari I am facing an issue that seems obvious, but I am unable to pinpoint the exact cause. It just doesn't seem right for no apparent reason. is the website in question. I have tried various troubleshooting methods such as inspecting th ...

Having trouble retrieving the necessary data to generate a menu, the getStaticProps function is coming back as undefined

I'm currently working with Next.js 13 & Strapi, and my goal is to create a Menu component utilizing the getStaticProps function. To achieve this, I've implemented a Layout component within the _app.js file, and nested a Menu component inside the ...

Identifying when a paste event occurs within a contenteditable field

How do you detect and prevent a paste event in a content editable div so that you can intercept and sanitize the paste to only include text? Another concern is not losing focus after completing the paste + sanitize process. ...

Unable to use .click function to choose image within container

Apologies for the lengthy post, but I believe providing all details is essential to understanding the issue at hand. The following code snippet is intended to display the first image in a pop-up box when a user clicks on any of the images shown: <div ...

Adjust the color of the text based on a conditional in react

I am looking for a way to select elements and change text color in my unordered list based on specific conditions. Below is an example of the structure I have: <div style={styles.passwordRules}> <ul style={styles.listOne}> <li style={ ...

What are some ways to handle and manipulate a JSON object received through AJAX?

In my Rails app, I have implemented this jQuery code: $('#rankings_link a').click(function(){ $.ajax({ dataType: 'json', contentType: 'application/json', url: '/rankings', type: ' ...

Is it really not feasible to retrieve a file using an AJAX request in ASP.NET MVC5?

While it may be more common to use a normal call instead of an AJAX call, there are instances where using AJAX is necessary, such as displaying an error message on a modal dialog during a download process. In my MVC5 project, I needed to download a file us ...

What is the best method to eliminate the 'Unsorted' selection from the sorting options in Material React Table?

Currently utilizing the "material-react-table" library within a React JS project. In alignment with my needs, seeking to eliminate the 'Unsorted' sorting option in Material React Table. Could someone assist me in addressing this? Your help is ...

ng-display does not display content when the condition switches to true

I am facing an issue with displaying an image and a YouTube video in my HTML. My goal is to show the image when the video is not playing, and switch to displaying the video when it starts playing. Upon loading the page, only the image is shown, which is ...

Updating the image sources of a group of image tags with a predetermined list

Looking to update a series of image source references within a specific div tag. For example: <!-- language-all: lang-html --> <div id="Listofimages"> <img src="images\2page_img_3.jpg"> <img src="images\2page_img_3 ...

Error: A TypeError occurred with the startup because it was unable to read the property 'Collection' as it was

Recently, I encountered a series of problems one after another. The first issue was: TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client To resolve this problem, I made changes to my code from: const Discord = require(" ...

Storing user feedback in database using ajax

I have encountered a common issue in this thread, and although it has been discussed multiple times, I am still unable to solve my problem. My struggle lies in sending and fetching data from comment.php to insert.php. Below is the code from my comment.php ...

Ways to prevent users from pushing multiple child data or adding more than one child to a specific child in the Firebase database

How can we limit users from pushing more than one piece of data to the Firebase database in terms of security rules? I have attempted this approach without success. { "rules": { ".read": false, ".write": false, "voters": { // En ...

Adding an eventListener to the display style of a div in React: A step-by-step guide

I'm currently working on implementing a functionality in React where a Highcharts chart automatically resizes to fit its parent element whenever the parent div is shown. Unlike other libraries, Highcharts doesn't support automatic resizing when t ...

Assign specific classes to the rows and overall table by extracting information from the first row and first column of the table

My goal is to utilize jQuery in order to dynamically assign classes to the rows and columns of a table based on the classes of the first row and column. For instance: The current HTML code I have is as follows: <table class="numAlpha" border="1"> ...

What is the best way to configure input fields as readonly, except for the one being actively filled by the user

Is there a way to make all input fields readonly except the one that the user is trying to fill data into? After the user loads the page index.php and attempts to input data into, for example, <input id="edValue2" ...>, I want to set all input field ...

Utilizing v-for to display dynamic data in a modal imported through slots

Issue: I'm facing an issue with passing data from a clicked card to a modal component. The modal should display the title, image, preview URL, and download URL of the card that was clicked. However, I'm encountering an error that says is not def ...

What is the reason for this Javascript regular expression only successfully matching two out of three identical strings when filtering?

To better illustrate my question, I would like to reference the following link: http://codepen.io/anon/pen/mRxOEP Here are three seemingly identical inputs from customers: <span class="customer_country" id="SW1">, Switzerland</span> <span ...

Despite the dependent dropdown menu not refreshing, the console continues to display the data

In my development project using MVC structure, I have implemented the following JQuery functionality: <script type="text/javascript> $('select[name="provider_id"]').change(function() { var provider_id = $(this).val(); ...

In order to utilize the componentDidUpdate lifecycle method, I passed props to the Outlet component while nesting it

I am currently using react-router-v6 and encountering some issues with my configuration. I have implemented nested routing with layouts according to the following settings. App.js <BrowserRouter> <Routes> <Route exact pat ...