Is this AJAX request properly formatted?

I am attempting to send an array of variables to my CakePHP action for editing purposes. The array is created from the ids of table rows. Below is the javascript code snippet that can be found in my index.ctp file.

<script type="text/javascript">
$('.edit_selected').click(function()
{
    var selected = new Array();
    alert('Edit Selected Has Been Clicked');
    $("#[id*=LocalClocks]").each(function()
    {
        if(false != $(this).is(':checked'))
        {
            selected.push($(this).attr('id').replace('LocalClocks', ''));
            $.ajax({
            type: 'POST',
            url: "/localhost/LocalClocks/editSelected/",
            data: JSON.stringify(selected),
            dataType: "json",
            success: function(data){ alert(data); alert('Edit Success'); }
            });
        }
    });
});
</script>

The logic involves extracting ids beginning with 'LocalClocks', removing 'LocalClock' to retain only numbers, then adding these id numbers to the selected array. The intention is to pass this array to the editSelected() function.

As I am not knowledgeable about data posting, I have a few inquiries. Is the existing code accurate so far? Should the editSelected() function include a parameter for the array being passed, or will the posted data automatically populate $this->request->data?

Shown below is the editSelected action:

public function editSelected()
{
    $this->set('isEditSelValid', false);
    $this->set('editSelValidationErrors', false);
    if ($this->request->is('post'))
    {
        $localClocksEntries = $this->LocalClock->find('all');
        foreach($localClocksEntries as $LocalClock)
        {
            $this->LocalClock->id = $LocalClock['LocalClock']['id'];
            $this->LocalClock->save($this->request->data);
            $this->set('isEditSelValid', true);
            $this->set('editSelValidationErrors', false);
        }
    }
}

The purpose behind sending this data is to obtain the ids of specific rows for editing. Each row contains checkboxes that the aforementioned JavaScript is capable of extracting and compiling into an array. It is essential to iterate through this array and update the user input accordingly.

Answer №1

In order for your server-side code to accept JSON, make sure to include contentType: "application/json" in the literal object sent to the ajax method. Currently, it is being sent with the default

application/x-www-form-urlencoded
. Other than that, your code appears to be correct.

datatType specifies the return data type, while contentType determines how the request data is transmitted.

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

Navigate to the element by clicking on the link, then apply a class to that specific element

I'm currently working with this HTML code: <div id="main"> <p>some text</p> <a id="goto-notes" href="#">see notes</a> <p>some text...</p> <div id="notes"> <p>notes here< ...

I encountered an issue with adding a console log in the getStaticProps() function that resulted in the error: SyntaxError: Invalid Unicode escape sequence at eval (<anonymous>

Welcome to my users.js page! import React from 'react' const displayUsers = ({users}) => { return ( <> { users.map(user => { return <div key={user.id}> {user.name} </div> }) } </&g ...

Enhancing Transparency of WMS Layers in OpenLayers

I need help figuring out how to add transparency to a WMS layer in openlayers. Here is the current javascript code for a non-transparent layer: var lyr_GDPSETAAirtemperatureC = new ol.layer.Tile({ source: new ol.source.TileWMS(({ ...

Implementing Dual Submit Buttons in Node.js using Express Framework

Struggling with implementing a like and dislike function in my node js app. Currently, I can only do one at a time. Below is the HTML code snippet: <form method="post" name="ratings"> <input type="submit" name="vote" value="like"> < ...

Angular first renders a component before removing another one using ng-If

I have two components that are displayed one at a time using an ngif directive. <app-root> <first-Comp *ngIf="showFirst"></first-Comp> <second-Comp *ngIf="!showFirst"></second-Comp> </app-root> Here are some key ...

Receiving a sleek black overlay with dynamic text upon hovering over an image

I have been searching extensively for a solution to my issue, but I haven't been able to make it work in my application. What I want is to create a black overlay over an image when it is hovered over, with text that resembles a button appearing on top ...

Creating dual modes (night/day) for your AngularJS application

Currently, I am in the process of developing a project with Angularjs and facing an obstacle with animations. My goal is to implement a feature in my application that allows it to display in two different modes - night mode and day mode. I have come ac ...

Regular expression for textarea validation

I'm currently working on creating a regex for a textarea in my Angular 8 application. The goal is to allow all characters but not permit an empty character at the start. I've experimented with 3 different regex patterns, each presenting its own s ...

Implementing Model-View-Controller architecture with the help of Ajax for displaying partial

Within my MVC app, I have the following markup: <div id="ingredientlistdiv"> <% Recipe recipe = (Recipe)Model; %> <% Html.RenderPartial("IngredientsListControl", recipe.Ingredients); %> </div> <div id="ingredien ...

Is it possible to dynamically assign and call functions through an Object in Angular 6?

I implemented a click handler for a button that is generated dynamically. Within the click handler function, I am invoking a callback function. However, I encountered an issue where an error message popped up stating that "Callback function is not a fu ...

What is the best way to organize divs in a grid layout that adapts to different screen sizes, similar to the style

Is there a way to align multiple elements of varying heights against the top of a container, similar to what is seen on Wolfram's homepage? I noticed that they used a lot of JavaScript and absolute positioning in their code, but I'm wondering if ...

When the 'keyup' event is detected, trigger the function only on keyup

Looking for assistance in setting this to only trigger on keyup events. Can anyone provide guidance? $(function() { $('#acf-field_5a32085c7df98-field_5a3208f87df99').on('keyup', function() { $('#link-headline-fb').text($( ...

What is the best way to transfer values from an AJAX script to the rest of the Javascript code?

Currently, I am diving into the world of a django 2.0 template along with a third-party jQuery script used for tagging photos and my own JavaScript code that acts as the "glue." Despite being new to JavaScript and JQuery, I managed to make a successful aja ...

How to enable the Copy to Clipboard feature for multiple buttons and transition from using an ID to a class identifier

Can someone please assist me? I have a copy to clipboard function that works well for IDs and a single button on my website. However, I need to modify it to work for multiple buttons and values with a class identifier. Unfortunately, I am unsure how to mak ...

Is there a way to automatically import all images from a folder in VUE?

I'm attempting to automatically import all images from a folder. Here is what I've tried under // tested: <template> <p>classical art</p> <img v-for="image in images" :key="image" :src="image.url& ...

Troubleshooting random array issues in JavaScript and jQuery

I want to create a randomized array with DOM elements, here's what I have so far: var allTargets=$('#target1, #target2, #target3, #target4'); var randomTargets=null; randomTargets = allTargets[Math.floor(Math.random() * allTargets.length)]; ...

Is the bearer terminology used for the authentication token or is it meant for a separate token?

In my MEVN application, I am incorporating JWT tokens and currently exploring how to transmit authentication tokens via axios. It is common practice to add "Bearer " before the token and have the server strip off "Bearer " to access the token's conten ...

Changing boolean values in Ruby on Rails articles

Within my 'comment' model, I have a boolean value that can be either true or false. The following excerpt is from my controller comments_controller.rb: class CommentsController < ApplicationController before_action :find_comment, only: ...

Delay in only a portion of the AJAX response

I created a chat application that is functioning correctly, but I am encountering an unexpected behavior. When a user sends a message, the user's name, time, and message should be displayed in order. However, currently, it seems like the username and ...

Retrieving data from a database using Ajax

As I develop a webpage that dynamically loads images from a database as the user scrolls, I encounter an issue where newly added images are displayed again when more images are fetched from the database. How can I prevent this from happening? Here is the ...