alert message not working properly in Ajax web method - javascript

Always getting the 'save error' message when I call the Ajax web method.But I can save the data to database.I couldn't find any errors.How can I get alert 'Saved' .
my web method is
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "paygrade.aspx/SavePayGrade",
data: JSON.stringify({ value: rec, arr: arr }),
success: function (msg) {
console.log(msg.d);
alert(msg.d);
},
error: function (msg) {
alert("Save error");
}
});
[WebMethod]
public static string SavePayGrade(string value, params string[] arr)
{
string res = "";
using (FlairEntities context = new FlairEntities())
{
tblPayGrade obj = new tblPayGrade();
obj.salaryGrade = arr[0];
obj.salary = arr[1];
obj.note = arr[2];
context.tblPayGrades.Add(obj);
context.SaveChanges();
res = "Saved";
}
return res;
}

try following
console.log(msg);
alert(msg);
As you are sending response in string( return res;), you cant use msg.d
You need to use only msg.

Related

Ajax POST returns undefined error from a ashx page

I keep receiving the undefined error. Here is the ajax method.
function testing() {
var data = JSON.stringify(
{
"TestID1": "12345",
"TestID2": "12345",
"TestID3": "12345",
});
$.ajax({
type: "POST",
url: "Test.ashx",
data: data,
//async: false,
//cache: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.ID);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR.status);
alert(textStatus);
alert(errorThrown);
}
});
}
Here is the controller/handler.
public void ProcessRequest(HttpContext context)
{
string jsonString = String.Empty;
HttpContext.Current.Request.InputStream.Position = 0;
using (StreamReader inputStream = new StreamReader(HttpContext.Current.Request.InputStream))
{
jsonString = inputStream.ReadToEnd();
JavaScriptSerializer jSerialize = new JavaScriptSerializer();
var receipt = jSerialize.Deserialize<Receipt>(jsonString);
if (receipt != null)
{
InsertData(receipt.TestID1, receipt.TestID1, receipt.TestID1);
var wrapper = new { ID = receipt.TestID1};
context.Response.Write(JsonConvert.SerializeObject(wrapper));
//context.Response.Write("{ \"data\": [1,2,3] }");
//context.Response.End();
}
}
}
public bool IsReusable
{
get
{
return false;
}
}
Right now I am getting undefined error, but I was getting the "JSON.parse: unexpected end of data at line 1 column 1 of the JSON data" until recently. The data that is being posted is working since the InsertData() function inserts the correct data. I also tried setting the async function in the ajax method to false, but no luck. Also, tried sending specific responses (like the one commented out) and so far none have succeeded.

How to pass multiple file names from input type file to a web method

Hi ihave this input with type file with multiple select enabled.
i need to get the files from the file input and pass it to my webmethod but i'm getting none in my webmethod, i've read that prop return a list, i have this code in jquery
function post_RepAttach(){
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:$('#FileUpload1').prop("files")[0]
}
var files = $('#FileUpload1').prop("files")[0];
alert(files);
$.ajax({
type: 'POST',
contentType: 'application/json',
url: baseUrl + 'Create-OCAP.aspx/post_attachment_rep',
data: JSON.stringify(params),
dataType: 'json',
success: function (data) {
var response = data;
if (typeof callback != 'undefined') {
//hideLoadingGif();
//callback(response);
}
},
error: function (xhr, status, error) {
//hideLoadingGif();
console.log(xhr, status, error);
}
});
}
i have try this $('#FileUpload1').prop("files") remove the [0] but still no luck
and here's my webMethod
[WebMethod]
public static string post_attachment_rep(string Ocap_no, List<string> file_Name)
{
OcapDataAccess ODA = new OcapDataAccess();
bool result;
result = ODA.insert_reports(HttpContext.Current.Request.MapPath("~/OCAP/files/Reports/" + file_Name.ToString()), Ocap_no);
if (result == true)
{
return "1";
}
else
{
return "0";
}
}
but the file_Name count is zero even if i selected files
how can i achive it.
Hope you understand what i mean
var fileNames = $.map( $('#FileUpload1').prop("files"), function(val) { return val.name; });
and params is :
var params = {
Ocap_no:$('#txtOcapNo').val(),
file_Name:fileNames }
}

Passing A Single Objects Into An MVC Controller Method Using jQuery Ajax

I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name

JSON Object always return undefined with AJAX

The JSON Object always return undefined in spite of the object contains data, i check it by using breakpoints in debugging
This is Action method in Controller:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
List<ComViewModel> comms = articleService.GetMoreComments(ArticleID, CommsCount);
return Json( comms );
}
and I also replaced the code in Action method to simple code like that but not work too:
public JsonResult GetMoreComments(int CommsCount, int ArticleID)
{
ComViewModel com = new ComViewModel
{
CommentContent = "cooooooooooontent",
CommentID = 99,
SpamCount = 22
};
return Json( com );
}
This is jQuery code for AJAX:
function GetMoreComments() {
$.ajax({
type: 'GET',
data: { CommsCount: #Model.Comments.Count, ArticleID: #Model.ArticleID },
url: '#Url.Action("GetMoreComments", "Comment")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var JsonParseData = JSON.parse(result);
alert(JsonParseData[0].CommentID)
alert(result[0].CommentID);
alert(result[0]["CommentID"]);
}
});
}
Usually you would have to parse your data if you need to alert it the way you have it. alert(result) should show data. If you need to access array of objects you must parse it first. Here is my example....
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
//PARSE data if you need to access objects
var resultstring = response.replace(',]',']');
var JsonParseData = JSON.parse(resultstring);
alert(JsonParseData[0].address)
});
That is wordpress ajax but its the same concept

Javascript error alert message fired before call to NewStatement is complete

I have the following Javascript code contained on the click event of an upload button where I want to record an xAPI statement. I have put a breakpoint on my Admin/NewStatement method and although it is hitting it the page is always displaying the error message even before I have stepped through the breakpoint. Why is this failing all the time?
var postData = {
'userID': 1,
'verbID': 26,
'objectID':1
};
$.ajax({
type: "GET",
cache: false,
dataType: "json",
url: "/Admin/NewStatement",
data: postData,
success: function (data) {
var json = data;
alert("THIS IS MY JSON" + json);
//tincan.sendStatement(json);
},
error: function (error) {
alert("An Error has occurred during the Creation of this xAPI Statement");
alert(error);
}
});
I have the following method at Admin/NewStatement
public string NewStatement(int userID, int verbID, int objectID)
{
string result;
result = avm.AddStatement(userID, verbID, objectID);
return result;
}
avm.AddStatement refers to my ViewModel code:
public string AddStatement(int userID, int verbID, int objectID)
{
Actor actor = actorRepository.Get(a => a.UserID == userID).FirstOrDefault();
Verb verb = verbRepository.Get(v => v.VerbID == verbID).FirstOrDefault();
StatementObject statementObject = statementObjectRepository.Get(o => o.StatementObjectID == objectID).FirstOrDefault();
Statement newStatement = new Statement();
newStatement.id = System.Guid.NewGuid();
newStatement.ActorID = actor.ActorID;
newStatement.VerbID = verb.VerbID;
newStatement.StatementObjectID = statementObject.StatementObjectID;
this.statementRepository.Add(newStatement);
this.statementRepository.SaveChanges();
JsonSerializerSettings jss = new JsonSerializerSettings();
jss.ObjectCreationHandling = ObjectCreationHandling.Auto;
var json = JsonConvert.SerializeObject(newStatement);
return json.ToString();
}

Categories