using java script and JQuery to show message instead of throwing exception - javascript

How to show message(to inform user if group is added successfully or not) using Javascript and JQuery instead of throwing an erro. Actually this code check if group name already exist in database.
Controller :
[HttpPost]
public int CreateGroup(UserGroup group)
{
return bc.Create(group, user.id);
}
User group class:
UserGroupDalc Dalc = new UserGroupDalc();
public int Create(UserGroup group, int creatorId)
{
if(ByName(group.name) != null) throw new ArgumentException(string.Format("Group name: {0} is already exist.", group.name));
return Dalc.CreateGroup(group, creatorId);
}
User group dalc class:
public int CreateGroup(UserGroup group, int creatorId) {
connection();
com = new SqlCommand("spp_adm_user_group_ins", conn);
com.CommandType = CommandType.StoredProcedure;
com.Parameters.AddWithValue("#name", group.name);
com.Parameters.AddWithValue("#userid", group.creator_id);
conn.Open();
int i = com.ExecuteNonQuery();
if (i >= 1)
{
return 1;
}
else
{
return 0;
}
This js for posting data:
save: function () {
var jForm = $("#form1");
Metronic.blockUI();
GroupAPI.create(jForm.serialize(),
function (data) {
console.log(data);
},
function (error) {
console.log(error);
},
function () { Metronic.unblockUI(); });
}
}
}();
var GroupAPI = function () {
var url_create = "api/usergroup/createGroup";
var url_list = "api/usergroup/list";
return {
create: function (item, done, fail, always) {
var jqxhr = $.post(url_create, item);
jqXhrHandler(jqxhr, done, fail, always);
}
}
}();

Change user group class
UserGroupDalc Dalc = new UserGroupDalc();
public int Create(UserGroup group, int creatorId)
{
if(ByName(group.name) != null){
return 1;
}
return Dalc.CreateGroup(group, creatorId);
}
js
save: function () {
var jForm = $("#form1");
Metronic.blockUI();
GroupAPI.create(jForm.serialize(),
function (data) {
//console.log(data);
if (data == 0)
{
alert('added');
}else if(data == 1){
alert('already exist');
}
},
function (error) {
console.log(error);
},
function () { Metronic.unblockUI(); });
}
}
}();

it will be better to response a 422 status code, in this case indicate validation failed and server is not able to process the request, you can as well put the user readable message in the response response body
The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

Related

mvc asp can't update using query from my view

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
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);

Cloud function returning nil value

I had a freelancer do some work in cloud code however I can no longer contact them due to an argument that occurred. I do not know javascript nor am I familiar with Parse cloud code and I was hoping someone could shed light on whether or not I am calling this function correctly considering it returns as if its parameter was equal to nil although I do believe I am giving it a value. Below is the javascript cloud code function as well as my swift code where I am calling it. For instance it is returning the value (-5).
Parse.Cloud.define("AddFriendRequest", function (request, response) {
var FriendRequest = Parse.Object.extend("FriendsIncoming");
var FRequest = new FriendRequest();
var user = request.user;
var query = new Parse.Query(Parse.User);
query.equalTo("username", request.params.username);
query.find({
success: function (people) {
if(people.length == 0)
{
response.success(-5);
return;
}
var person = people[0];
FRequest.set("OwnerID", user.id);
FRequest.set("TargetFriend", person.id);
FRequest.set("Status", 0);
var query = new Parse.Query("FriendsIncoming");
query.equalTo("OwnerID", user.id);
query.equalTo("TargetFriendID", person.id);
query.find({
success: function (results) {
if (results.length > 0) {
response.success(1);
return;
}
FRequest.save(null, {
success: function (Friend) {
response.success(2);
},
error: function (Friend, error) {
response.error(3);
}
});
response.error(-2);
},
error: function () {
response.error(-1);
}
});
}
,
error: function (Friend, error) {
response.error(-4);
}
});
});
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == NewRequest {
textField.resignFirstResponder()
print(NewRequest)
var name : NSString
name = NewRequest.text!
print(name)
//let parameters : [NSObject : AnyObject]
let params = ["TargetFriendID" : name]
PFCloud.callFunctionInBackground("AddFriendRequest", withParameters: params) { results, error in
if error != nil {
//Your error handling here
} else {
print(results)
}
}
return false
}
return true
}
The parameter from the client is named "TargetFriendID", but the cloud function runs the query on request.params.username.
Either rename the parameter in swift to username, or rename the parameter in the cloud to request.params.TargetFriendID.

JavaScript not getting function returns in Node.js

I have made an IRC bot for purely learning purposes but I have a Minecraft server that I use an API to get the status back as JSON. Now I have made the code and it works but for some reason when I try and use a return on the function so I can get the content it seems to not work?
So I have the two functions below:
function getservers(name) {
if (name == "proxy") {
var Request = unirest.get(proxy);
Request.header('Accept', 'application/json').end(function (response) {
main = response["raw_body"];
data = JSON.parse(main);
console.log(data["motd"]);
return data.motd;
});
} else if (name == "creative") {
var Request = unirest.get(creative);
Request.header('Accept', 'application/json').end(function (response) {
main = response["raw_body"];
data = JSON.parse(main);
return data;
});
} else if (name == "survival") {
var Request = unirest.get(survival);
Request.header('Accept', 'application/json').end(function (response) {
main = response["raw_body"];
data = JSON.parse(main);
return data;
});
}
}
// Main logic:
function parsemessage(msg, to) {
// Execute files
function pu(o,t,f){if(o)throw o;if(f)throw f;bot.say(to,t)}
if (msg.substring(0,1) == pre) {
// Get array
msgs = msg.split(' ');
console.log(msgs[0]);
// Run Login
if (msgs[0] == pre+"help") {
bot.say(to, "Help & Commands can be found here: https://server.dannysmc.com/bots.html");
} else if (msgs[0] == pre+"status") {
// Get status of server, should return online/offline - player count for each server - motd
server = getservers("proxy");
console.log(server);
/*var data = '';
var Request = unirest.get('https://mcapi.us/server/status?ip=185.38.149.35&port=25578');
Request.header('Accept', 'application/json').end(function (response) {
main = response["raw_body"];
data = JSON.parse(main);
});
} else if (msgs[0] == pre+"players") {
// Should return the player list for each server
} else if (msgs[0] == pre+"motd") {
// Should return the message of the day.
} else if (msgs[0] == pre+"ip") {
bot.say(to, "ShinexusUK IP Address: shinexusuk.nitrous.it");
} else if (msgs[0] == pre+"rules") {
}
}
}
The code in the getservers() function works, when I do the
console.log(data["motd"]);
It outputs my servers message of the day. But when I do return
data.motd
(same as data["motd"]?) The code that calls the function is here
server = getservers("proxy");
console.log(server);
Please note this is a node.js code and it contains many files so i can't exactly paste it. So here is the link to the github repo with the whole node application: Here
When the function getservers is called, it makes an asynchronous request and return nothing.
Then the callback is fired with the response of that request as parameter.
Note that the function getservers will end before the end callback of your request is called
(simplified version)
function getservers(name) {
var Request = unirest.get(proxy);
Request.header('Accept', 'application/json').end(function (response) {
main = response["raw_body"];
data = JSON.parse(main);
console.log(data["motd"]);
return data.motd;
});
// nothing returned here
}
What you need is a function callback that will be called after you got the response.
function getservers(name, callback) { // callback added
var Request = unirest.get(proxy);
Request.header('Accept', 'application/json').end(function (response) {
main = response["raw_body"];
data = JSON.parse(main);
console.log(data["motd"]);
callback(data.motd); // fire the callback with the data as parameter
});
// nothing returned here
}
And then you can use your function like this :
getservers("proxy", function(server){
console.log(server);
....
})

Call Controller from .cshtml via getJSON

I have performed this action within a .js file without issue and I am wondering if I have to do something a little different from a .cshtml because I can't seem to find any other reason this is failing. Here is my js within my .cshtml file:
mergeBtn.onclick = function (e) {
e.preventDefault();
var url = '/api/publicpatron/student-no-validation?studentNo=' + studentNo.value;
$.getJSON(url)
.done(function (json) {
if (json.errors) {
toastr.error(json.message, '', { timeOut: 0, extendedTimeOut: 0 })
}
else {
//do something
}
})
.fail(function (jqxhr, textStatus, error) {
var err = textStatus = ', ' + error;
toastr.error(err, '', { timeOut: 0, extendedTimeOut: 0 })
})
}
The code in the controller doesn't seem to be the issue as it never gets to the controller, I have verified I have the controller file name and function name correct in my URL. Any suggestions? Is this not possible from within a .cshtml file??
UPDATE:
Here is the controller:
file name: PublicPatronController
[Authorize(Roles = "my-roles")]
[ActionName("student-no-validation")]
public dynamic IsStudentNoValid([FromUri] string studentNo)
{
dynamic results = new ExpandoObject();
if (studentNo == null)
{
results.error = true;
results.message = "Invalid Student Number";
return results;
}
using (ADRoutineEntities db = new ADRoutineEntities())
{
var exists = db.UserLinkages.Any(x => x.StudentNo == studentNo);
if (!exists)
{
results.errors = true;
results.message = string.Format("Student number {0} does not exist", studentNo);
return results;
}
}
results.ok = true;
return results;
}
UPDATE 2:
It does appear to be related to the controller somehow. I changed the url to a different apicontroller I use elsewhere and it worked fine. The issue seems to be related to the name of the apicontroller. When I change it to the name of an existing apicontroller but keep the actionname the same it works. Why would that be???
You should add the [HttpGet]-attribute to the method on the controller.
Normally WebAPI takes the first part of the methodname to determine what HTTP-verb it should use. In your case, that's not a valid http-method, so you need to explicitly add the attribute.
Another option is to change the method name, eg: GetIsStudentNoValid
You should also return an HttpResponseMessage with a status code instead of a dynamic

MVC- After ajax request Page cannot be refresh

on my view page , i am passing some values to controller by ajax request , on controller action, after checking , redirecting message value to view's controller.Adding message to model and pasisng model to view again with new model value.On second time( postback) model values passed to view as Json but new model value(which is message) cannot be catch by javascript.In my code it is Model.INFO
$.ajax({
type: "POST",
url: '#Url.Action("TeamSaveChanges", "Administrator")',
data: {
ID: '#Model.ID',
doctorID: doctorValue,
nurseID:nurseValue,
driverID:driverValue,
technicianID: technicianValue
},
dataType: "text",
success: function () { alert("#Model.INFO")},
error: function () { alert("Error occured!!!") }
});
Controller
public ActionResult TeamSaveChanges(Guid ID, Guid? doctorID, Guid? nurseID, Guid? driverID, Guid? technicianID)
{
try
{
using (var client = SoapProxyFactory.CreateDSrvGDSoapClient())
{
var emptyTeam = Guid.Empty;
var ambID = client.getAmbulanceIDbyTeamID(ID);
var baseresult = client.checkAmblanceTeamsforDuplicateMembers(ambID, ID);
if (doctorID == emptyTeam && nurseID == emptyTeam && driverID == emptyTeam && technicianID == emptyTeam )
{
var result = client.EditTeamMembers(ID, doctorID, nurseID, driverID, technicianID);
if (result)
throw new Exception("saved");
}
else
{
foreach (var item in baseresult)
{
if(item.DOCTORCODE == doctorID && item.NURSECODE == nurseID && item.DRIVERCODE == driverID && item.TECHNICIANCODE == technicianID)
throw new Exception("The team with Same Members is exist." + "<p>(" + item.TEAMCODE + ")</p>");
}
var result = client.EditTeamMembers(ID, doctorID, nurseID, driverID, technicianID);
if (result)
throw new Exception("saved");
}
catch (Exception exp)
{
string message = exp.Message;
return RedirectToAction("TeamMembers", "Administrator", new { ID = ID, message = message });
}
[OutputCache(Location = System.Web.UI.OutputCacheLocation.None)]
public ActionResult TeamMembers(Guid? ID,string message)
{
try
{
if (!ID.HasValue())
return RedirectToAction("Ambulance");
using (var client = SoapProxyFactory.CreateDSrvALLSoapClient())
{
Guid id = ID.Value;
var clientGD = SoapProxyFactory.CreateDSrvGDSoapClient();
var result = client.GetTeamMembers(id);
result.INFO = message;
if (message != null)
{
result.INFO = message;
return Json(result,JsonRequestBehavior.AllowGet);
}
return View(result);
}
}
This line:
success: function () { alert("#Model.INFO")},
Will only pull in the INFO of the model once because it renders the server value in the client. If you are expecting it to change, then you have to pass the result back to success, and accept the new value as such:
success: function (d) { alert(d); },
To return a value to it you have to return from the action:
return Content("SOMEVAL"); // or PartialView or something that is string data
However, redirecting to action isn't going to return a response to the caller, and may not be handled properly through AJAX, so I'm not 100% sure what the question is...
Why would you use AJAX for this? What is happening is your script is firing a request off to your controller, which sends the response back as data, not a redirect to a new webpage.
Just create a form that POSTs those variables to your controller in typical MVC fashion, you'll get the result you want.

Categories