calling c# webservice using jquery ajax - javascript

When i try to call c# webservice using jquery ajax I get Internal Server Error and if i call it from browser directly i get the following error
System.InvalidOperationException: newDonor Web Service method name is not valid.
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
the following is the web method
[WebMethod]
public void newDonor(localDonor donor)
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
CloudTable table = tableClient.GetTableReference("donors");
table.CreateIfNotExists();
Donor newDonor = new Donor(donor.FullName, donor.Mobile);
TableOperation insertOperation = TableOperation.Insert(newDonor);
table.Execute(insertOperation);}
the following is the ajax method of jquery
var userInput = {
FullName: "Lakshman NEW",
Mobile: "1122004455"
};
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "addDonor.asmx/newDonor",
data: JSON.stringify(userInput),
dataType: "json",
error: function (error) {
alert(error.toString());
}
});
What could be the mistake, everything seems to be fine.. ???

Related

Sending JSON string to my backend code to add it to my DB but it's not adding anything

I've been stuck on this problem for a good bit
I'm trying to add an object to my database through jQuery/AJAX. Apparently, there are no errors but it's not adding anything to my DB.
This is my JS/JQuery code:
var student = new Object();
student.Name = $("#txtNameAdd").val();
student.Age = $("#txtAgeAdd").val();
student.Email = $("#txtEmailAdd").val();
$.ajax({
type: "POST",
url: "Default.aspx/AddStudent",
data: "{'studentJSONString':'" + JSON.stringify(student) + "'}",
success: function (response) {
$("#lblSuccessAdd").text("Success!");
$("#lblSuccessAdd").css("display", "block");
},
error: function (response) {
alert(response.responseJSON);
}
});
My JS code points towards this code I have in my Default.aspx page code:
[WebMethod]
public static void AddStudent(string studentJSONString)
{
JavaScriptSerializer converter = new JavaScriptSerializer();
Student a = converter.Deserialize<Student>(studentJSONString);
WebMethods.AddStudent(a);
}
Which points to this code in my WebMethods.cs class
[WebMethod]
public static void AddStudent(Student student)
{
MasterStudent master = new MasterStudent();
master.AddStudent(student);
}
And finally that goes to my class library and finishes with this method in MasterStudent:
public void AddStudent(Student student)
{
if (string.IsNullOrWhiteSpace(student.Name))
{
throw new Exception("There's no name");
}
if (string.IsNullOrWhiteSpace(student.Email))
{
throw new Exception("There's no email");
}
using (studentEntities model = new studentEntities())
{
model.student.Add(student);
model.SaveChanges();
}
}
I run the code and the Console doesn't log any problems but it also doesn't do anything.
I have run very similar code on a Forms application with no problems so I'm kind of in a pickle right now. Does anyone know why it keeps failing?
Have you tried attaching a debugger to it and verifying that the student object is not null prior to model.SaveChanges() ?
Try debugging and verifying that the student string is being converted to an actual Student object first.
If it is, then try profiling the DB and validate any commands issued.
So I actually did find a solution shortly after posting my question, I changed my JQuery AJAX call to look like this:
$.ajax({
type: "POST",
url: "Default.aspx/AddStudent",
data: "{'studentJSONString':'" + JSON.stringify(student) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#lblSuccessAdd").text("Success!");
$("#lblSuccessAdd").css("display", "block");
},
error: function (response) {
$("#lblErrorAdd").text(response.responseJSON.Message);
$("#lblErrorAdd").css("display", "block");
}
});
And it actually works now! so either the dataType or contentType were very important for what I was trying to do
Thanks for your answers everybody
var student = new Object();
student.Name = $("#txtNameAdd").val();
student.Age = $("#txtAgeAdd").val();
student.Email = $("#txtEmailAdd").val();
$.ajax({
type: "POST",
url: "Default.aspx/AddStudent",
data: student,
success: function (response) {
$("#lblSuccessAdd").text("Success!");
$("#lblSuccessAdd").css("display", "block");
},
error: function (response) {
alert(response.responseJSON);
}
});
Then you can to point to this WebMethod.
[WebMethod]
public static void AddStudent(Student student)
{
MasterStudent master = new MasterStudent();
master.AddStudent(student);
}
Try this.

Receiving Undefined Information from web service

Here is the Code for my WebService,
[WebService(Namespace = "http://mydomain.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class VBRService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string callJson(string x)
{
return "Worked =" + x;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void callJson2(string x, string callback)
{
StringBuilder sb = new StringBuilder();
sb.Append(callback + "(");
var json = new JavaScriptSerializer().Serialize("aString");
sb.Append(json);
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
}
Here is the JavaScript Code,
$.ajax({
crossDomain: true,
contentType: "application/json; charset=utf-8",
url: "http://localhost:31310/VBRService.asmx/callJson2",
data: { x:"someDataPassed", callback:onDataReceived },
dataType: "jsonp",
error: function (data){
alert(data.d);
}
});
function onDataReceived(data) {
alert(data.d);
// ^ Here is where the data comes back as undefined.
}
The JavaScript fires off and hits the onDataReceived function. I'm not really sure as to if this is how you respond from a webService to perform a callback as there are not any examples of server side code to call to.
However, the object data is undefined when it calls back. This is cross domain by the way so that's why I'm trying to figure out how to use jsonp.
Thanks in advance!
This is the correct way to send a jsonp request. You're overcomplicating it.
$.ajax({
url: "http://localhost:31310/VBRService.asmx/callJson2?callback=?",
dataType: "jsonp",
data: {x: "somedata"},
success: function(data){
console.log(data);
}
});
Alternative:
$.getJSON("http://localhost:31310/VBRService.asmx/callJson2?callback=?",{x: "somedata"},function(data){
console.log(data);
});

Web service Spring ajax call

I'm trying to call a web service with ajax. The service is up, and it can shows the result on the RestClient on firefox, but, in mi application call, gives me Status error "Pending".
This is my simple web service.
#Controller
#RequestMapping("/hello")
public class HelloWs {
#RequestMapping(value= "/helloWorld", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public #ResponseBody String HelloWorld() {
return "Hello Worldssss¡¡";
}
And this is my ajax call.
function hellowsfunction() {
$.ajax({
type: "GET",
url:"http://localhost:8080/ehCS-ui/rest/hello/helloWorld",
crossDomain: true,
dataType: "JSON",
headers : {Accept : "applicationjson","Access-Control-Allow-Origin" : "*"},
success: function(msg) {
var returnedData = jQuery.parseJSON(msg);
$("#lblResult")
.text(result)
.slideUp("hide", function() { $(this).slideDown("slow") });
},
error: function (e) {
$("#lblResult").removeClass("loading");
alert('failed:'+e);
console.log(e);
}
});
what is wrong? Ideas?¿ please help.
Thanks
Your #RequestMapping is wrong... you should not map based on Accept header like this. Instead you should use produces parameter.
#RequestMapping(value="/helloWorld", method=RequestMethod.GET,
produces={"application/xml", "application/json"})
Also your header in the JS is incorrect. Just remove their specification completely.

How to pass string value from javascript to function in ASHX

I'm used this code to pass parameter from jQuery to ASHX, actually I want to upload file using Uploadify Plugin and send Parameter named 'Id' to ASHX
function CallHandler() {
$.ajax({
url: "PIU.ashx/MyMethod",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { 'Id': '10000' },
responseType: "json",
success: OnComplete,
error: OnFail
});
return false;
}
function OnComplete(result) {
alert(result);
}
function OnFail(result) {
alert('Request Failed');
}
and this ASHX code:
public void ProcessRequest(HttpContext context)
{
var employee = Convert.ToInt32(context.Request["Id"]);
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
string serEmployee = javaScriptSerializer.Serialize(employee);
context.Response.ContentType = "text/html/plain";
context.Response.Write(serEmployee);
parent MyParent = (parent)context.Session["mahdZNUparent"];
//the file data is the file that posted by Uploadify plugin
HttpPostedFile PostedFile = context.Request.Files["Filedata"];
string FileName = PostedFile.FileName; // whene i comment this line, the code works
// properly, but when uncomment this line, the code get to 'Request Failed'
}
public bool IsReusable
{
get
{
return false;
}
}
how can I Solve this problem!!!!!!!
You may want to take a loot at this: http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/
And this one too: Using jQuery for AJAX with ASP.NET Webforms

MVC 4 APIController not receiving POST data

Sure this had been dealt with many times... but.. just cant see what im doing wrong!
This is a simple JS script that Posts data back to ApiController.
function WebCall(url,parameterObject, callBackFunction) {
this.callbackfunction = callBackFunction;
this.parameterObject = parameterObject;
this.url = url;
self = this;
this.GetData = function () {
//self = this;
$.ajax({
//dataType: "json",
type: "POST",
url: self.url,
data: JSON.stringify(self.parameterObject),
contentType: "application/json;charset=utf-8",
success: function (data) {
self.callbackfunction.call(this, data);
},//self.GotData,
error: function (xhRequest, ErrorText, thrownError)
{
alert("error : " + ErrorText)
},
complete: function () {},
})
}
}
The data being sent (parameterObject) is simply
var postData = {
clientId: id
}
The c# code in the controller is :
public class ClientPostObject
{
public string clientId;
}
public class ClientDetailController : ApiController
{
[HttpPost]
public ClientDetailWidgetData GetClient(ClientPostObject clientObject)
{
return new ClientModel().GetClientDetail(clientObject.clientId);
}
}
In Google chrome developer tools, the XHR is showinf 'form Data' as clientId:A0001 - so that looks ok?
No matter what I try (and I'be been through many suggestions on the web), the post data is not there.
Sure its something simple.... Thanks in advance.
Unless you're planning on using a full-on form to submit to this method at some other point, it doesn't really make sense to ask the model binder to attempt to bind to a complex type when you're just using one property. Change your method signature to:
[HttpPost]
public ClientDetailWidgetData GetClient(int clientId) // or whatever type clientId represents
{
return new ClientModel().GetClientDetail(clientId);
}
I'd also recommend adding Glimpse at some point (http://getglimpse.com/) so that you can see how the model binding and/or routing of your app works.
Try to ditch contentType and don't stringify data:
$.ajax({
type: "POST",
url: self.url,
data: self.parameterObject,
success: function (data) {...},
...
});

Categories

Resources