jquery AJAX get encountering undefined error for valid json response - c#

Team - I am new to jquery and facing issue with a valid json response giving unknown error.
Web based C# MVC and backend database is SQL Server. I am using EF.
If I use the below code:
IQueryable dbResult = dbContext.ParentRecord.Where(row => row.Id ==id).Include(row => row.ChildRecord);
if (dbResult != null) { return Ok(dbResult) }
I have verified that the HTTP Status code is 200, the child records are populated correctly and tested the structure to be a valid json.
However the above encounters error in get function. If I remove the Include - the ParentRecord.ChildRecord is null and the get works.
There are no details available about the error in the xhr object. It enters the error function and response is undefined. (code below)
Please note: I have tried with fail function, datatype: "json",
content-type: "application/json, charset=UTF-8" combinations as well.
$.ajax({
url: _url,
cache: false,
error: function (xhr, status, error) {
alert("error : " + xhr.responseText);
}
}).done(function (data) {
alert("inside " + data);
})
Can anyone point me to the root cause of the error? Or help me get more details on the actual error?

include success for e.g:
cache: false,
success: function(reponse){
//parse your serverside code from resonse
}
I hope this works for you.
plus in javascript/jquery, execution stops at the line where it finds an error in code.
and in your ajax you have a extra 'comma' at the end. I'll Bold it.
.ajax({
url: _url,
cache: false,
error: function (xhr, status, error) {
alert("error : " + xhr.responseText);
}, // <=== there's extra comma here. When comma is mentioned it expects for another parameter as you're passing an object. Remove it.
}).done(function (data) {
alert("inside " + data);
})

The issue is traced to Fluent API in C#. Apparently what I did not realize is that jquery is not only expecting a valid json structure but also validating the json response with the respective class.
Unfortunately jquery get error did not provide me any details about the error, which made it hard to detect the anomaly (esp. for newbies like me)
The validation to class failed in this case as it was expecting a ChildRecord.ParentRecord = null field in the response structure. This anomaly is due to Fluent API navigation property definition where the ChildRecord class has the following declaration:
[ForeignKey("PID")]
public virtual ParentRecord ParentRecord { get; set; }
The work around would be to either explicitly set ChildRecord.ParentRecord as null and ensure it is passed into the response or change the Fluent API definition.
I went with the second option.

Related

Receiving a C# Enum in JavaScript and passing it to a model via Ajax

In my code, I need to receive a string, convert it into a C# enum, and pass the enum to my model. The code is within a for-loop (not shown).
var thisDwm = document.getElementById("dwm_" + i).value;
var urlDwm = "/KnowledgeTransfer/GetDailyWeeklyMonthlyEnum";
var response
$.ajax({
type: 'GET',
url: urlDwm,
data: { 'caseFromJS': thisDwm },
contentType: 'application/json',
success: function (thisResponse) {
response = thisResponse;
}
})
model.MainResponsibilities[i].DailyWeeklyMonthly = response;
Currently the ajax hits my C# controller and returns the correct enum. But when I look at the JavaScript breakpoints, "response" remains undefined and is not set. How do I set the response to a C# enum object that I can pass to my model? Is there some parsing that needs to happen? It seems like I am not receiving anything from the controller at all.
One thing that doesn't help is that type, data, contentType, success, and thisResponse all show as "having a reference error is undefined" in Chrome. Yet the Ajax still works, at least in other places, even though these other methods also show this error.
Thank you for your assistance.
Edit: below is my controller method:
public ObjectModel.Enums.DailyWeeklyMonthly GetDailyWeeklyMonthlyEnum(string caseFromJS)
{
switch (caseFromJS){
case "Daily":
return ObjectModel.Enums.DailyWeeklyMonthly.Daily;
case "Weekly":
return ObjectModel.Enums.DailyWeeklyMonthly.Weekly;
case "Monthly":
return ObjectModel.Enums.DailyWeeklyMonthly.Monthly;
case "Yearly":
return ObjectModel.Enums.DailyWeeklyMonthly.Yearly;
default:
throw new Exception("problem with dailyWeeklyMonthly in KnowledgeTransferController");
With the code you shared, you will get response is not defined error if you are trying to use the response variable before it is defined. In the code snippet you shared, you are initializing it only inside the success callback method of your ajax call.
Remember, ajax is asynchronous. When JavaScript framework executes this line model.MainResponsibilities[i].DailyWeeklyMonthly = response;, which is outside the success callback scope, The ajax call might be still executing/waiting for the response from the server, this means nothing has been set to response, which means the variable response is not initialized!
Access the response for your ajax call only inside the success or done callback.
$.ajax({
type: 'GET',
url: urlDwm,
data: { 'caseFromJS': thisDwm },
contentType: 'application/json',
success: function (thisResponse) {
// safe to use thisResponse in this callback method scope
console.log(thisResponse);
// Assuming model.MainResponsibilities[i] exist
model.MainResponsibilities[i].DailyWeeklyMonthly = thisResponse;
}
})

Advice Needed : MVC4 and Jquery Ajax

Need some advice - doing a project with MVC 4 - used to Forms and Ajax.
Normally I do AJAX calls
My code looks like this :
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "#SiteConfig.BaseUrl/assessment/getquestion",
data: "{'AssessmentId':" + "'" + AssessmentId + "'" + ",'PageNumber':" + PageIndex + "}",
dataType: "json",
beforeSend: function(){
$('#ajaxLoader').show();
$('#questionContainer').hide();
},
success: function (msg) {
var data = msg.d;
},
complete: function(){
$('#ajaxLoader').hide();
$('#questionContainer').show();
},
error:function (request, status, error){
alert(request.responseText);
alert(request);
$('#ajaxLoader').hide();
//window.location = '#SiteConfig.BaseUrl/questionnaire';
}
});
[HttpPost]
public JsonResult GetQuestion(Guid AssessmentId, Int32 PageNumber)
{
... my code
return this.Json(assessmentInfo, JsonRequestBehavior.AllowGet);
}
I keep getting HTML that is returned instead of JSON - it basically just sends me the HTML for the entire page back in the method - what am I doing wrong?
Debugging the problem yields the following result from javascript:
Javascript : SyntaxError: JSON.parse: enexpected character
Furthermore, if I add a breakpoint to the C# GetQuestion method, it is not being hit.
Could this be a URL routing issue?
Also, for the guys that are commenting on Naming conventions : the purpose of this method is to get a question. Naming conventions should follow business logic first, then technical conventions. Calling the method postquestion implies that I am posting a question which doesnt make sense at all.
You should edit your GetQuestion method like this:
[HttpPost]
public JsonResult GetQuestion(Guid AssessmentId, Int32 PageNumber)
{
//my code
return this.Json(myClass,JsonRequestBehavior.AllowGet);
}
Please also get your naming conventions right, if you get something, call the method GET. If you post someting call the method POST.
Ok, I found the problem.
It was indeed a routing problem that caused the issue.

jQuery ajax POST call to ASP.NET Web Service randomly fails

I'm developing a web site for mobile devices that makes ajax calls using jQuery (v 1.7.2) to an ASP.NET (v 2.0.50727) Web Service.
The call works correctly about 95% of the time, but it will randomly fail, returning a 500 internal server error. It fails on the server side before the first line of code is ever executed (the first line writes to the event log).
I haven't seen the call fail using a desktop browser that I remember, but I've seen it fail enough using an iPad. I added
<browserCaps userAgentCacheKeyLength="256">
to the Web Service's web.config file, but that hasn't helped.
javascript:
$.ajax({
type: "POST",
url: serverURL + "/getImage",
data: '{"formURL":"' + url + '", "rowNumber":"'+rowNumber+'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg,textStatus, jqXHR) {
...
}, error: function(xhr, ajaxOptions, thrownError) {
...
}
}).done(function(){
console.log("getImage call is done");
});
Example data passed to the web service:
'{"formURL":"fileName.xml", "rowNumber":"1"}'
c#
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string getImage(string formURL, string rowNumber) {
log("Retrieving image of form " + formURL);
string image = "";
string username = /*retrieve username*/;
string password = /*retrieve password*/;
if (username != null && username != "") {
image = /*code to retrieve the image*/;
}
return image;
}
private void log(string message) {
EvLog.WriteToEventLog(DateTime.Now.ToString("MM:dd:yyyy H:mm:ss:fff") + Environment.NewLine + message, 10);
}
The only thing I've found that has slightly helped me, is when the call fails because the response headers from the Web Service contain "jsonerror: true" though I haven't been able to pinpoint why it would randomly fail.
Any help is appreciated!
Assuming it truly is a JSON error, my first thought is that the data being passed into the parameters is incorrect.
The following line is quoting the contents of variables, which I assume is being loaded from somewhere else in the code:
data: '{"formURL":"' + url + '", "rowNumber":"'+rowNumber+'"}',
Assuming you are already making sure rowNumber is an integer value and wouldn't break it, the likelihood is that the 'url' variable is breaking your JSON format. The easiest way this could happen is if you had an unescaped quote in the filename, especially if it's closing your parameter values earlier than expected when it gets concatenated.
There's always the possibility of the characters not being valid for the charset. Do you have an example data that triggers the failure? The example provided looks nice and clean, so I'm assuming it wasn't one of the error cases.
Don't build your data in this way
data: '{"formURL":"' + url + '", "rowNumber":"'+rowNumber+'"}',
It can cause malformed JSON string.
Instead of this stringify your JavaScript object using JSON.stringify method:
data: JSON.stringify({formUrl: url, rowNumber: rowNumber}),
JSON.stringify will make all job for you to represent your object as valid JSON string.

AJAX error in ASP.NET c#

I am very new to Ajax and ASP.NET MVC. I have a function, that returns back to AJAX and I need to handle the error situation. When everything works fine, then the code is okay. My question is how to handle the error part. Here is what I have:
To return success I have:
var data = new { success = false };
return Json(data, JsonRequestBehavior.AllowGet);
And I need to know what to return when there is an exception or error??
This is my query:
function DoMailPDF() {
$("#submitMail").attr("disabled", true);
var personid = $("#personid").val();
var unitid = $("#unitid").val();
var url = "#(Url.Action("SendEmail", "Report"))";
$.ajax({
url: url,
data: { person: personid , unit:unitid},
success: function () {
// $('input[name=MailSent]').attr('checked', true);
$("#submitMail").removeAttr("disabled");
alert("Email sent!");
},
error: function () {
alert("Email not sent!");
}
});
}
It never comes to the error function. How do I make it go to the error? Any tips and suggestions are most welcome.
You can access your json response object by writing:
$.ajax({
url: url,
data: { person: personid , unit:unitid},
dataType: 'json',
success: function (response) {
if (response.success == false) {
// Error handling
} else {
// Success handling
}
},
error: function () {
alert("Email not sent!");
}
});
As Nick Bork already explained in a comment, the error/success status of a response is determined by the Http status code that is sent down in the header. You can still go the suggested way and inspect the response object and the success property but it is clearly not the proper way when you already have a more powerful and long proven mechanism (the HTTP protocol itself).
.NET will use HTTP 200 (OK) when everything goes according to the code but you can change this behaviour in the Controller by accessing the Reponse object like this, for example:
Response.StatusCode = 500; // or any of the other HTTP "failure" status codes
Any status code in the 4xx or 5xx category will trigger the error() handler specified in the $.ajax(...) call. From there you can of course also inspect the proper status code, the response details and every properties of the XHR object to provide a more meaningful user experience.
HTTP status codes are pretty much set in stone and are not likely to change, that's why they are in my opinion definitely preferrable to a custom made solution...
PS: For a list of HTTP status codes, wikipedia is your friend.

JQuery AJAX, Error Status code: 200, Status Text: parserorro | OK

Here is a funny situation that I'm in.
I'm developing an ASP.Net web site using VS 2008 and .Net Framework 3.5, and I want to use jquery ajax in a test page, the code looks like this:
C# Method
[WebMethod]
public static string test()
{
return "Server Response" ;
}
$(document).ready(function() {
$("#myDiv").click(function() {
$.ajax({
type: "POST",
url: "AjaxTest.aspx/test",
data: "",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function(msg) {
// Replace the div's content with the page
// method's return.
alert(msg.d);
},
error: function(result){
alert("error occured. Status:" + result.status
+ ' --Status Text:' + result.statusText
+ " --Error Result:" + result);
}
});
});
});
So When I use Jquery 1.4.4 like this :
I get : Status 200; Status Text: OK
When I use Jquery 1.5 I get: Status 200; Status Text: Parsererror
So I created a new WebSite in Visual Studio, copy and pased the code there, and it works fine !!!! I can't figure out what causes the problem.
Also I have used methods with parameter, and setting data:"{}", and removing data completely, but nothing seems to work.
I don't know if has to do anything with the DevExpress components that I'm using or not.
I also found a good answer which was working with complete method like this :
complete: function(xhr, status) {
if (status === 'error' || !xhr.responseText) {
alert("Error");
}
else {
var data = xhr.responseText;
alert(data);
//...
}
}
But I don't know if it will work fine or there might be some other problem with this method too. I also don't know how to access response data from here.
But my main concern is finding out what is causing the problem in my website.
UPDATE: Well today in Google Chrome console I noticed some syntax problems with JQuery 1.5
they are as below:
Uncaught SyntaxError: Unexpected token <
jQuery.jQuery.extend.globalEvaljquery.js:593
jQuery.ajaxSetup.converters.text scriptjquery.js:7175
ajaxConvertjquery.js:7074
donejquery.js:6622
jQuery.ajaxTransport.send.callbackjquery.js:7441
The issue isn't so easily solved with fiddler, although it's a great tool.
The issue I think is described here, and for now use the complete event.
there are some issues that will be resolved in jQuery 1.5.1
See:
jQuery returning "parsererror" for ajax request
as it was posted there,
complete: function (xhr, status) {
if (status == 'error' || !xhr.responseText) {
handleError();
}
else {
var data = xhr.responseText;
//...
}
}
Although the interesting thing is - this works for me with jsonp data when I query amazon's service (code amazon was based on some other posting on the net I don't have the ref too) ala:
//resp is simple a placeholder for autocomplete's response which I will need to call on a global scope.
var resp;
var filter;
$(document).ready(function () {
//http://completion.amazon.com/search/complete?method=completion&q=halo&search-alias=videogames&mkt=1&x=updateISSCompletion&noCacheIE=1295031912518
filter = $("#productFilter").autocomplete({
source: function (request, response) {
resp = response;
$.ajax({
url: "http://completion.amazon.com/search/complete",
type: "GET",
cache: false,
dataType: "jsonp",
success: function (data) {
//data[1] contains an array of the elements returned from the service.
//use .map to enumerate through them.
response($.map(data[1], function (item) {
//debugger;
return { label: item, value: item, id: item}
}))
},
data: {
q: request.term,
"search-alias": "videogames",
mkt: "1",
callback: '?'
}
});
},
minLength: 2,
select: function (event, ui) {
//$('#browseNode option:first').attr('selected', 'selected');
alert('selected');
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
});
//this is the method that will be called by the jsonp request
function updateISSCompletion() {
alert('updateiss');
resp(completion[1]);
}
You should use Fiddler - the great web debugging proxy. With its help you can watch for all communication between server and client
Not sure if this will help, but the ajax() API specifies that they have changed the return object for the success() callback function. This is from the jQuery API
As of jQuery 1.5, the success callback function receives a "jqXHR" object (in jQuery 1.4, it received the XMLHttpRequest object). However, since JSONP and cross-domain GET requests do not use XHR, in those cases the jqXHR and textStatus parameters passed to the success callback are undefined.
You can find it here if it helps at all...
jQuery $ajax API
I am running into a similar problem, and am unable to pull the JSON object from any callback functions.
I had this problem too but in PHP When i put in 'remote.php':
`echo $msg`'
problem occurs. When I use json_encode():
echo json_encode($msg);
then everything works.
This is strange, because I get response from server with status 'OK', so then function 'success' should work not 'error'. In 'success' i have only
success: function(res){ console.log(res);}
In my case (when using "jquery 1.9.1"), adding dataType: "json" solved the "parsererror" problem (I didn't specify dataType before and that problem occurred).
I had a similar problem.
I called in AJAX a REST service with POST method and got back :
arguments[0] = status 200 (OK) | arguments[1] = "parseerror" | arguments[2] = "Invalid JSON :"
My server method returned a "void" value. To resolve the problem, I replaced it by a Boolean value for example.

Categories

Resources