My jQuery ajax call is failing with an undefined error. My js code looks like this:
$.ajax({
type: "POST",
url: "Data/RealTime.ashx",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
timeout: 15000,
dataFilter: function(data, type) {
alert("RAW DATA: " + data + ", TYPE: "+ type);
return data;
},
error: function(xhr, textStatus, errorThrown) {
alert("FAIL: " + xhr + " " + textStatus + " " + errorThrown);
},
success: function(data) {
alert("SUCCESS");
}
});
My ajax source is a generic ASP.NET handler:
[WebService(Namespace = "http://my.website.com")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class RealTime : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "application/json";
context.Response.Write("{ data: [1,2,3] }");
context.Response.End();
}
public bool IsReusable
{ get { return false; } }
}
Now, if I return an empty object ("{ }") in my handler, the call will succeed. But when I return any other JSON object, the call fails.
The dataFilter handler shows that I am receiving a correct object. Firebug shows the response as expected, and the JSON tab shows that the object is parsed correctly.
So what could be the cause?
[Edit] I should have actually written "when I return any invalid JSON object, the call fails"! :D
You need valid JSON! :)
Change this line:
context.Response.Write("{ data: [1,2,3] }");
To this:
context.Response.Write("{ \"data\": [1,2,3] }");
jQuery 1.4+ doesn't tolerate invalid JSON like it used to (fails silently/in weird ways), so just add the double quotes and you're all set. For a handy tool to test JSON validity, checkout JSONLint: http://www.jsonlint.com/
Related
i get error message [object Object] - error - Internal Server Error when using ajax to call asp.net web method. i wan to get list of object from the server with the ajax.
ajax code
var Packages;
$.ajax({
type: "POST",
async: false,
url: "http://localhost:54954/WebSite/B/Setting/Packages.asmx/GetAllPackage",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
Packages = response.d;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest.toString() + ' - ' + textStatus + ' - ' + errorThrown);
}
});
web method code
public class Package
{
public float PackageId;
public string Code;
public string Name;
}
[WebMethod]
public List<Package> GetAllPackage() {
List<Package> PackageList =new List<Package> {};
for (int i = 1; i <= 100; i++)
{
var temp = new Package();
temp.PackageId = i;
temp.Code = "Code " + i;
temp.Name = "Name" + i;
PackageList.Add(temp);
}
return PackageList;
}
may i know which part i had make the mistake??
Several places.. for starters your WebMethod does not return JSON
I suggest reading this: - What are some simple and fast ways to retieve session variables using javascript or jquery?
Having trouble handling a jQuery AJAX post of FormData to an ASP.net 4 Web service WebMethod.
<input id="ipt_file" type="file" />
<a href='#' onclick="UploadFile();" data-role='button'>Upload</a>
var UploadFile = function () {
var file_object = $('#ipt_file')[0].files[0];
var form_data = new FormData();
form_data.append('job_id', '123456');
form_data.append('job_name', 'xyx');
form_data.append('job_file', file_object);
var xhr_upload = $.ajax({
type: "POST",
headers: { "Cache-Control":"no-cache", "Content-Type":"multipart/form-data" }, // also tried without these
url: "../MyServices.asmx/Upload",
data: form_data,
processData: false,
contentType: false,
dataType: "json",
success: function (msg) {
if (typeof (msg) === "object") {
var _upload = $.parseJSON(msg.d);
alert(_upload.status + ': ' + _upload.msg);
};
}
});
};
public class FileUploadRequest
{
public string job_id { get; set; }
public string job_name { get; set; }
public HttpPostedFile job_file { get; set; }
}
[WebMethod]
public string Upload(FileUploadRequest x)
{
string str_response = string.Empty;
if (x.job_file.ContentLength > 0)
{
str_response = "{\"status\":1,\"msg\":\"" + x.job_id + ", " + x.job_name + ", " + x.job_file.FileName + "\"}";
}
else
{
str_response = "{\"status\":0,\"msg\":\"FAIL"\}";
};
return str_response;
}
Must not be handling the FormData object parameter properly; here I instantiated a custom class, but all I get back from the server is 500 errors (also tried a generic object x). Also tried handling it as HttpRequest object as I've seen on some postings, to no avail. Not concerned about IE 9 incompatibility in this case; just want to see single file upload or at least a FormData object with key/value pairs properly received by an asmx WebMethod.
I did get it to work with the following code, in case anyone wants to see it:
var upload_file = $('#ipt_file')[0].files[0];
var upload_filename = upload_file.name;
var upload_maxsize = 10485760;
var upload_projectname = "test";
var form_data = new FormData();
form_data.append('session_id', this.sessionID());
form_data.append('project_name', upload_projectname);
form_data.append('file_name', upload_filename);
form_data.append('file_size', upload_file.size);
form_data.append('file', upload_file);
if (upload_file.size < upload_maxsize) {
var xhr_upload = $.ajax({
type: "POST",
headers: { 'Cache-Control': 'no-cache' },
url: "../services/upload.ashx",
data: form_data,
processData: false,
contentType: false,
dataType: "json"
}
})
.done(function (xhr_data) {
...
})
.fail(function (jqXHR, textStatus, errorThrown) {
...
})
.always(function () {
...
});
.NET will not allow the multipart/form-data for the content-type:
JSON Hijacking and How ASP.NET AJAX 1.0 Avoids these Attacks
There is a built-in validation layer of protection that ASP.NET
enforces for both GET and POST based ASP.NET AJAX web methods, which
is that regardless of the HTTP verb being used, ASP.NET always
requires that the HTTP Content-Type header is set to the value
application/json. It this content type header is not sent, ASP.NET
AJAX will reject the request on the server.
I am stuck with a critical issue.Can some one please suggest.
I have an .ascx page on which there is a pop up which has an aspnet button which must redirect to another page on click.
I followed the following steps:
On ascx page after opening colorbox, this function is called on clicking the button.
$.ajax({
type: 'POST',
url: "/HomeLoan/ProductConfirmationPop_SaveData.aspx/btnSaveData",
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
alert(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + textStatus + errorThrown);
}
});
On aspx page
[WebMethod]
public static void btnSaveData()
{
function sahil();//this function i want to call after this function is being called
}
I am getting Json parse error.
I removed dataType:json and made it return a html/text then it is giving me object object error.
This would propably be a lot easier if you could use a simple html form, add the value to a hidden input when onsubmit is triggered, and post it to a webservice which will redirect for you.
Anyway:
You need to decorate your btnSaveData method with another attribute and change the return type / parameter to string (or any other type that suits your needs):
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public static string btnSaveData(string color)
{
// do sth with the color
return "/SaveSuccess.aspx";
}
And in js:
// retrieve the color as a string (this is up to you - I don't know what sort of ColorPicker you're using, so this is a placeholder)
function saveColor()
{
var color = $('#myColorPicker').color.toString();
// create the data for the webmethod,
// the parameternames have to be the same as they are on the WebMethod
var colorData = "{ color:'" + color + "'}";
$.ajax({
type: 'POST',
url: "/HomeLoan/ProductConfirmationPop_SaveData.aspx/btnSaveData",
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: colorData,
success: function (response) {
window.location.href = response.d; // redirect on success
},
error: function (response, text, error)
{
alert(response + ' ' + text + ' ' + error);
}
});
Hope this helps and works!
This code worked fine in mvc2, but moving back to traditional ASPX (because of Sharepoint 2010). I am encountering errors. Can anyone tell me what I am doing wrong for this framework?
This ajax call is in the $.ready
$.ajax({
type: "POST",
dataType: "json",
data: 'siteName=a&siteUrl=b',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
code behind
[WebMethod]
public static string DoesNameUrlExist(string siteName, string siteUrl)
{
//do something
return someString;
}
I get an error everytime.
You need to send JSON to the service and indicate that you're doing so via the contentType header:
$.ajax({
type: "POST",
contentType: 'application/json',
data: '{"siteName":"a","siteUrl":"b"}',
url: 'Wizard.aspx/DoesNameUrlExist',
beforeSend: function () { alert("before send"); },
complete: function () { alert("complete"); },
success: function (data) { alert("success"); },
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
More info here: http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
Also, if you're using jQuery 1.4, you can drop the dataType. jQuery will infer JSON automatically based on the response's Content-Type header.
Ajax calls in jQuery will always give you an error if you declare your contentType as json and the response content type is anything but json. If the response from your WebMethod has something different (such as html or text), you'll always get that error. You can set that response type on your method like this:
[WebMethod]
[ScriptMethod (UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public static string DoesNameUrlExist(string siteName, string siteUrl)
Outside of WebMethods this can also be achieved like this:
Response.ContentType = "application/json";
I am trying to make a jquery ajax call to a static method on the codebehind file. The problem is that ArtistManager injected by Spring is not static and I cannot use it in the static webmethod. I am looking for any ideas on how to implement this
ArtistList.aspx
$(document).ready(function () {
$("#Result").click(function () {
$.ajax({
type: "POST",
url: "ArtistList.aspx/GetArtists",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#Result").text(msg.d);
alert("Success: " + msg.d);
},
error: function (msg) {
// Replace the div's content with the page method's return.
$("#Result").text(msg.d);
alert("Error: " + msg.d);
}
});
});
});
ArtistList.aspx.cs
private IArtistManager artistManager;
public IArtistManager ArtistManager
{
set { this.artistManager = value; }
get { return artistManager; }
}
protected long rowCount = 0;
.
.
.
[WebMethod]
public static IList<App.Data.BusinessObjects.Artist> GetArtists()
{
//return ArtistManager.GetAll("Name", "ASC", 1, 100, out rowCount);
}
Assuming a single context, in which an IArtistManager is configured named artistManager:
using Spring.Context.Support;
// ...
[WebMethod]
public static IList<App.Data.BusinessObjects.Artist> GetArtists()
{
IApplicationContext context = ContextRegistry.GetContext(); // get the application context
IArtistManager mngr = (IArtistManager)context.GetObject("artistManager"); // get the object
return mngr.GetAll("Name", "ASC", 1, 100, out rowCount);
}
Note that this code won't compile either, since rowCount is an instance member, similar to artistManager in your question.
Don't know about spring, but I am sure it has something like structure map.
ObjectFactory.GetInstance<IAristManager>.GetAll();