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);
});
Related
I'm using Spring MVC and when I do an ajax post call I get a 404. My controller looks like this:
#Controller
#RequestMapping("/mensaje")
public class MensajeController {
public MensajeController() {
super();
}
#ResponseBody
#RequestMapping(value = "/prueba", method = RequestMethod.POST)
public String prueba(#RequestParam("cuerpo") final String cuerpo) {
String b = null;
String a = null;
return b;
}
}
And the ajax call like this:
<script type='text/javascript'>
$(document).ready(function() {
$("#save").click(function(e) {
e.preventDefault();
var myEditor = document.querySelector('#editor');
var html = myEditor.children[0].innerHTML;
$.ajax({
type : "POST",
url : "/Gestion-Practicas/mensaje/prueba",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: {'cuerpo': html},
async: false,
cache: false,
delay: 15,
success: function(data){
alert('success');
},
error: function (xhr) {
alert(xhr.responseText);
}
});
});
});
</script>
The url from where I do the ajax call is:
http://localhost:8080/Gestion-Practicas/mensaje/create.do
The url who appears in the Chrome's console after doing the ajax call is:
http://localhost:8080/Gestion-Practicas/mensaje/prueba
Summarizing, the ajax call never reaches the controller's method and I don't know why
Instead of #RequestParam use #RequestBody
#RequestParam - It's used for query parameters in request url.
#RequestBody - It's a post body payload.
Convert your String cuerpo to a class with property String cuerpo
public class PostBody{
private String cuerpo;
public String getCuerpo(){
return this.cuerpo;
}
public void setCuerpo(String cuerpo){
this.cuerpo = cuerpo;
}
}
Now your line public String prueba(#RequestParam("cuerpo") final String cuerpo)
Updated will look like public String prueba(#RequestBody final PostBody postBody).
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.. ???
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 make play 2.1 controller function execute a captured external url and return json data object to javascript.
First of all InputStream is not opening an external url. errors out saying no protocol
play doesn't like JSONObject as return.
code underway -
Javascript
$.ajax({
url: "/documents/getjsontext/" + talksUrl ,
type: 'GET',
data: "",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){ do_this(data);},
error: function () {alert("Error in Ajax Call");}
});
Route- /documents/acontext/:jsonurl controllers.Class.acontext(jsonurl: String)
public static JSONObject acontext(String jsonurl) {
InputStream is = new URL(jsonurl).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = new JSONObject(jsonText);
return json;
} finally {
is.close();
}
}
first of all you need to add a JsRoutes class. i named it as "myJsRoutes"
public class CommonController extends Controller{
public static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(
Routes.javascriptRouter("myJsRoutes",
routes.javascript.Controller_name.function()
);
}
}
now your js route is defined .and "myJsRoutes" can be further used to call in your scala file as :
myJsRoutes.controllers.Controller_name.function_name().ajax({
//your ajax handlers here
});
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