How to get JSON file from server? (ASP.NET) - javascript

I have a simple web application that operates with a set of words using JS. In order to test the main code I just put a needed data in a variable in my script.
CONST WORDS = [
["Computer", "Ordinateur", "https://www.lifewire.com/thmb/nNDKywb8qvKzhxelVAR95sEHBj0=/768x0/filters:no_upscale():max_bytes(150000):strip_icc()/Acer-aspire-x3300-5804ec185f9b5805c2b6b9e6.jpg"],
["Function", "Fonction", "http://latex-cookbook.net/media/cookbook/examples/PNG/function-plot.png"],
["Server", "Serveur", "https://effortz.com/wp-content/uploads/dedicated-hosting-server.png"]
]
Now I need to build a database (already done) and get such data from the server. So, the question is how do I acquire JSON file from the server using JS? I know how to make GET requests, but what should I do on the server to make it response? (or may be there is an easier way to get this data in JS, considering that I already got it from DB and can easy display on the webpage).
Here is a backend code
namespace LFrench
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<Words> WordsSet = Words.GetWords("Business");//recieving from DB a set of words, that i need to use in JS
}
}
}

The thing you need to understand is the flow of your request. if you strictly want to do it in the Page_Loag event then I suppose you will have to make a method in your Javascript that will actually accept your data as parameter and then call the Javascript method from the C# CodeBehind Assuming that the data in the parameter is in JSON format. This method works but is not very efficient.
Other way is, in your JQuery side, you should make an ajax call to a WebMethod of yours in the CodeBehind that will actually send the response in JSON format. This is cleaner way of doing it.
Your JQuery should look like:
$(document).ready(function(){
$.ajax({
method: "GET", accept: "application/json; charset=utf-8;",
url: 'MyPage.aspx/GetDataFromDB', success: function(data){
console.log('Success Response in JSON: ' + data.d); // notice *data.d*, Calling from WebMethods returns the object encoded in the .d property of the object.
}, fail: function(err){
console.log(err);
}
});
});
And your CodeBehind should look like:
[WebMethod]
public static string GetDataFromDB()
{
var myData = YourDbCall(); // Some method to retrieve data from database
var body = new
{
Firstname = myData.Firstname,
Lastname = myData.Lastname,
Email = myData.Email,
// Any Other Information
};
var json = JsonConvert.SerializeObject(body);
return json;
}
EDIT
Here is how your Word Set will be sent back as JSON:
[WebMethod]
public static string GetDataFromDB()
{
List<Words> WordsSet = Words.GetWords("Business");
return JsonConvert.SerializeObject(WordsSet);
}
Make sure you have installed Newtonsoft.JSON from Nuget Package Manager Console. if not you can Open Package Manager Console and run this command:
PM> Install-Package Newtonsoft.Json

You need to make json return type method on serverside. Than call it from your get method and do your method on serverside and fill the List and return that list by converting JSON format.

Related

How to create ajersey restful method that can accept three arrays of strings

I have been trying to send string arrays to a restful services without any luck. I have written this
#GET
#Produces(MediaType.TEXT_PLAIN)
public String getBackgroundImages(#QueryParam("missions") String[] missions,
#QueryParam("objects")String[] objects,
#QueryParam("dates")String[] dates) {
........
return generateTxt();
}
on the javascript side I have this
var missions = new Array("One", "Two");
var objects = new Array("objOne" ,"objTwo");
var dates = new Array("1967-11-07","1977-12-17");
$.ajax({
url: "myurl/rest/UploadBackgroundFile/",
data: {'missions':missions,'objects':objects,'dates':dates},
success: function (data) {
arr = JSON.parse(data);
$('.container-fluid').css('background-image','url('+arr[0].img+')');
}
});
my problem is that this is not working and I am getting this exception
org.apache.catalina.core.ApplicationContext.log StandardWrapper.Throwable
org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
[[FATAL] No injection source found for a parameter of type
public java.lang.String UploadBackgroundFile.getBackgroundImages(java.lang.String[],java.lang.String[],java.lang.String[])
if I change the parameters to normal string and send strings from the javascript side than the method will work.
so the question is how to send and receive string arrays from the jquery ajax to the jersey restful method.
with regards,
es
Server side, you have to change the string array to a List<String> to make it work.
Client side, you can see this to help you how to send the datas. I know in title it's write PHP, but it's well explained.

Can I use c# exe in a fashion similar to PHP in ajax calls

I am currently using jquery to send data from javascript to a php file to execute some server side code:
$.ajax({
url: 'myfile.php', //instead of php, can I call a exe (c#) or asp page here?
type: "POST",
data: ({name: Dummy}),
success: function(data){
}
});
I am facing issues in passing values from my javascript to php file, data is dropped at adfs (eso). So I want to know if a c# exe, or an asp page can be called instead of a php and is it advisable, are there any other way of passing values from client end to server side, my website is made of html files and javascript only.
tried passing this aspx page as URL in above code
Url ="mydomain.com/site/default.aspx";
on the aspx page I am reading
string[] keys = Request.Form.AllKeys;
but the aspx page isnt getting executed (like a php does otherwise)
Take a look at this link, ASP.Net have something know as WebAPI which is great for HTTP services and potentially perfect for what you want.
EDIT:
Based on a comment here is a really basic controller with Get and Post verbs
public class DummiesController : ApiController
{
[HttpGet()]
[Route("api/dummies")]
public IHttpActionResult Get()
{
return this.Ok(new[] {new Dummy(), new Dummy()});
}
[HttpGet()]
[Route("api/dummies/{id}")]
public IHttpActionResult GetById(int id)
{
return this.Ok(new Dummy());
}
[HttpPost]
[Route("api/dummies")]
public IHttpActionResult Post(Dummy dummy)
{
int id = 1;
return this.Created($"api/dummies/{id}", dummy);
}
}

URL GET using Basic Auth with Java Servlet

I have a .jsp page which handles some basic html (text field, submit button a table to populate) and javascript. On click it calls my java Servlet class which handles the request and the response from and to the jsp respectfully. I also have a Java class to handle url connection to make a REST call using GET which should return a json string result. This is the scenario: User wishes to make a simple search by entering an ID value to populate the table using REST to connect to a url and get a json response.
I have separately tested the Java class to make a REST call made by URL connection with Basic Authentication to GET the data in json string and it works perfectly fine. (I have coded 4 different methods of doing this and all work fine and return the expected json).
I have separately tested the jsp page making a call to the servlet to populate "dummy" values in the table and the servlet response is fine and the table populates as expected.
THE PROBLEM:
When I tried to populate the table by the values obtained from the GET REST call, it hangs and I get no result. So I tried to investigate why and found out that for some crazy reason, the servlet doesn't like the line of code which sets the header with the basic authentication to get access to the URL. I tried commenting the basic auth 1 line code out (to debug, so now we have no authentication) but passing through some "dummy" hard coded data, and it populates the table.
I actually don't know why the servlet doesn't like it when I set the authentication. My guess is probably it is overwriting the servlet's response path and therefore lost the initial response location to the jsp? (i.e. where to send the json back to?) Can anyone help me here? Anyone know whats happening? is my assumption of the problem correct? if so, how do I overcome this problem?
Javascript call to the servlet:
$("#myForm2").submit(function(e) {
$.ajax({
type: "GET",
url: "servlet1", // the script where the form input is handled.
data: $("#myForm2").serialize(), // serializes the form's elements.
success: function(responseData){
var dataObj = $.parseJSON(responseData)
$('#myTable').append(>>add values to table here<<);
});
e.preventDefault(); // avoid to execute the actual submit of the form.
$("#myForm2")[0].reset(); // clear previous values entered
});
Servlet class, request made by jsp page and the servlet's response:
Rest getCallOnURL = new Rest(); // instance of my rest class
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException,IOException {
// create a dummy string "test" to hold the ID value passed in from javascript
String testID = request.getParameter("ID");
// Hard coded - only for testing purposes
if (testID.equals("1")){
//call my java class' method to connect to url and retrieve the json string
getCallOnURL.connectToUrlAndMakeAGetRequest();
valueToPopulateTable = getCallOnURL.testJsonString;
}
response.setContentType(CONTENT_TYPE);
PrintWriter out = response.getWriter();
// using backslash to escape the quotes to make a valid json response
out.print("{\"testRow\": \"valueToPopulateTable\"}");
out.close();
}
My Java Class method to make URL call and Basic Authentication:
String testJsonString = "defaultValue";//testing purposes
//creates a valid encoded authentication string
private String basicAuth(String name, String pass){
String authString = name + ":" + pass;
byte[] authEncBytes = Base64.encodeBase64(authString.getBytes());
String authStringEnc = new String(authEncBytes);
return authStringEnc;
}
private HttpURLConnection prepareGETConnection(final URL verifierURL)
throws IOException {
final HttpURLConnection connection = (HttpURLConnection) verifierURL.openConnection();
connection.setRequestMethod("GET");
//this is the line which authorizes access to the url via Basic Auth
connection.setRequestProperty("Authorization", "Basic " + basicAuth(name, password));
return connection;
}
public void connectToUrlAndMakeAGetRequest(){
try {
String webPage = "URL HERE";// pass it a valid REST url with endpoints
URL url = new URL(webPage);
HttpURLConnection conn = prepareGETConnection(url);
// get the url response json string
InputStream getUrlresponse = conn.getInputStream();
BufferedReader rd = new BufferedReader(new InputStreamReader(getUrlresponse));
//get only the first line of the string - testing purposes only!
testJsonString = rd.readLine();
rd.close();
conn.disconnect();
} catch(IOException e){
System.out.println("IO exception: "+e);
}
}

How to send a value from client side to server side for server side processing

I am trying to send a value from the client side using javascript or JQuery, to the server (ideally to a method in my codebehind). I am using C# .net 4.0.
In my client side JQuery I have:
$.post("test.aspx/testMethod",
{
name: "Donald Duck",
city: "Duckburg"
}
);
In my server side (test.aspx.cs) method, I have
public void testMethod()
{
string name = Request.Form("name");
string city = Request.Form("city");
}
But with this I get a compilation error: "Non-invocable member 'System.Web.HttpRequest.Form' cannot be used like a method."
How can I rectify this? Or reach the same objective? Using the $.ajax({...}) is not an option as the value is needed by a non-static method.
There is a very simple answer to this. After searching for hours thru dozens of questions posted along the same lines and many people offering overly complicated ajax post back solutions, I came up with this. Basically a one liner. Hope it helps someone:
In your javascript you just call the method:
PageMethods.SomeMethod('test');
Your "SomeMethod" would be a code behind method like this:
[WebMethod]
public static string SomeMethod(string param1)
{
string result = "The test worked!";
return result;
}
Rules:
You have to identify your code behind method with a WebMethod attribute. It has to be static. And you have to register a script manager in your page as follows:
<asp:ScriptManager ID="MyScriptManager" runat="server" EnablePageMethods="true" />
Since I am working with an aspx webforms page to do some really simple javascript functions like retrieving / stashing geo location, I put it inside the Form element as required.
you can use like this - https://rvieiraweb.wordpress.com/2013/01/21/consuming-webservice-net-json-using-jquery/
try it :)
I dont know if Web Forms support this type of JSON request. I have tried long back but I have to add asmx file that time. Currently you have WCF, but if you don't want to change your webforms project and still want restful api, then merge MVC project for your restful task. You dont have to shift everything but it work together. Here it is explained how?
I don't know about latest version of Web Forms but before VS2012, you can't do ajax type call to page. As far as I know.
Please let me know if any further details needed.
Found Solution... (Hope someone finds it useful)
JAVA SCRIPT
function myFunction() {
var str= "fname=Henry&lname=Ford";
log("MyString=" + str);
}
function log(message) {
var client = new XMLHttpRequest();
client.open("POST", "Default.aspx", true); // Default.aspx being the page being posted to
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.send(message);
}
C# Default.aspx.cs (CODE BEHIND TO Default.aspx)
protected void Page_Load(object sender, EventArgs e)
{
getText();
}
public void getText()
{
if (HttpContext.Current.Request.Form.Keys.Count > 0)
{
string code = HttpContext.Current.Request.Form["MyString"];
// code = "fname=Henry"
// For looping etc, see below
}
}
WHAT ELSE YOU CAN GET....
HttpContext.Current.Request.Form.Count // 2
HttpContext.Current.Request.Form.Keys.Count // 2
HttpContext.Current.Request.Form.AllKeys[0] // "MyString"
HttpContext.Current.Request.Form.Keys[0] // "MyString"
HttpContext.Current.Request.Form.AllKeys[1] // "lname"
HttpContext.Current.Request.Form.Keys[1] // "lname"
HttpContext.Current.Request.Form[0] // "fname=Henry"
HttpContext.Current.Request.Form[1] // "Ford"
Loop through keys...
foreach (string key in Request.Form.Keys)
{
DoSomething(Request.Form[key]);
}
The above code works in that it passes a value(s) from the client side javascript to the server side code-behind, but then unable to use the value because you lose it.
The following modification to the above code is required to use the value (essentially store it in a separate static class until needed).
C# Default.aspx.cs (CODE BEHIND TO Default.aspx)
protected void Page_Load(object sender, EventArgs e)
{
getText();
}
public void getText()
{
if (HttpContext.Current.Request.Form.Keys.Count > 0)
{
// Reset staticValue
Class1.staticValue = "";
Class1.staticValue = HttpContext.Current.Request.Form["MyString"];
// Call Class1.staticValue anywhere else and you get expected answer= "fname=Henry"
}
}
STATIC CLASS (App_Code/Class1.cs) - another object to store value (otherwise the HttpContext object removes it from anything)
public class Class1
{
private static string myValue = "";
public Class1()
{
//
// TODO: Add constructor logic here
//
}
public static string staticValue
{
get
{
return myValue;
}
set
{
myValue = value;
}
}
}

Can JavaScript read HTTP Session object?

Is it possible to read the value of a dynamic variable like httpRequest.getSession("attr_name") from within a JavaScript?
(With Javascript, I assume that you mean client script in the browser.)
No, that is not possible. The contents of the Session object never leaves the server, so client script can't read Session data directly.
If you want to access it in the browser, you have to read the data out of the Session object and send it along in the response (for example in a hidden field), or provide a web service that reads data from the Session object and returns to the browser.
As I said in my comment, the only way would be some kind of Ajax call and request it from the server. I dont know what backend your using, here's how I would do it in Asp.net MVC and jQuery.
(If there are minor syntax errors, I apologize - not in front of a compiler)
public class HomeController : Controller
{
//abstract the session code away, don't let the evil javascript touch
//it directly. Ideally this would all be in a seperate logic class or something.
public string NameAttribute
{
get
{
return Session["attr_name"] as string ?? string.empty;
}
}
[HttpGet]
public string GetNameAttribute()
{
return NameAttribute;
}
public ActionResult Index()
{
return View();
}
}
<script>
$(function(){
$.get( 'home/GetNameAttribute', function( response ) {
var name = response; //don't forget error checking, ommited
});
});
</script>
Alternatively, you could always write down the values you need into hidden fields, and read them with normal javascript.

Categories

Resources