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

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.

Related

jquery AJAX get encountering undefined error for valid json response

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.

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.

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.

Problem with jQuery selector and MasterPage

I have a problem with a master page containing a asp:textbox that I'm trying to access using jQuery. I have read lot sof thread regarding this and tried all the different approaches I have seen, but regardless, the end result end up as Undefined.
This is the relevant part of the MasterPage code:
<p><asp:Label ID="Label1" AssociatedControlID="osxinputfrom" runat="server">Navn</asp:Label><asp:TextBox CssClass="osxinputform" ID="osxinputfrom" runat="server"></asp:TextBox></p>
When I click the button, the following code from a jQuery .js file is run:
show: function(d) {
$('#osx-modal-content .osxsubmitbutton').click(function (e) {
e.preventDefault();
if (OSX.validate()){
$('#osx-modal-data').fadeOut(200);
d.container.animate(
{height:80},
500,
function () {
$('#osx-modal-data').html("<h2>Sender...</h2>").fadeIn(250, function () {
$.ajax({
type: "POST",
url: "Default.aspx/GetDate",
data: "{'from':'" + $("#osxinputfrom").val() + "','mailaddress':'" + $("#osxinputmail").val() + "','header':'Test3','message':'Test4'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Meldingen er sendt!</h2>');
$('#osx-modal-data').fadeIn(200);
});
},
error: function(msg){
$('#osx-modal-data').fadeOut(200, function () {
$('#osx-modal-data').html('<h2>Feil oppstod ved sending av melding!</h2>');
$('#osx-modal-data').fadeIn(200);
});
}
});
});
}
);
}
else{
$('#osxinputstatus').fadeOut(250, function () {
$('#osxinputstatus').html('<p id="osxinputstatus">' + OSX.message + '</a>');
$('#osxinputstatus').fadeIn(250);
});
}
});
},
So the problem here is that $("#osxinputfrom").val() evaluated to Undefined. I understand that the masterpage will add some prefix to the ID, so I tried using the ID from the page when it's run that ends up as ct100_osxinputfrom, and I also tried some other hinds that I found while searching like $("#<%=osxinputfrom.ClientID%>"), but it ends up as Undefined in the method that is called from the jQuery ajax method anyway. The third and fourth parameters to the ajay function that is hardcoded as Test3 and Test4 comes fine in the C# backend method.
So my question is simply: How can I rewrite the jQuery selector to fetch the correct value from the textbox? (before I used master pages it worked fine by the way)
Best regards
Daemon
It will be abit slower but why dont you try adding cssclass="bla" to your label and then get it with $('.bla').val(); ?
You should use the attribute ends with selector
Link
it would be $("id$='osxinputfrom'")

Using PageMethods with jQuery

Simply put I want to call public static methods decorated with WebMethod attribute inside my code-behind C# file from jquery.ajax to get some json and other simple stuff (in different functions). But instead I'm getting whole page :'(
I'm not using asp.net AJAX though I'm developing for .NET 3.5 framework and using VS 2008. (There are some restrictions from client)
Please let me know if I can use page-methods with using asp.net ajax or If not what is other simple solution?
After much deliberations I found the problem. I was using jquery's editable plugin. This was source of the problem. When jeditable calls jquery's ajax it sets ajax options like this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
success: function(result, status) {
if (ajaxoptions.dataType == 'html') {
$(self).html(result);
}
self.editing = false;
callback.apply(self, [result, settings]);
if (!$.trim($(self).html())) {
$(self).html(settings.placeholder);
}
},
error: function(xhr, status, error) {
onerror.apply(form, [settings, self, xhr]);
}
};
so it was sending the things as simple html and to use this with page methods we need to setup the things so that it sends as json. So we need to add something to the settings like this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
dataType: 'json', //Data Type
contentType: 'application/json; charset=utf-8', //Content Type
//....other settings
};
So I put two new properties in settings dataType and contentType and changed above to this:
var ajaxoptions = {
type: 'POST',
data: submitdata,
url: settings.target,
dataType: settings.dataType,
contentType: settings.contentType,
//....other settings
};
Now another problem arised :( it was sending data (from submitdata property) as normal query-string which asp.net does not accept with json requests. So I had to use jquery's json plugin and change the way data is sent in ajax using following test on dataType:
if (settings.dataType == "json") {
if ($.toJSON) {
submitdata = $.toJSON(submitdata);
}
}
and it works like breeze!!!
Russ Cam posted this link in response to another question (so if this helps, go up vote his answer ;)):
Using jQuery to directly call ASP.NET AJAX Page Methods
Dave Ward has a series of posts that use jQuery directly with ASP.Net PageMethods, no MS Ajax UpdatePanel required. In particular this post will get you started.
I am not sure but i think WebMethods are accessible only through asp.net AJAX. I may be wrong though, because we dont use it that way at all. We do it in a slightly different way.
We have built a aspx page which accepts all our AJAX requests and passes them to the subsequent methods.
Server side code
If Not (Request("method") Is Nothing) Then
method = Request("method")
username = HttpContext.Current.User.Identity.Name.ToString
Select Case UCase(method)
Case "GETPROJECTS"
Response.ContentType = "text/json"
Response.Write(GetProjects(Request("cid"), Request("status")))
Exit Select
end select
end if
Client Side code [using jquery]
$.ajaxSetup({
error: function(xhr, msg) { alert(xhr, msg) },
type: "POST",
url: "Ajax.aspx",
beforeSend: function() { showLoader(el); },
data: { method: 'GetProjects', cid: "2", status:"open"},
success: function(msg) {
var data = JSON.parse(msg);
alert(data.Message);
},
complete: function() { hideLoader(el); }
});
Hope this helps.

Categories

Resources