I am pretty new to Javascripts, jQuery and Ajax and so I have a few questions.
What I want is this: Make an Ajax request in my javascript, and the controller will take an OBJECT as a parameter. The Controller, after having received the response from the back-end as a stream, will return the result as JSON (on success in the javascript). However, here is where I am getting a bit unsure. Shall JObject be returned or raw JSON string (with the help of e.g JsonConvert) ?
In my WebApiConfig.cs:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
The object type in the Controllers parameter list:
public class Credentials
{
public string Email { get; set; }
public int CustomerID { get; set; }
public string Reference { get; set; }
}
Contoller method to be called:
public HttpResponseMessage GetOrderInfo(Credentials credentials)
{
// Create Url with appended Credential properties
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.Accept = "application/json";
httpWebRequest.Method = "POST";
var response = (HttpWebResponse)httpWebRequest.GetResponse();
var responseStream = response.GetResponseStream();
var rawJson = new StreamReader(responseStream).ReadToEnd();
// var json = JObject.Parse(rawJson);
return Request.CreateResponse(HttpStatusCode.OK, rawJson);
}
Javascript:
function get_order_info(email, customerId, reference) {
/* This is where I want the Ajax call to the correct controller, taking an object
as a parameter */
}
Now, my questions are:
How will such a $Ajax call look like, considering I want a specific Controller method to be called that takes a Credential object as parameter?
I want JSON format to be returned, is it the correct way in Controller method GetOrderInfo?
And I feel a bit dumb for the last question. If correct JSon-format is returned, how do I access it from the response:
success: function (response) {
/* response.responseText ?? */
}
Thanks, Best Regards
Taking Ajax out of the picture;
How would be your normal web request be?
example of GET request: http://localhost:8080/api/controller1/get_order_info?email=value1&&customerId=value2&&reference=value3
Does this call recognize your Controller method, accept the request parameters and gives you the json object back?
If yes, then you can either make Ajax GET or POST request to do the same.
Ajax POST request via JQuery:
$.post( "http://localhost:8080/api/controller1/get_order_info", { email: "value1", customerId: "value2", reference:"value3" })
.done(function( data ) {
alert( "Data Loaded: " + data );
});
https://api.jquery.com/jQuery.post/
Note: In this specific case, there should be some server component that accept the request and create Credentials
object and set the properties from the incoming request parameters.