The configurations to my asmx page are as follows
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using Time.CSharpclasses;
/// <summary>
/// Summary description for LiquidityMonthAjax
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[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 LiquidityMonthAjax : System.Web.Services.WebService
On the client side my response is mysteriously coming back with a different type of item I have never seen before, even though I use the same methods to parse it to JSON.
#document
<string xmlns="tempuri.org">
["Presbyterian Health","Devon","LABS","Self-Pay","Sagamore"]
</string>
I don't understand what's different. I usually get my json from .d.
Using Asp 4
There must be some dependency I'm missing but I dont know if it is client side or server.
[WebMethod]
public string getUniqueFinClass()
{
DataTable dt = ExcelManager.CreateDataTableFromSql(new XMLManager("liquiditymonth.xml").getReport(Xmls[6]));
var r = from row in dt.AsEnumerable() select (string)row["FinancialClass"];
return DictToJSON.serializeJSONObject(r.ToList());
}
The former is the method that gives me problems the serializeJSONObject method
follows:
public static String serializeJSONObject(Object items)
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
serializer.MaxJsonLength = 2147483644;
return serializer.Serialize(items);
}
I really don't think is that method that's the problem because I've used it a hundred times before with success.
Some versions of the .Net platform return d some do not. Try putting something like this in your code:
var data = (response.hasOwnProperty("d")) ? d : response;
Now data contains the response no matter which version of .Net is being used making your client code more robust.
Dave Ward did a blog on this: http://encosia.com/never-worry-about-asp-net-ajaxs-d-again/
Apparently the problem was client side. I forgot to stringify my object so jquery politely wrapped the aguments up in the url query instead. A function of ASP.net says that if the request is not JSON then the response is XML forsaking the request header type and any attempt of the programmer to make it JSON.
Refer to this link under JSON,Objects and Strings: oh my!
http://encosia.com/3-mistakes-to-avoid-when-using-jquery-with-aspnet-ajax/
Related
I have recently discovered chartJS and adore the design. Now I am struggling to get the data dynamic.
My goal is to retrieve data from the postgresDB in my Java Controller and route it to the javascript file to display it in the jsp files. But I don't know how to access the data in the java files out of the javascripts.
Thank you for your time and helping me!
Yours, Janick
Edit:
In the controller I've tried to put a JSON Object as String in the request:
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
JsonObject json = new JsonObject();
json.addProperty("20210701",100.00);
json.addProperty("20210702",101.00);
json.addProperty("20210703",102.00);
String strJson = json.toString();
request.setAttribute("json",strJson);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
and in the Javascript file:
const urlSearchParams = new URLSearchParams(window.location.search);
const params = Object.fromEntries(urlSearchParams.entries());
console.log(params);
Unfortunately I do not know how to do this with Java? But in .NET with ASP you can use Ajax or PageMethods to call a server-side web service or web method and query the database and then use Chart.js dynamically. You can of course control the web service with parameters and in the return object you can write arrays or lists for the result and then use a callback method to make the chart dynamic.
I have created a spring application and i am also using webservices.
I want to use jsonp callback function for which the media type should be {"application/x-javascript"}. This seems not to be working. it is returning json object and not javascript.
Here is the code..
#RequestMapping(value = "widget", method = RequestMethod.GET)
#Produces({"application/x-javascript"})
public #ResponseBody JSONWithPadding displayWidgetPage(Model model, HttpServletResponse
response,HttpServletRequest request)
{
String callback = request.getParameter("callback");
PointsInfo pointsInfo =new PointsInfo();
pointsInfo.setUsername("json");
return new JSONWithPadding(pointsInfo,callback);
}
I checked using the rest client...
It says the content type is : Content-Type: application/json;charset=UTF-8
It has to be : Content-Type: application/javascript;charset=UTF-8
I think that you're mixing Jersey's #Produces and JSONWithPadding with Spring MVC, and Jersey's #Produces will not take any effect there.
If you're looking for a way to implement JSON-P with Spring MVC only, take a look at
http://patrickgrimard.com/2010/07/28/tutorial-implementing-a-servlet-filter-for-jsonp-callback-with-springs-delegatingfilterproxy/
or if you're able to upgrade to the version 4.1 or above
http://spring.io/blog/2014/07/28/spring-framework-4-1-spring-mvc-improvements
You are using a Spring version older than 3.1.1.RELEASE. If you are looking to set your response's media type, it should be in the RequestMapping annotation like this:
#RequestMapping(value = "/list/rideLogs/{rideId}", method = RequestMethod.POST,
produces = YOUR_MEDIA_TYPE)
That being said application/javascript isn't a valid media type for Spring. You can refer to values of MediaType class.
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/http/MediaType.html
I have created a Web API that will receive Input from Jquery and will use this input to dynamically alter a string that's stored in a resource file.
This String happens to be an almost complete piece of vbscript code that I plan on passing back down to my website.
My problem is that the resource automatically "stringifies" the Code and the output is flooded with escape characters which renders it completly unusable as actual code.
Is there a way to store the code in a way that makes escape strings unneccesary while still enabling me to alter it similiar to "if it were a string" and pass it down to my Website?
The goal is to then use Jquery/Javascript to make this code into an actual vbscript file and let the user download it.
As per request here some Code.
public string GetDeployment(Deployment deployment)
{
string vbs = Resource1.vbs;
vbs = vbs.Replace("%environment%", deployment.SystemKind);
vbs = vbs.Replace("%platform%", deployment.PlatformKind);
vbs = vbs.Replace("%application%", deployment.ApplicationName);
vbs = vbs.Replace("%config", deployment.ConfigInfix ?? "Null");
vbs = vbs.Replace("%subFolder%", deployment.subFolder ?? "Null");
return vbs;
}
This method alters the vbscript depending on the Input. The API itself receives a JSON with Data for all the properties of deployment.
public class DeploymentController : ApiController
{
private DeploymentRepository DeploymentRepository;
public DeploymentController()
{
DeploymentRepository = new DeploymentRepository();
}
[HttpPost]
public string Post([FromBody]Deployment deployment)
{
return DeploymentRepository.GetDeployment(deployment);
}
}
So let's say you're trying to do a jquery ajax request, something like:
$.ajax({
...
url: http://other-website.com
...
})
I understand that because of the same-origin principle, this request will fail because the URL is an external domain.
However I've heard that GetJSON() does not obey this principle and can send asynchronous get requests to external servers using JSONP and an appended URL.
My question is: is it possible to use GetJSON() to retrieve all the HTML from an external name as a single string within a JSON object? If it doesn't do so by default, is there any way I can force / trick it into doing so?
Yes, you can request html from a remote location, however you must use a proxy to do so. One publicly available proxy is YQL.
http://jsfiddle.net/BKJWu/
var query = 'SELECT * FROM html WHERE url="http://mattgemmell.com/2008/12/08/what-have-you-tried/" and xpath="//h1" and class="entry-title"';
var url = "http://query.yahooapis.com/v1/public/yql?q=" + query + "&format=json&callback=??";
$.getJSON(url,function(data){
alert(data.query.results.h1.content);
})
You could of course build your own on your server that returns plain html rather than json.
The answer is no, you cannot trick it or force it to load html from an external source. GetJSON only works on servers that serve JSONP, and only valid JSON objects are able to be read.
You can retrieve any JSON object that you have access to with GetJSON. Here is an example with Razor an MVC Controller.
jQuery Code
$(function () {
$.getJSON('#Url.Action("GetColorsJson", "Json")', function (jsonData) {
var css = new customContentJs.css.apply(jsonData);
});
});
Controller Code
using System.Web.Mvc;
using DAL;
using Newtonsoft.Json;
public class JsonController : Controller
{
private readonly CustomContentContext _db = new CustomContentContext();
/// <summary>
/// Return a json serialized object of user saved colors
/// </summary>
/// <returns></returns>
public string GetColorsJson()
{
return JsonConvert.SerializeObject(_db.Site.Include("Colors"));
}
}
I am building a SPA and are using BreezeJS for data management. Now I want to be able to set processed data on my model class that are not present in the database and send it up the client. The problem is that breeze also ignores these properties.
public class MyModel{
public int Id{get; set;}
public string Name{get; set;}
public string ProcessedData{get; set;}
}
...
Ignore(model=> model.ProcessedData);
I realize that Breeze uses the same metadata as my datacontext, but there should be a way to override it.
The ignored properties is sent by the controller as json, it's just a matter of making breeze parse it as I need it to.
I haven't confirmed this but I think that if your are sure that the data is being returned from the server then you can add "unmapped" properties with the correct names to the Breeze client and it will materialize these as well. See the "unmapped" discussion here: http://www.breezejs.com/documentation/extending-entities .
Or you could try this ( I haven't actually tested this) AFTER the metadata has already been returned.
var dp = new breeze.DataProperty( {
nameOnServer: "ProcessedData",
dataType: "String",
isUnmapped: true
});
myEntityManager.metadataStore.getEntityType("MyModel").addProperty(dp);
and then try your query.
Note: only "unmapped" properties can be added to the EntityType after the EntityType has been itself added to a MetadataStore.