Is it possible to retrieve data from SQL Server using jQuery?

19,006

jQuery is designed to run within a browser environment — so that's an environment with a DOM, with JavaScript support (obviously), and such.

To retrieve data from MS SQL Server, you need access to a database driver, and access to the server. It's rare for the browser to have those two things, and even if they do, you usually don't want to have the two talking directly.

Instead, the usual way you structure this is to have your browser-based code talk to a middle layer server (a web server, since browsers are good at talking to them), which then has access to the database. There are several reasons for this:

  1. It gives you a place (the server between the browser and the database) to apply security, gate-keeping, throttling, monitoring, etc.

  2. It prevents exposing your database code and structure to the end user (as your browser-based JavaScript code can be read by anyone who wants to read it).

  3. Getting access to the database driver from the browser environment is tricky, requiring non-standard things like IE's ActiveXObject which aren't present on all browsers and trigger security warnings even on browsers they're present in.

How you have the browser talk to the server varies depending on what you want to do, but the modern practice is to use ajax, which stands (somewhat apocryphally) for Asynchronous JavaScript and XML. (Nowadays people use it for a lot more than XML; JSON is a more common data notation.)

So for instance, maybe you want to fill in some HTML on a button click. In your browser-based code, you'd hook the button click:

$("#theButton").click(handleButtonClick);

You'd have that button send a request to the server. If the request is idempotent (you always get back the same data), you send a GET; otherwise, you send a POST:

function handleButtonClick() {
    $.ajax({
        url:     "/path/to/server/resource",
        type:    "GET",
        data:    {articleId: 27},
        success: function(data) {
            /* ...use the data to fill in some HTML elements... */
        },
        error:   function() {
            /* ...show an error... */
        }
    });
}

On the server, the page at /path/to/server/resource would do the work necessary to validate that the request should be fulfilled, connect to the database, query (or update) the information, and format a response to send back to the client.

Obviously the above is a very, very, very condensed account of how you do this, but hopefully it sets the stage and gives you an idea what to look into to go to the next step.

Share:
19,006
Admin
Author by

Admin

Updated on July 03, 2022

Comments

  • Admin
    Admin over 1 year

    Is it possible to retrieve data from SQL Server using jQuery and display the data using an HTML control ?