Returning json in asp.net webservice - javascript

In my application,we use the prototype1.4.2 in the page.
And we need the tree view which support lazy load(make a ajax request and add the data from the server to the node),then I found the
TafelTree
It is built based on the prototype.
And there is a function:
onopenpopulate:
It will load data from the server according the "openlink" provided by user.
Called after a branch is opened. When it's open, it launch an Ajax
request at the page openlink and send the Ajax response to the user
function. It must return a JSON string representing an array of one or
more TafelTreeBranch. Override setOnOpenPopulate() of TafelTree
But it need the server return pure json data format.
And I have created a webservice this way:
[WebService(Namespace = "http://microsoft.com/webservices/";
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UtilService: WebService {
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string loadData(id) {
//some logic according the id
return "{id:0,name:'xx'}";
}
}
However when I invoke this service use:
http://xxx/UtilService/loadData?id=0
I always get the xml format.
Through google,it seems that I have to set the "content-type" when make the ajax request.
However,in my case,the ajax is sent by the "TafelTree",I can not add extra parameters.
Any idea? or use another prototype based tree?

you can use jquery to do an Ajax call.
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "webServiceUrl/MethodName",
data: "{Id: '" + id + "'}",
dataType: "json",
success: loadSucceeded,
error: loadFailed,
async: true
});
function loadSucceeded(result, status)
{
var data = result.d;
}
function loadFailed(result, status)
{
}
Note that it is not necessarily to return a string, you can return a list of object.
[WebService(Namespace = "http://microsoft.com/webservices/";
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class UtilService: WebService
{
[WebMethod]
public List<string> loadData(id) {
//some logic according the id
return new List<string>(){"data"};
}
}

Related

Trying to make an Ajax call to a web form method and getting an internal server error. I have tried almost all solutions to similar questions

The function getClientData() gets called from one of the anchor tags in a grid's column. The anchor tag has a couple of Data-Tags which are passed to the code behind method. I have to perform some DB operation through these parameters but before that I wanted to make sure if this prototype would work.
This is how the anchor tag looks:
Show
This is my Javascript method:
function getClientData() {
//var dataValue = { "keyData": this.event.target.getAttribute("data-kt"), "valueData": this.event.target.getAttribute("data-kv")};
$.ajax({
type: "GET",
url: "Clients.aspx/GetClientData",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ keyData: this.event.target.getAttribute("data-kt"), valueData: this.event.target.getAttribute("data-kv")}),
dataType: 'json',
error: function (error) {
alert(error.statusText);
},
success: function (result) {
alert("Success: " + result );
}
});
}
I put a break point here and it never gets triggered. This is my web method in the code behind file:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string keyData, string valueData)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}
This is the URL that gets created for the POST request "http://localhost:60825/Clients.aspx/GetClientData?{%22keyData%22:%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22,%22valueData%22:%221p7q9%22}". Please let me know if I am doing something wrong.
I am not sure how you configured routing but based on your API method (code behind) your data should be formatted in following manner:
Method 1:
http://localhost:60825/Clients.aspx/GetClientData?keyData=Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy&valueData=1p7q9
As you can see, instead passing stringified JSON object I am sending data in format of query string where keyData and valueData has corresponding values.
Method 2:
If you prefer to send stringified JSON you can modify your Payload in URL like this:
http://localhost:60825/Clients.aspx/GetClientData?data=%7BkeyData%22%3A%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22%2C%22valueData%22%3A%221p7q9%22%7D
Here I am sending stringified JSON as data parameter in query string. For that purpose your code behing method needs to be like this:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string data)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}

I want to send a class array with ajax but, when I make a request, the request does not reach the backend side

I want to send a class array with ajax but, when I make an ajax request, the request does not reach the backend side. When I sent a string array request. It works great. But If the Array contains a class, it is as if no request is made.
This is my javascript class:
var image_base64_code = [];
class images_base64 {
constructor(id, base64, name) {
this.id = id;
this.base64 = base64;
this.name = name;
}
}
//***************************************
// there are some codes here. For information.
//***************************************
image_base64_code.push(new images_base64(preview_intex, image_base64,name));
This is my ajax request:
$('#Ajax').click(function () {
var ImageJsonText = JSON.stringify({ image_base64_code: image_base64_code});
$.ajax({
url: 'main.aspx/ImageSave',
dataType: 'json',
type: 'POST',
data: ImageJsonText,
traditional: true,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data.d);
}
});
});
});
And my backend function:
[WebMethod]
public static bool ImageSave(RequestImage[] image_base64_code)
{
return 1;
}
public class RequestImage{
public string id;
public string base64;
public string name;
}
Use an object
var image_base64_code = {}; // object.
image_base64_code["images"] = [];
image_base64_code["images"].push( ... ); // add new here.
var ImageJsonText = JSON.stringify(image_base64_code);
JSON.stringify turns objects into strings, so change public static bool ImageSave(RequestImage[] image_base64_code) to accept a string.
public static bool ImageSave(string image_base64_code)
{
return 1;
}
Inside this method you can convert the string to RequestImage objects (deserialize) with built-in javascript deserializer or a library like JSON.NET (Newtonsoft).
Also see: JSON.stringify doesn't work with normal Javascript array

Pass array list back to struts jsp using spring controller?

Working with two projects, one built on struts and one built on spring. I need to be able to make an ajax call to bring back a list of objects so that I can display them in the html for the struts project. Currently the ajax call to the controller is working correctly but I'm having trouble passing back the array list. Any suggestions?
javascript
$.ajax({
url: 'sampleUrl.com/controller/call',
success: function(data) {
//handle returned object
}
}
Controller method
#RequestMapping(value = 'call', method = RequestMethod.Get)
public #ResponseBody List<SampleObject> getSampleObjects(HttpServletRequest request) {
List<SampleObject> sampleList = new ArrayList<SampleObject>();
sampleList.add(new SampleObject());
return sampleList;
}
In the controller I had to add produces="application/json" to the #RequestMapping and before the return create a new Gson and return gson.ToJson() of the list. On my jsp file I it was able to loop through the list normally once the JSON was returned by adding dataType: 'json' to the ajax call.
javascript
$.ajax({
url: 'sampleUrl.com/controller/call',
dataType: 'json',
success: function(data) {
for(var i = 0; i < data.length; i++) {
console.log(data[i]);
}
}
}
Controller:
#RequestMapping(value = 'call', method = RequestMethod.Get, produces="application/json")
public #ResponseBody String getSampleObjects(HttpServletRequest request)
{
List<SampleObject> sampleList = new ArrayList<SampleObject>();
sampleList.add(new SampleObject());
Gson gson = new Gson();
return gson.toJson(sampleList);
}

posting one value using ajax (frontend)

I have a problem with connection frontend-backend. I would like to send one value (radio1Value) from javascript function (on click) using jquery ajax. This function should look like I have wrote?
If yes how should REST look in Java? Should this number that backend have received be in function Get() as a parameter?
$.ajax({
url: "someurl",
method: "post",
data: radio1Value
success: function (response) {
alert("Success!");
}
});
#GET
#Path("/{ship}")
public int Get(){
//check in matrix if number from radiovalue exists
}
After checking I would like to send response from backend to frontend.
After advices here what I have got:
$("th").click(function(){
event.preventDefault();
var radio1Value;
var ifEnoughShips;
radio1Value = $("input[name='stat']:checked").val();
//sending radiovalue
$.ajax({
url : "localhost:8126/ship",
method : "get",
data : radio1Value
success: function (response) {
alert("Success!");
ifEnoudhShips=response;
)};
)};
-------------------------
//REST
public class RestTest{
#GET
#Path("abc/{ship}") //here I am not sure because I dont wanna use path
public int CheckHowMany(#PathParam("ship") Integer ship){
Checker ch1 = new Checker();
int res=ch1.CheckNumber(ship);
return res; //0 if number doesn't exists 1 if it does
}
}
You can use the #PathParam notation.
#GET
#Path("/{ship}")
public int Get(#PathParam("ship") Integer ship){
//check in matrix if number from radiovalue exists
return 1; // Return your success int
}
After you are done in your function you can return anything you want to the frontend. Also when you are using ajax make sure you are calling your backend via a GET method and appending the parameter in the call url.
$.ajax({
url: "someurl",
type: "get", //send it through get method
data: radio1Value,
success: function(response) {
//Do Something
},
error: function(xhr) {
//Do Something to handle error
}
});
I am assuming that url : "someurl", is just a placeholder and will actually contain the correct value. Make sure that you're sending the request to http://yourdomain.top/ship since ship is the URL that your Java framework listens to (#Path("/{ship}")
You need to set the correct method header.
You're sending method : "post", while your Java endpoint expects #Get. The Java framework will probably not match the POST request with a GET action.
You need to receive a parameter that the Java framework you are using will be able to bind it to. Probably you need to do this:
#GET
#Path("/{ship}")
public int Get(string radio1Value) {
//check in matrix if number from radiovalue exists
}
What you need to fix is:
Use the correct URL
Use the correct method (use GET or POST in both the request and action)
Have the action receive a parameter so the value you send is obtainable
Edit: for the onclick part you need to wrap your ajax request into an event using jQuery (since you're using this library). You do this like this:
<button id="execute_on_click">Send request</button>
and in your javascript:
$("#execute_on_click").click(function(event) {
event.preventDefault();
$.ajax({
url: "localhost:8126/ship",
method: "get",
data: radio1Value
success: function (response) {
alert("Success!");
}
});
});

Ajax call to Asp.net Web Method using Jquery

I am using a jquery method, to send information (namely only member identification #) from client side to the server side.
The server side has the traditional Web Method implemented so as to capture data sent and execute SQL queries based on it.
Web-service-method-using-jQuery
However until now I have been returning a single string from the server side back to the client side after the SQL query.
Wondering what would be the best way to return a complicated series of strings... member Identification number, start date, end date, type of member... depending on the type of the member, there can be multiple start dates and end dates.
Should I be looking into XML ?
What about returning even a datatable
$.ajax({
type: "POST",
url: "YourPage.aspx/doSomething",
data: "{'id':'1'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var returnedstring = data.d;
var jsondata = $.parseJSON(data.d);//if you want your data in json
}
});
aspx:
[WebMethod]
public static string doSomething(int id)
{
....
DataTable dt = new DataTable();
dt = anothermethodReturningdt(id)
return JsonConvert.SerializeObject(dt);
}
You can use json.net for serializing .Net objects
Edit
you can also do this
[WebMethod]
public static string doSomething(int id)
{
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
return JsonConvert.SerializeObject(product);
}
The point is you can serialize any type of object, arrays, collections etc and then pass it back to the calling script.

Categories

Resources