"Implementing database updates with AJAX and utilizing the PUT method: a step-by-step guide

I am attempting to update a database property named "Estado" using ajax. Here is the code I am using:

  function updateDatabaseProperty(idMarker, newState) {
    $.ajax
        ({
            url: `/api/IgnicoesAPI/${idMarker}`,
            type: 'PUT',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify({ Id: idMarker, Estado: newState }),
            async: true,
            processData: false,
            cache: false,
            success: function (result) {
                 connection.invoke("PostMarker").catch(function (err) {
                              return console.error(err.toString());
                 });
            },
            error: function () {
                alert("An error occurred!")
            }
        });
}

Below is my model:

        public class Ignicoes
{

    public Ignicoes()
    {
        ListaOcorrencias = new HashSet<Ocorrencias>();

    }
    [Key]
    public int Id { get; set; }

    [Required]
    public string Latitude {get ;set;}

    [Required]
    public string Longitude {get; set;}

    //estado(recusada, aceite, em avaliacao, concluido)
    //public string Estado { get; set; }
    [Required]
    public string Estado {get;set;}
  
    public DateTime DataInicioPropostaIgnicao {get;set;}
    
    public DateTime DataDecisaoIgnicao{get;set;}
   
 
    public virtual ICollection<Ocorrencias> ListaOcorrencias {get;set;}

}

Below is my PUT method:

     public async Task<IActionResult> UpdateIgnicoes([FromRoute] int id, [FromBody] Ignicoes ignites)
    {
      
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }


        if (id != ignite.Id)
        {
            return BadRequest();
        }

        else
        {
            var decisionDate = DateTime.Now;
            var ig = _context.Ignicoes.FirstOrDefault(igniteId => igniteId.Id.Equals(id));
            if (ig != null)
            {
                ig.Estado = ignites.Estado;
                ig.DataDecisionIgnicion = decisionDate;
            }
            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!IgnicoesExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }
        }

        return NoContent();
    }

I have tried the above code and noticed that instead of changing the "Estado" property, it changed the "Latitude" property successfully. Both properties are of the same type - String. Can someone help me identify the error? Here is the content from my output tab:

https://i.sstatic.net/w4LOV.png

Here is the Network Analysis: https://i.sstatic.net/sfcKo.png

{"errors":{"Latitude":["The Latitude field is required."],"Longitude":["The Longitude field is required."]},"type":"https://tools.ietf.org/html/rfc7231#section-6.5.1","title":"One or more validation errors occurred.","status":400,"traceId":"|43114da6-4594b09a6260f1a2."}

Answer №1

To better understand the issue, it would have been helpful if you included logs of ajax http requests and responses, including status codes and payloads. The application output indicates a 400 bad request error for your API method invocation.

Upon reviewing your resource class, it seems that you have three properties marked as [Required] (excluding Id): Longitude, Latitude, Estado. However, in your ajax call, you are only passing ID and Estado. It is likely that the 400 response is due to missing required properties in your ajax request body. To resolve this issue, try adding the missing properties like so:

data: JSON.stringify({ Id: idmarcador, Estado: novoEstado, string: latitude, string: longitude })

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

The jQuery application adds new HTML elements to the page and then reveals the code that follows

When making an Ajax call and rendering two templates based on the response, I encountered a problem where the correct template renders but the script following it appears on the page as plain text. Here's the code snippet with the issue: if (question ...

Struggling to locate a combobox control within the edittemplate of a Gridview?

I'm currently searching for this specific control within the Gridview's edititemtemplate area. <EditItemTemplate> <ajaxToolkit:ComboBox ID="GridviewCategoryComboBox1" AppendDataBoundItems="true" runat="server" Aut ...

Serialize a series of select boxes to optimize for AJAX POST requests

To better explain my issue, let's consider a simple example: Imagine I have a form that collects information about a user: <form action="#" method="post" id="myform"> <input type="text" name="fname" /> <input type="text" name= ...

Encounter issue with async function in produce using Immer

Having an issue while attempting to create an asynchronous produce with immer. When calling the async function, this error is encountered: Below is my code snippet: import { combineReducers, createStore } from 'redux'; import produce from ' ...

What is the reasoning behind leaving out wwwroot from tsconfig?

Currently, I am working on a TypeScript project using an ASP.NET 5 template in VS.NET 2015. In the scripts/tsconfig.json file that I added, there is a default exclude section which includes: "exclude": [ "node_modules", "wwwroot" ] However, a ...

Is there a way to close the menu in react by clicking anywhere on the

Presently, I have a solution to close my topbar menu that involves clicking the menu icon. However, this method is not satisfactory because it only closes the menu when the icon is clicked. I am looking for a way to make the menu close when any area of th ...

Retrieving embedded documents from Mongoose collections

I am currently facing challenges in caching friends from social media in the user's document. Initially, I attempted to clear out the existing friends cache and replace it with fresh data fetched from the social media platform. However, I encountered ...

NextAuth.js in conjunction with nextjs version 13 presents a unique challenge involving a custom login page redirection loop when using Middleware - specifically a

I am encountering an issue with NextAuth.js in Nextjs version 13 while utilizing a custom login page. Each time I attempt to access /auth/signin, it first redirects to /login, and then loops back to /auth/signin, resulting in a redirection loop. This probl ...

Retrieve all references to child elements in React

I am working on a component that renders dynamic children, and I need to assign a unique ref to each child (e.g. ref={'childID' + index}) After the children have been loaded, I am looking for a way to loop through them and access their refs. Is ...

Attempting to Retrieve Information from a Get Request using Axios

I am attempting to retrieve SQL data from a GET request using axios. My backend is set up with an express server, and the front end is built with React. In my React component, I have a function that contains the axios GET call, which I then invoke within t ...

Leverage NodeJS data within Angular framework

I am working with the following route: Server app.get('/claim/:id', compact.js(['global']), indexController.claim); module.exports.claim=function(req,res){ res.render('claim-note', { title: 'claim', noteId:req. ...

Keep rolling the dice until you hit the target number

Currently, I am in the process of learning JavaScript and one of my projects involves creating a webpage that features two dice images, an input box, and a button. The objective is for users to input a value, click the button, and then see how many rolls i ...

Preventing SQL Injection by properly formatting SQL queries

In my Node.js application, I need to construct an SQL query that looks like the one shown below. SELECT * FROM my_table WHERE my_column IN ['name1','name2'] The user inputs an array, such as ['name1', 'name2'], whic ...

The browser fails to cache images from HttpHandler

I've implemented an IHttpHandler to serve an image from a database, but I'm facing an issue with the browser not caching the image. Here's the relevant code snippet: public void ProcessRequest(HttpContext context) { context.Response.Con ...

Is it possible to retrieve the BrowserWindow by its unique identifier in Electron?

Imagine if the following function is called multiple times to instantiate BrowserWindow, specifically 5 times. let mainWindow; function createWindow() { "use strict"; mainWindow = new BrowserWindow({ height: height, width: width ...

What is the best way to choose CSS class attributes using Mootools and the getStyle()

Seeking to duplicate an object, I am trying to figure out how to retrieve class CSS attributes from Mootools. css: .card { width: 109px; height: 145px; } html: <div id="cards"> <div class="card" id="c0"> <div class="face fron ...

Updating the scope value in AngularJS with an asynchronous response is a crucial task for

I am facing an issue with sharing data between AngularJS controllers. The data is obtained through an http request, but when I try to access it in the controller, it returns null. Strangely, if I manually refresh through the UI, the data becomes available. ...

Can you explain the distinction between employing express.urlencoded() with extended set to true as opposed to setting it to false along with performing manual JSON stringify/parse calls?

Within my NodeJS/Express server, I am faced with the decision of setting extended to either true or false for the urlencoded middleware: app.use(express.urlencoded({ extended: true/false })); I have come to understand that when set to false, it signifies ...

Eliminating blank attributes within an array of objects

I'm currently working on a task that involves creating an array to summarize another array. I've received valuable suggestions from various sources, including this discussion on Stack Overflow. Although the solutions provided are effective, they ...

The transitions in Vue do not seem to be functioning properly when used with router-link and $router

I have the following structure in my App.vue file: <script setup> import { RouterView } from "vue-router"; </script> <template> <RouterView v-slot="{ Component }"> <transition :name="fade" mod ...