Using AJAX in Classic ASP to submit a form via a POST request

My code in TEST.ASP looks like this:

<HTML>
<HEAD>
    <SCRIPT src="ajaxScript.js" type="text/javascript"></SCRIPT>
</HEAD>
<BODY>
    <FORM action="action_page.asp" method="post">
        First Name:<BR>
        <INPUT type="text" name="FName"><BR>
        Last Name:<BR>
        <INPUT type="text" name="LName"><BR>
        <INPUT type="submit" value="Submit">
        <BUTTON type="button" onClick="loadXMLDoc('action_page.asp',this.form);">GoGoGo!</BUTTON>
    </FORM>
    <DIV id="msgBoxDiv">TEST!!</DIV>
</BODY>
</HTML>

The ajaxScript.js file has the following code:

var req; // global variable to hold request object

function processReqChange()
{
    if (req.readyState == 4 && req.status == 200){document.getElementById("msgBoxDiv").innerHTML = req.responseText;}
}

function loadXMLDoc(url, params)
{
    if(window.XMLHttpRequest)
    {
        try
        {
            req = new XMLHttpRequest();
        } catch(e)
            {
                req = false;
            }
    }
    else
    {
        req = false;
    }

    if(req)
    {
        var formData = new FormData(params);

        req.onreadystatechange = processReqChange;
        req.open("POST", url, true);
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        req.send(formData);
        return true;
    }
    return false;
}

The receiving "action_page.asp" file is set up like this:

<%
    vRF1 = request.Form("FName")
    vRF2 = request.Form("LName")
%>

<HTML>
    <HEAD>

    </HEAD>
    <BODY>
        First:<%=vRF1%><BR>
        Last:<%=vRF2%>
    </BODY>
</HTML>

When using the normal submit button, everything works fine. However, when trying to read the target ASP with AJAX using the "GoGoGo" button, the form values are not sent to the target page. Instead, I receive the target page without the values. See the result page.

If I manually input the form data in the AJAX request, it works well, but when trying to send the entire form, it does not. I thought using the FormData object would handle this, but it's not working as expected.

What could be the issue here?

Answer №1

Leaving this unanswered was not an option for me.

Lankymart pointed me in the right direction for the solution. It turns out that when I used "new FormData(formID)", I was actually sending data in multipart/form-data format instead of the application/x-www-form-urlencoded format that I had intended to use.

Therefore... Following Lankymart's suggestion, we can consider using application/x-www-form-urlencoded. In simple terms, you just need to take my original question and format the parameters to pass in req.send(); similar to a GET request. "name1="+param1+"&name2="+param2. I chose this method because it suited my requirements perfectly.

Alternatively... If you do require or prefer to send the form using req.send(formData), it will result in multipart/form-data format (refer to an example of multipart/form-data format here: http://www.codeproject.com/Articles/1125/Advanced-ASP-Uploader) In this scenario, you will need to create a parser for the data. Below is a snippet of code I wrote (just to experiment):

Function StoreNameAndValues(tempVarArray)
    Dim tempVar

    for i = 1 to ubound(tempVarArray)-1
        if tempVarArray(i)<>"" then
            tempVar=Split(tempVarArray(i), """")

            if ubound(tempVar)>1 then
                postNamesArray(i-1)=tempVar(1)
                postValuesArray(i-1)=StripString(tempVar(2),CHR(13)&CHR(10))
            End if
        End if
    next
End Function


tempVar=Request.TotalBytes
tempVar1=Request.BinaryRead(tempVar)

tempVar1=SimpleBinaryToString(tempVar1)

separator=Split(tempVar1, CHR(13)&CHR(10))(0)
tempVar2=Split(tempVar1,separator)

postArgumentsSize=ubound(tempVar2)-1
Dim postNamesArray()
Dim postValuesArray()
ReDim Preserve postNamesArray(postArgumentsSize)
ReDim Preserve postValuesArray(postArgumentsSize)

StoreNameAndValues(tempVar2)

The parser I created in the code above is very basic and not suitable for file uploads, but it serves as an illustration.

I hope this information is error-free and beneficial to someone in need.

Answer №2

After trying numerous solutions and searching extensively, I finally found the answer that led me in the right direction. I was facing an issue with my classic asp page not reading the ajax form post that I was trying to send.

The breakthrough came when I added

contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
to the ajax function. This adjustment allowed me to successfully send the form data, and my classic asp page was able to read all the values correctly.

    $('#subdel').click(function () {
      // Retrieve values from outside the form
      var tDate = $('#datepicker').val();
      var tCID = $('#Client').val();
      var vFD = $('#dataentry').serialize();
      // Append those values to the form data
      vFD = vFD + '&C=' + tCID;
      vFD = vFD + '&D=' + tDate;
      $(function() {
         var request = $.ajax({
            url: 'api/saveDLR.asp',
            type: 'POST',
            data: vFD,
            processData: false,
            contentType: false,
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            cache: false,
            success: function (response) {
               // Perform actions such as hiding parts of the page and displaying the result after saving the form
               $('#cldel').hide("slow");
               $('#endel').hide("slow");
               $("#encon").html( response );
               $('#encon').show("slow");
               // Update a table after processing the form
               $(function() {
                   var request = $.ajax({
                   url: "/api/getDelClient.asp?C=" + tCID + "&D=" + tDate,
                   type: "GET",
                   dataType: "html",
                   success: function (response) {
                      $("#cldel").html( response );
                      $('#cldel').show("slow");
                   },
                   error: function (response) {
                      alert(response.responseText);
                   }
                   });
               });
            },
            error: function (response) {
                  alert(response.responseText);
            }
         });
      });
   });

This solution may be beneficial for others facing a similar issue.

The classic asp page simply retrieves the form data using Request.Form

<%  For Each item In Request.Form
      Response.Write item & " - " & Request.Form(item) & "<br/>"
    Next
%>

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

Leveraging the spread operator in cases where the value is null

Is there a more elegant solution for handling null values in the spread operator without using if-else statements? In this specific case, I only want to spread assignedStudents if it is not undefined. When attempting to do this without using if-else, I e ...

Discover the steps to traverse through directories and their numerous subdirectories (including a whopping 15000 subdirectories) with the help of the directory-tree

We are currently utilizing the directory-tree npm package to access and read through all directories and subdirectories, noting that there are as many as 15000 nested subdirectories. Code snippet in use: const dirTree = require("directory-tree"); const ...

Is it possible to utilize a controller within a different controller?

As I work on developing an application, I am faced with the challenge of using controller functions within another controller function. Is it possible to achieve this or not? Use-case: My goal is to verify in the User collection (using mongoDB) if a user ...

How can we format a number to match the Brazilian number system while still maintaining its ability to be used in calculations?

Is there a known method to convert the number 123,123,214.93 into Brazilian currency format (123.123.214,93) for display purposes only? I attempted to achieve this conversion using a JavaScript function where I added periods after every 3 numbers and repl ...

What is the best method for passing parameters from HTML to AJAX within code?

My project involves working with Flask, HTML, and Ajax. Here is the HTML code snippet: <script type=text/javascript> $(function() { $('a#calculate').bind('click', function() { $.getJSON('/_add_numbers&ap ...

Troubleshooting why passing $var within @{{ }} in Vue.js + Laravel is not functioning as expected

I am integrating Algolia Vue-InstantSearch into a Laravel Project. Since we are working with a blade file, the {{ }} symbols will be recognized by the php template engine. To ensure that they are only understood by Vue in JavaScript, we can add an @ prefix ...

Error in table layout caused by asynchronous .get jQuery function

I am facing a challenge in populating a timetable with specific information for each cell from a database. The table is being dynamically refreshed using the following function: function refreshTable() { //Form values var park = $('#Park&apos ...

How can Vue be used to dynamically change the input type on focus?

What Vue method do you recommend for changing an input element's type on focus? e.g. onfocus="this.type = 'date'" I am specifically looking to switch the input type from text to date in order to utilize the placeholder property. ...

Searching in binary for the number closest to the target float value

Seeking assistance with a float array conundrum! I am trying to identify the closest float value to a target number within the array. My attempt involved utilizing a basic binary search algorithm in JavaScript, but I've hit a roadblock. function bina ...

Discover the concealed_elem annotations through the power of JavaScript

As I work on my new website, I am struggling with narrowing down the web code. I came across a solution that seems fitting for what I need, but unfortunately, I can't seem to make it work: I attempted the non-jQuery solution, however, I must be missi ...

Javascript error when attempting to add leading zeros

Is there a way to utilize JavaScript or JQuery in order to prepend a zero to this script? for (im=1;im<=31;im++){ days[im]=everyDay[im]; } ...

Unpredictable Dependency Outcomes in Node.js

Encountering a warning while running yarn install where all dependencies are installed, but a specific warning is triggered: Warning: Pattern ["esprima-fb@~3001.0001.0000-dev-harmony-fb"] is attempting to unpack in the same destination "/Users/Me/Librar ...

spill the elements from one div into another div

I'm facing a situation where I have 2 divs on a page, with the first div containing text content only. The issue is that when the content of the first div overflows, it gets cut off due to the CSS applied to it: .one { overflow: hidden; width: 1 ...

Most effective method for utilizing Ajax to upload files and ensuring they are uploaded before submission

I am currently working on a form that contains various fields, including file upload functionality for multiple files. I have also explored the option of using AJAX to upload files. My goal is to seamlessly upload files via AJAX while simultaneously fillin ...

Is the conditional module require within an "If" statement always executed in nuxt.config.js?

Despite the missing file mod.json, the "require" statement is still executed leading to an error. The condition should have prevented it from entering the "if" block: const a = 1; if(a === 2){ const mod = require('./scripts/mod ...

What is the best way to prevent useEffect from triggering when a modal is being rendered?

I'm currently developing a react movie application. I am facing an issue with the hero picture feature that displays a random popular movie or show. Whenever I click the button to open a modal, the useEffect function is triggered and changes the movie ...

Unable to host Express app on Firebase functions emulator due to a port conflict with error code EADDRINUSE: address already in use :::3000

Testing the deployment of an express app on Firebase using Firebase functions has presented a challenge for me. Upon running the command firebase serve, I encountered the error EADDRINUSE: address already in use :::3000. Below is my index.js file: const fu ...

How to make the slides in a Bootstrap 4 carousel slide in and out with animation

I'm currently utilizing the bootstrap 4 carousel and have made some customizations to fit my project needs. The main requirement is: When I click on the next slide, the current next slide should become active and a new next slide should load with ...

How can I apply and delete a css class only while scrolling in a React application?

Currently, I am designing a pretend blog layout to showcase my work. The grid of posts features cards that are precisely 400x400 in size with a hover effect that magnifies and adds a drop shadow (this is visible in the dashboard route). However, an issue ...

Using caret range and package-lock.json to acquire the most recent non-disruptive versions

I understand the purpose of package-lock.json, but I'm unsure about how the caret range works after adding this file. Let's say I have a package called my-module and I want to automatically receive all new non-breaking versions without manually ...