Unable to perform updates using queries in my ASP MVC view

I am currently working on updating my script and I am having trouble saving the changes made to my table. When I click the button, the success alert does not appear and there are no error messages either. I have also checked my table to see if the changes were reflected but nothing seems to have happened

Below is the function called when the save button is clicked:

<script>
    var op = '';    
    var op_dif = '';

    $('#btnSave').click(function () {
        op = $('#op').val();        
        op_difficulty = $('#op_difficulty').val();

        alert(op + " " + op_dif); // I can see the value here

        $.post("/Home/UpdateOP", {
            'data': JSON.stringify([{
                'op': op,                
                'opDiff': Op_difficulty
            }])
        }, function (data) {
            var resp = JSON.parse(data);
            if (resp["status"] == "SUCCESS") {
                alert('Data has been successfully updated');
                location.reload();
            }
            else {
                alert('Error!!');
            }
        });
    });
</script>

This is the view where my update query is located:

public string UpdateOpsDiff(operation[] ops)
{
    string res = "";
    foreach(var op in ops)
    {
        string updatetQuery = "update sys.OP_difficulty set op_difficulty = @diff where op = @op;";                
        MySqlCommand updateCommand = new MySqlCommand(updatetQuery);                
        updateCommand.Connection = myConnection;
        updateCommand.Parameters.AddWithValue("@diff", op.op_difficulty);
        updateCommand.Parameters.AddWithValue("@op", op.op);                

        myConnection.Open();
        int updatedRowNum = 0;
        try
        {
            updatedRowNum = updateCommand.ExecuteNonQuery();
        }
        catch(MySqlException)
        {
            updatedRowNum = updateCommand.ExecuteNonQuery();
        }
        finally
        {
            myConnection.Close();
        }

        res = "{status:SUCCESS, updatedRowNum:" + updatedRowNum + "}";
    }

    return res;
}

This is the controller that reads the query from the view:

public string UpdateOp()
        {
            string data = Request.Form["data"];
            IQA sys = new MysqlSys();
            try
            {
                var rows = JsonConvert.DeserializeObject<operation[]>(data);
                return sys.UpdateOpsDiff(rows);
            }
            catch (JsonSerializationException je)
            {
                Console.WriteLine(je.Message);
                return "{status:'DATA_FORMAT_ERROR'}";
            }
        } 

Are there any missing elements that I need to consider? The query works fine with the controller but this time I want to retrieve it from the view.

Any suggestions or comments would be greatly appreciated. Thanks in advance!

Answer №1

If you are utilizing an AJAX callback, it is important to adjust the return type to ActionResult and apply the [HttpPost] attribute to the action method. Additionally, ensure that you use either return Content() or return Json() based on the output type from the UpdateOpsDiff() function (string or object, respectively). Below is a sample configuration:

[HttpPost]
public ActionResult UpdateOp(string data)
{
    IQA sys = new MysqlSys();
    try
    {
        var rows = JsonConvert.DeserializeObject<operation[]>(data);

        string result = sys.UpdateOpsDiff(rows);

        // Use 'Content()' for returning JSON-formatted strings, refer to https://stackoverflow.com/q/9777731
        return Content(result, "application/json"); 
    }
    catch (JsonSerializationException je)
    {
        // handle exception
        return Json(new { status = "DATA_FORMAT_ERROR"});
    }
}

Make sure to set up the AJAX callback to send a JSON string to the mentioned action method:

$('#btnSave').click(function () {
    op = $('#op').val();        
    op_dif = $('#op_difficulty').val();

    var values = { op: op, opDiff: op_dif };

    $.post("/Home/UpdateOP", { data: JSON.stringify(values) }, function (data) {
        var resp = JSON.parse(data);
        if (resp["status"] == "SUCCESS") {
            alert('Data has been successfully updated');
            location.reload();
        }
        else {
            alert('Error!!');
        }
    });
});

Important Note:

The JSON-formatted string should be organized in key-value pairs for proper content delivery, as demonstrated below:

res = string.Format(@"{""status"": ""SUCCESS"", ""updatedRowNum"": ""{0}""}", updatedRowNum);

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

Determining the completion of file unzipping using the npm `unzip` module

Currently, I am utilizing the npm unzip module to extract the content of a zip file. It is important for me to determine when the extraction process is complete and the file has been successfully saved to disk. Here is my code snippet: fs.createReadStrea ...

Potential 'undefined' object detected in Vuex mutation using TypeScript

Currently, I am diving into learning Vue.js alongside Vuex and TypeScript. While working on my application, I encountered an error stating "Object is possibly 'undefined'" within the Vuex Store. The error specifically arises in the "newCard" mut ...

"Convert a date string to a date object using the verbose moment date

I utilized the materialize datepicker to select a date in French format. Now I need to convert this formatted date back to a date object for use in my API. Here's how I attempted to revert the date to a standard format: moment("dimanche 30 juillet 20 ...

The radio button's on click event necessitates a double click

At the heart of my issue are two radio buttons within a form. One triggers a registration form for new users, while the other allows already registered users to sign in. To aid with validation, I've integrated jVal form validation. The problem arises ...

Immediate family members nearby are not an option. We will have to create the form dynamically

On a previous page, there is a form that allows users to input data and define the number of "Attributes" they want to assign to a device by clicking on a button. Users are prompted to specify a name and type for each attribute. If the user selects "Selec ...

Exploring React Native Networking using react-native-router-flux

Hello everyone, I have a quick query. I am looking to assign each Button to a different page. import React, { Component } from 'react'; import { ActivityIndicator, FlatList, Text, View, TouchableOpacity } from 'react-native'; export ...

What is the best practice for naming variables in JavaScript?

Currently, my API is built using PHP Laravel and MySQL, which uses snake_case for field names. I am considering using the same naming convention in client-side JavaScript to make it easier to transfer field names from PHP code to JavaScript code and when m ...

JQuery div not cooperating with other JavaScript/jQuery functions

I used the $(select).append() method to add one div inside another div, but I wanted to close it on click of an image. So I added an image and another $(select).button().click( { $(select).hide() }) to achieve this functionality. However, when clicking t ...

Angular is failing to retrieve data from FS.readFile using promises

My goal is to utilize an Angular service to decide whether to call fs.readFile or fs.writeFile based on the button pressed, in order to explore the interaction between node and angular promises. Although I have managed to read and write files, I am facing ...

Quicker way to apply appendChild

Is there a more efficient method to simplify the process of creating elements from an object fetched via a request? While the current code is functional, it seems overly verbose for what appears to be a straightforward task. async function getJobs() { ...

The placeholder text is not displaying with bullets in Internet Explorer. However, it is functioning correctly in Chrome

I need assistance displaying the placeholder text in IE8 as shown below: "Any relevant reference numbers, such as Direct Debits: - Name of the Branch (if applicable) - What was the original problem - Date the problem occurred " While it appears correct ...

Leverage the exported data from Highcharts Editor to create a fresh React chart

I am currently working on implementing the following workflow Create a chart using the Highcharts Editor tool Export the JSON object from the Editor that represents the chart Utilize the exported JSON to render a new chart After creating a chart through ...

The hidden absolute positioned div disappears once the sticky navbar becomes fixed on the page

Whenever my navbar reaches the top of the screen, the links in the dropdown menu disappear. I followed tutorials and examples from w3schools to build my webpage. Specifically: howto: js_navbar_sticky howto: css_dropdown_navbar This code snippet exempli ...

Exploring the Dependency Injection array in Angular directives

After some deliberation between using chaining or a variable to decide on which convention to follow, I made an interesting observation: //this works angular.module("myApp", []); angular.module('myApp', ['myApp.myD', 'myApp.myD1&a ...

Using JavaScript to modify the -webkit-animation-play-state

Hello, I'm currently facing a challenge in changing my css3 -webkit-animation-play-state property from paused to running upon clicking on another div. Does anyone have any suggestions on how I can achieve this? I believe JavaScript might be the way to ...

Establish a value for the attribute of an HTML tag

Can anyone assist me with setting the attribute value for the following HTML tag using Selenium WebDriver? For example, I need to change 50% to 70% either via JavaScript with WebDriver or a simple WebDriver script. I have tried several options but this pa ...

Error message: The Node.js filtered LS command is missing a ")" after the argument list

I've been working on the learnyounode workshop and I'm stuck on a code issue. After running it through jslint, I received this feedback: Expected ')' to match '(' from line 6 but instead saw '{'. Oddly enough, line ...

Sorting objects with Javascript

users[usernames] = { userName : username, userId : id, userStatuINT : statu, userMobilemi : mobile, }; Console log : console log(JSON stringify(data)); Output : { "Guest-77": {"userName":"Jack","userId": ...

Update the innerHTML content dynamically every 5 seconds with Vue.js

I'm working on a new website and I'd like to spice things up by changing the header text with a random word every 5 seconds. Here's the starting point: const header = document.querySelector('.header') const needs = ['jacket& ...

"Unlocking the Secrets of Extracting Data from Highlighted Cells in Excel with Node.js

I created a script in node.js to extract information from an excel file. Each row contains a highlighted cell (only one). Right now, I am utilizing the xlsx package to access the data. Here is my code snippet for retrieving data from the sheet: var XLSX = ...