JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript AJAX ASP


AJAX allows web pages to communicate with the server without reloading, and ASP (Active Server Pages) is a server-side technology often used to generate dynamic web content. Using AJAX with ASP lets you send and receive data asynchronously, making your web applications more interactive.

What Is AJAX ASP?

AJAX ASP refers to using AJAX requests in JavaScript to interact with ASP scripts on the server. This combination is commonly used for:

  • Retrieving data dynamically without page reload.

  • Submitting form data to the server.

  • Updating parts of a webpage based on user input.

AJAX handles the client-side communication, while ASP handles the server-side logic.

Creating a Simple AJAX ASP Example

Imagine Vicky wants to fetch a greeting message from the server using ASP.

ASP File (greet.asp)

<%
Response.ContentType = "text/plain"
Response.Write "Hello, Sanjana! This is a greeting from ASP."
%>

HTML and JavaScript

<button id="loadBtn">Get Greeting</button>
<div id="output"></div>

<script>
document.getElementById("loadBtn").addEventListener("click", function() {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "greet.asp", true); // Initialize GET request

  xhr.onload = function() {
    if (xhr.status === 200) {
      document.getElementById("output").textContent = xhr.responseText;
    } else {
      document.getElementById("output").textContent = "Error loading message";
    }
  };

  xhr.send(); // Send the request
});
</script>

Explanation:

  • The ASP script returns a plain text greeting.

  • The AJAX request fetches it asynchronously.

  • xhr.responseText contains the server response.

Clicking the button displays:
“Hello, Sanjana! This is a greeting from ASP.”

Sending Data from JavaScript to ASP

You can also send data to an ASP page using the POST method.

HTML Form

<input type="text" id="username" placeholder="Enter your name">
<button id="sendBtn">Send</button>
<div id="response"></div>

JavaScript

document.getElementById("sendBtn").addEventListener("click", function() {
  let name = document.getElementById("username").value;

  let xhr = new XMLHttpRequest();
  xhr.open("POST", "process.asp", true);

  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

  xhr.onload = function() {
    if (xhr.status === 200) {
      document.getElementById("response").textContent = xhr.responseText;
    } else {
      document.getElementById("response").textContent = "Error sending data";
    }
  };

  xhr.send("username=" + encodeURIComponent(name));
});

ASP File (process.asp)

<%
Dim name
name = Request.Form("username")
If name <> "" Then
    Response.Write "Hello, " & name & "! Your data has been received by ASP."
Else
    Response.Write "No data received."
End If
%>

Explanation:

  • Data from the input field is sent via POST.

  • Request.Form("username") retrieves the data on the server.

  • Vicky can enter “Sanjana” to receive:
    “Hello, Sanjana! Your data has been received by ASP.”

Returning JSON from ASP

AJAX ASP can also send JSON data, useful for dynamic web applications.

ASP File (user.asp)

<%
Response.ContentType = "application/json"

Dim user
user = "{""name"": ""Sanjana"", ""age"": 26, ""email"": ""sanjana@example.com""}"

Response.Write user
%>

JavaScript

let xhr = new XMLHttpRequest();
xhr.open("GET", "user.asp", true);

xhr.onload = function() {
  if (xhr.status === 200) {
    let user = JSON.parse(xhr.responseText);
    document.getElementById("output").innerHTML =
      `Name: ${user.name}<br>Age: ${user.age}<br>Email: ${user.email}`;
  } else {
    document.getElementById("output").textContent = "Failed to load data";
  }
};

xhr.send();

Explanation:

  • The ASP page returns a JSON string.

  • JSON.parse() converts it into a JavaScript object.

  • This allows dynamic display of user information.

Error Handling in AJAX ASP

Always check the status code to handle errors properly.

xhr.onload = function() {
  if (xhr.status === 200) {
    console.log("Request successful:", xhr.responseText);
  } else if (xhr.status === 404) {
    console.error("ASP file not found.");
  } else {
    console.error("Server error:", xhr.status);
  }
};
  • 200 indicates success.

  • 404 means the ASP file is missing.

  • Other codes indicate server issues.

Displaying ASP Data Dynamically

AJAX allows you to update the page without reloading.

<button id="fetchData">Load User Info</button>
<div id="userInfo"></div>

<script>
document.getElementById("fetchData").addEventListener("click", function() {
  let xhr = new XMLHttpRequest();
  xhr.open("GET", "user.asp", true);

  xhr.onload = function() {
    if (xhr.status === 200) {
      let user = JSON.parse(xhr.responseText);
      document.getElementById("userInfo").innerHTML =
        `<p>Name: ${user.name}</p>
         <p>Age: ${user.age}</p>
         <p>Email: ${user.email}</p>`;
    } else {
      document.getElementById("userInfo").textContent = "Error loading user info";
    }
  };

  xhr.send();
});
</script>

Explanation:

  • Clicking the button fetches JSON data from ASP.

  • Data is displayed dynamically in a <div>.

  • The page does not reload.

Summary of the Tutorial

Using AJAX with ASP, you can:

  • Fetch or send data asynchronously.

  • Handle plain text, HTML, or JSON responses.

  • Submit forms without reloading pages.

  • Update parts of a webpage dynamically.

  • Handle server errors gracefully.

Combining AJAX and ASP allows developers like Vicky to build interactive and responsive web applications where the user, for example Sanjana, can see updates immediately without refreshing the page.


Practice Questions

  1. Write an AJAX GET request to fetch a greeting from greet.asp and display it in a <div> when a button is clicked.

  2. Create a form with an input field for a name and send it via AJAX POST to process.asp, then display the server response.

  3. Fetch JSON data from user.asp and display Sanjana’s name, age, and email dynamically on the page.

  4. Write an AJAX request that handles errors when process.asp is missing (404) and shows an alert.

  5. Create a button that sends a name to ASP via POST and updates a <p> element with the returned message.

  6. Fetch an HTML snippet from snippet.asp and insert it into a <div> without reloading the page.

  7. Send multiple form fields (name, email, age) via AJAX POST to ASP and display a confirmation message.

  8. Write code to fetch JSON from user.asp, parse it, and populate an unordered list <ul> with the data.

  9. Create an AJAX request that times out after 5 seconds and shows an error message if the ASP script doesn’t respond.

  10. Write a function that sends the user’s name to ASP, receives a personalized greeting, and appends it to a <div> each time the button is clicked.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top