Exploring the Dynamics of jQuery and Ajax Interaction

I am relatively new to working with Javascript, jQuery, and Ajax, so I have a few inquiries.

What I am hoping to achieve is as follows: I would like to make an Ajax request in my javascript code, where the controller will accept an OBJECT as a parameter. Upon receiving the backend response as a stream, the Controller should then return the result in JSON format (upon successful execution in the javascript). However, I am a little uncertain about whether to return JObject or raw JSON string (possibly using JsonConvert)?

In my WebApiConfig.cs file:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

The object type within the Controllers parameter list:

public class Credentials 
{
    public string Email { get; set; }
    public int CustomerID { get; set; }
    public string Reference { get; set; }
}  

Controller method that needs to be invoked:

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 snippet:

function get_order_info(email, customerId, reference) {
    /* This is where I want to send an Ajax call to the designated controller, passing an object as a parameter */ 
}

Now, onto my questions:

How should the $Ajax call be structured if I want a specific Controller method that accepts a Credential object as a parameter?

Am I following the correct approach for returning data in JSON format from the Controller method GetOrderInfo?

Lastly, how can I access the returned JSON format in the success function of the response:

success: function (response) {
    /* response.responseText ?? */
}  

Thank you and best regards.

Answer №1

Removing Ajax from the equation;

What would a standard web request look like?

an instance of GET request:

http://localhost:8080/api/controller1/get_order_info?email=value1&&customerId=value2&&reference=value3

Will this call identify your Controller method, process the request parameters, and return the json object to you?

If so, you can opt for either an Ajax GET or POST request to achieve the same result.

Ajax POST request using 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/

Please note: In this particular scenario, there needs to be a server component that accepts the request, creates a Credentials object, and sets the properties based on the incoming request parameters.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to fetch the session variable using express-session

In my development work, I have been utilizing express-session for persistently storing sessions on a MongoDB database. While the project functioned flawlessly in a test environment, an issue arose when deploying to a production setting where the session v ...

Guide to sending a HTTP POST request with parameters in typescript

I need assistance sending a POST request using parameters in the following format: http://127.0.0.1:9000/api?command={"command":"value","params":{"key":"value","key":"value","key":"value","key":value,}} I attempted to do this but encountered an issue: l ...

The result of a React component's render method is a

I am currently updating an existing codebase. Here is a portion of the code with specific details concealed: class Config extends Component { . . . render() { const { onSubmit, isConfigValid } = this.props; return ( <Form> ...

Typescript on the client-side: what is the best way to eliminate circular dependencies when using the factory method design pattern?

In my code, I have implemented the factory method pattern. However, some instances using this pattern end up with circular dependencies. Removing these dependencies has proven to be a challenge for me. To illustrate, consider the following example: // fact ...

The RC-dock library's 'DockLayout' is not compatible with JSX components. The instance type 'DockLayout' is not a valid JSX element and cannot be used as such

Despite encountering similar questions, none of the provided answers seem to address the issue within my codebase. My project utilizes React 17, Mui v5, and TS v4. I attempted to integrate a basic component from an external package called rc-dock. I simply ...

"Unraveling the Mystery: In Javascript Vue, what is the secret behind the origin of the variable 'e' found in the function

Where does the mysterious variable e in onFileChange(e) come from? In the code snippet below, we see a variable e being used in onFileChange(e). However, this variable is not declared or imported anywhere in the code. How is it possible for this to be val ...

Displaying numbers individually with commas in a Django template

I am facing an issue where the number being typed into a text field does not have commas separating the thousands For example, if the user types 500000, it displays as 500000 instead of 500,000 This issue is present in the models section of the code: so_ ...

"Enhancing Code Readability with Language-Specific Syntax Highlighting

My goal is to develop an editor that allows users to input code in various languages by selecting an option from a dropdown menu. The code should then be automatically highlighted based on the chosen language. I am considering using Codemirror for syntax ...

Problems encountered with dragging elements in Firefox

Is there a reason why an image may not be draggable in Firefox even when the draggable="true" attribute is set? I am working on a JavaScript image swapping script and encountering difficulties with drag-and-drop functionality specifically in Firefox. While ...

Angularjs pledged to utilize $http for its functionality

$http({ url: '/verifyUserName', data:{username:$scope.username}, method: "POST" }) .then(function(response) { $scope.allowGameStart = true; }) Is there a way to access the variable $scope.allowGameStart outside of the promise in ...

"JavaScript throws an 'Undefined' error when trying to access a basic

I am struggling with a basic set of HTML and JS files that are not functioning properly, and I can't seem to pinpoint the issue: <html> <head> <script type="text/javascript" src="data.json"></script> < ...

SQL's ability to handle multidimensional JSON objects

My database table is structured as follows: https://i.sstatic.net/fTwe2.png I need to craft a SQL query that accomplishes the following: Create an object for each unique value in the "MONTH" column Store this data in an array according to the JSON stru ...

I am struggling to comprehend the passing of elements from an array to a function's argument

I'm grappling with the concept of a function that I grasp. function forEach(array, action) { for (var i = 0; i< array.length; i++) action(array[i]); } When we use this function, like forEach([1,2,3,4,5], console.log);, it essentially swaps ...

Could you break down the concept of the for/in loop for me?

/* Follow the instructions provided to implement each function. The parameters of a function that reference `cart` pertain to an object structured like this: { "Gold Round Sunglasses": { quantity: 1, priceInCents: 1000 }, "P ...

Unveil the modules of a Node.js NPM application

I have a Node application that is used as an npm module and serves as a dependency in the package.json file of another Node application. This application needs to grant access to internal modules to the app utilizing my package as a dependency. All these m ...

Adjusting the content within a text area using an AngularJS service

I am currently editing text in a textarea within the admin view and I would like to display it through an angular service on the user view. However, I want the text to be displayed in multiple rows, maintaining the same format that I entered in the textare ...

Just starting out with coding and feeling a bit lost - Echo

Forgive my lack of understanding. This is my first time delving into the world of coding and it all seems a bit confusing and overwhelming. I'm trying to keep it simple by following a guide to build something for Amazon Echo. I've reached Step 2 ...

A guide to dynamically adding an HTML class using JavaScript

I have a login page with a text field for email and password, styled using the Bootstrap framework. I want to change the border color of the input field from grey to red when it is empty and the user clicks the login button. I tried implementing the code t ...

The issue with Scrolltop is that it is not aligning to the intended

My goal is to focus the top of a div when an anchor is clicked using the code below. $('html, body').animate({scrollTop: $("#" + divid).offset().top}, 100); Unfortunately, instead of scrolling to the top of the div, the focus ends up at a posit ...

Node.js scheduler library for triggering events based on time in a cron-like fashion

Currently, I am utilizing Node.js to develop a web application. My aim is to trigger events at specific times. While I am aware of using setTimeout and computing the time difference from the present moment, this method does not account for various timezone ...