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

Tips on avoiding blurring when making an autocomplete selection

I am currently working on a project to develop an asset tracker that showcases assets in a table format. One of the features I am implementing is the ability for users to check out assets and have an input field populated with the name of the person author ...

Using AJAX/JQuery along with PHP to instantly send notifications without refreshing the page for a contact form

Website URL: This website was created by following two separate tutorials, one for PHP and the other for AJAX. The main objective was to develop a contact form that validates input fields for errors. If no errors are found, a success message is displayed ...

Sending data from a child component to its parent counterpart

A component called cartComponent has a data property named cartCount which increases every time a new item is added to the cart. I want to utilize this value to update another value in the template that is not part of the component. Is it achievable? Bel ...

Tips for implementing validation on dynamically inserted fields in a form

My form has two fields, and the submit button is disabled until those fields are filled with some text. However, if I add a third field dynamically using AngularJS, validation will not be supported for the new field. Check out the example here <butto ...

JavaScript data structure similar to ListOrderedMap/ArrayMap

Does anyone know of a JavaScript data structure that functions similarly to ListOrderedMap? I need it to have the capability to add an object at a specific index, retrieve the index for a given object, and lookup an object by its id. Unfortunately, all t ...

What are the steps for implementing custom edit components in material-react-table?

I am currently using the official material-react-table documentation to implement a CRUD table. You can find more information at this link: . However, I encountered an issue while trying to utilize my own custom modal components for the "create new" featur ...

Accessing a subcollection with DocumentSnapshot in Firebase using JS9

Just had a quick question. Is anyone familiar with how to achieve something similar using Firebase JavaScript v9? Essentially, I have a `userDoc` that is a DocumentSnapshot and I need to access a sub-collection with the document snapshot. Here's the c ...

Update the Google Chart whenever an Ajax request is made

Upon the initial load of the chart with the default Ajax response, everything seems to be working fine. When I add console.log(chart_data), I can see both the default data and the new data after submitting. The only issue is that the chart does not redraw ...

How to Retrieve a Variable from the Parent Component in a Child Component using Angular (1.5) JS

I am currently working on abstracting the concept of a ticket list building into an angular application using 2 components. 1st component --> ("Smart Component") utilizes $http to fetch data and populate an array called populatedList within the parent ("g ...

Prevent mobile users from entering text with Material UI Autocomplete on keyboard

Currently, I am utilizing the Material UI Autocomplete component for multi-select functionality. Although it functions perfectly on desktop, I want to prevent keyboard input on mobile devices and only allow touch selection. Essentially, I do not want the v ...

Using jQuery ajax links may either be effective or ineffective, depending on the scenario. At times

Can someone please assist me in understanding why an ajax link may or may not work when clicked? It seems to function intermittently. window.onload = function(){ function getXmlHttp(){ ...... // simply ajax } var contentContainer = ...

Best Practices for Managing Long Running Tasks in ASP.NET 4.0 with C#

How should I handle processes that require a long execution time? I want to avoid running them on the server because it may cause the page to time out. I have researched various methods such as AJAX, Threading, and Web Services, but I do not have experien ...

Converting Milliseconds to a Date using JavaScript

I have been facing a challenge with converting milliseconds data into date format. Despite trying various methods, I found that the solution provided in this link only works for a limited range of milliseconds values and fails for higher values. My goal is ...

TS2345: The argument provided, which is of type 'Event', cannot be assigned to the parameter expected, which is of type 'HtmlInputEvent'

I am facing an issue while trying to upload a file, and I could use some assistance in resolving it. Angular-----Error: src/app/admin/producto/create-producto-dialog.html:38:47 - error TS2345: Argument of type 'Event' is not assignable to parame ...

submit a new entry to add a record to the database

Hey there, I recently started learning PHP and JS and I'm trying to insert a row into a WordPress database table. I need to get the information needed for insertion from another table, but I'm facing an issue with the PHP file as it's not in ...

Transform the appearance of a button when focused by utilizing CSS exclusively or altering it dynamically

As a newcomer to coding, I am currently working on a project that involves changing the color of buttons when they are clicked. Specifically, I want it so that when one button is clicked, its color changes, and when another button next to it is clicked, th ...

Determine if the given text matches the name of the individual associated with a specific identification number

Struggling to create a validation system for two sets of fields. There are 6 inputs in total, with 3 designated for entering a name and the other 3 for an ID number. The validation rule is that if an input with name="RE_SignedByID" contains a value, then c ...

The JavaScript Ajax request appears to be malfunctioning in both Firefox and Google Chrome, however, it seems to be functioning properly

I am currently using JavaScript to make an Ajax request to communicate with an Arduino webserver and dynamically update the content on a webpage. While this functionality has been working smoothly in Safari, I have encountered issues when trying to use it ...

Issues with Jquery keyup on Android devices - unable to detect keyup

I have not tested this code on an iPhone, but I am certain (tested) that it does not work on Android mobile devices: $('#search').live('keyup',function(key){ if(key.which == 13){ /*ANIMATE SEARCH*/ _k ...

Uploading a file to a .NET Framework API Controller using React

I am trying to figure out how to send files in the request body to an API controller in .NET framework using React. My goal is to achieve this without changing the request headers, so I want to send it as application/json. What I am looking for is somethi ...