0

I am trying to have save changes on my script and I just need an update from my table. So far if I clicked the button, the alert success will not pop and can't see any error either. I also tried to verify to my table if the changes is made but the result is nothing happened

Here is the call function from my save button:

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

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

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

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

My 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_dif);
        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;
}

Controller where it reads the view query:

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'}";
            }
        } 

Is there any missing items that I need. It already working using the query from my controller but this time I need to store my query from my view.

Any suggestions or comments. TIA

Syntax Rommel
  • 932
  • 2
  • 16
  • 40

1 Answers1

0

Since you're using AJAX callback, you should change return type to ActionResult and mark the action method with [HttpPost] attribute, also you should use return Content() or return Json() depending on returned type from UpdateOpsDiff() (string or object, respectively). Here is an example of proper setup:

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

        string result = sys.UpdateOpsDiff(rows);

        // return JSON-formatted string should use 'Content()', see https://stackoverflow.com/q/9777731
        return Content(result, "application/json"); 
    }
    catch (JsonSerializationException je)
    {
        // do something
        return Json(new { status = "DATA_FORMAT_ERROR"});
    }
}

Then set the AJAX callback to pass JSON string into action method mentioned above:

$('#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!!');
        }
    });
});

Note:

The JSON-formatted string should be presented in key-value pairs to be returned as content, as shown in example below:

res = string.Format(@"{""status"": ""SUCCESS"", ""updatedRowNum"": ""{0}""}", updatedRowNum);
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61