Converting form data to string in JavaScript without using jQuery or any external libraries

Is there a way to post form data using AJAX without relying on jQuery or other libraries?

I am looking to create an ajaxForm function that can serialize form data, make an AJAX post request, and then handle the response with JavaScript.

Let's say I have the following form:

<form action="url" method="POST">
<table>
<tr><td>label...</td><td><input name="input1" type="text"/></td></tr>
<tr><td>label...</td><td><input name="input2" type="checkbox"/></td></tr>
<tr><td>label...</td><td><select name="input3"><options....></select></td></tr>
</table>
</form>

If I select the form element using JavaScript and pass it along with a callback function to ajaxForm(form, callback), could someone provide an example of how this can be done? Thank you in advance.

Update: My main issue lies in figuring out how to serialize form data. Any suggestions are welcome!

Update Again: Thank you for all your responses. The problem has been resolved.

I have successfully converted the jQuery form plugin into pure JavaScript, and I'm excited to share it with all of you.

https://github.com/guileen/ajaxform.js

button.onclick = function(){
  ajaxForm(form, function(xmlhttp){
    alert(xmlhttp.status);
    alert(xmlhttp.responseText);
  });
}

Answer №1

let httpRequest = false;
function sendPostRequest(url, params) {
  httpRequest = false;
  if (window.XMLHttpRequest) { // Using modern browsers like Mozilla and Safari.
     httpRequest = new XMLHttpRequest();
     if (httpRequest.overrideMimeType) {
        // Adjusting the content type as needed
        //httpRequest.overrideMimeType('text/xml');
        httpRequest.overrideMimeType('text/html');
     }
  } else if (window.ActiveXObject) { // For Internet Explorer
     try {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) {
        try {
           httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {}
     }
  }
  if (!httpRequest) {
     alert('Unable to create XMLHTTP instance');
     return false;
  }

  httpRequest.onreadystatechange = handleResponse;
  httpRequest.open('POST', url, true);
  httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  httpRequest.setRequestHeader("Content-length", params.length);
  httpRequest.setRequestHeader("Connection", "close");
  httpRequest.send(params);
}

function handleResponse() {
  if (httpRequest.readyState == 4) {
     if (httpRequest.status == 200) {
        result = httpRequest.responseText;
        document.getElementById('output').innerHTML = result;            
     } else {
        alert('There was an issue with the request.');
     }
  }
}

// Call this function with parameters
function postData(obj) {
  let data = "textarea1=" + encodeURI(document.getElementById("textarea1").value) +
                "&textarea2=" + encodeURI(document.getElementById("textarea2").value);
  sendPostRequest('post.php', data);
}

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

How can you simultaneously utilize customCell and Reorder functionalities in Kendo React Grid?

Currently, I am utilizing the Kendo React Grid with reorder functionality enabled and a custom cell for showing/hiding columns. Initially, everything works smoothly when toggling visibility without reordering. However, once I rearrange the columns and the ...

Maintain a fixed element and enable the rest of the elements to scroll as the mobile browser address bar collapses while scrolling upwards

Currently facing a challenge where I want the background image to remain static while the address bar and content underneath scroll up. The image occupies 90% of the view height, and although I've prevented it from resizing and jumping when the addres ...

Parsley JS - Personalized Validation for Ensuring selected Items meet Minimum Value Requirements

Is it possible to validate a form so that at least 5 select boxes are set to Yes? If there are fewer than 5, the form should not submit and display an error message. I believe a custom validator is needed for this task. To see a complete example, check ou ...

Steps to create a new popup and convert it into a new tab

I would like to customize the way a new window opens by displaying it in a tabbed view rather than a separate popup. I have attempted the following methods: var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes"; var URL = " ...

What is the best way to delete a parent div without losing its inherited CSS properties?

My current objective involves the following: <div id="table"> <div id="user"></div> <div id="user1"></div> </div> Upon clicking a button, the following actions take place: $("#body").append("<div id=\"user-wra ...

Issues with ajax functionality

Utilizing Codeigniter When clicked ... .. insert some code.... $.ajax({ url: '<?php echo base _ url(); ?>locations/getmap', dataType: 'json', type: 'POST', data: location_data, success ...

Fill various dropdowns with a list or array of values discreetly without displaying the populated values on the visible interface

I have an array with values 1,2,3,4. Using an add function, I am able to create multiple dropdowns. By default, the first dropdown always has a value of one when initially set up. When we press add and populate the second dropdown with values 2,3,4, tho ...

Store the JSON reply as a fixed variable

Recently, I have been delving into ReactJS and I've encountered a challenge of saving a JSON array as a 'const'. I have attempted the following approach: fetch(url) .then(response => response.json()) .then(json => { this.setSt ...

Is there a way to incorporate React into JavaScript files without using NodeJs?

Want to know how to incorporate a react file into Javascript files without using any library or nodeJs? Here is a snippet of my code: main.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8> <title> ...

Incorporating Dynamic Component Imports in Vue.js Data and Computed Properties

I have a component called 'Page' that needs to display another component retrieved via props. Currently, I am able to successfully load my component by hardcoding the path in the data like this: <template> <div> <div v-if=" ...

Is there a way to get the eventListener to function properly within a table that contains an image?

I need help with a JavaScript function that can add or remove an image from table cells when clicked. Here is my current code snippet: const table = document.querySelector("tbody") table.addEventListener("click", clickTile) function cl ...

What is the best way to use a nested for loop to extract values from JSON and assign them to variables?

I have a JSON structure containing subject fields and their corresponding values listed separately. I am looking to implement a nested for loop that will dynamically assign the values to each subject field based on the given JSON data. Currently, my approa ...

Can the value of ng-model be altered without using ng-change function?

Can the ng-model value be altered without using the ng-change function? The method below does not seem to work. <div ng-app="myApp"> <div ng-controller="MyCtrl"> <input id="checkbox" type="checkbox" ng-model="field"> <div> {{field ...

Using Django to retrieve data from a file uploaded through a website

Looking to create a website that allows users to select a local file (XML/JSON) and then navigate to a Django view to extract data from it. Should I implement javascript for the file selection form and sending it to a specific URL for the Django view? Any ...

Attempting to transform a brief JavaScript script into Java code

There's a code snippet in JavaScript that I'm not familiar with, but I need to pass this information to one of my Java methods. example.setChoices([{ value : 'One', label : 'Label One', disabled : true }], 'value', ...

What causes the map function to behave differently when I use an array as the return value rather than a primitive in the callback function?

Program var corporations=[ {name:'Vicky',category:'Devdas',start:1993,end:2090}, {name:'Vikrant',category:'Devdas',start:1994,end:2019}, {name:'Akriti',category:'mental',start:1991,end:2021}, { ...

Select the specific reducer from action type in Redux when utilizing combineReducers

Here's the code for my reducer: const buttonReducer = (state = { buttons: [] }, action) => { switch(action.type) { case "add": { state = { ...state, buttons: [...state.buttons, action.payload] } ...

Utilize Typescript/Javascript to utilize the Gmail API for sending emails via email

I am trying to send emails from my application using my Gmail account with Ionic. I have followed tutorials from SitePoint and Google Developers. Here is how I'm initializing the client: client_id: gapiKeys.client_id, discoveryDocs: ["https://www.goo ...

There is no comparison when it comes to ajax

//Within a different function var result = performCheck(a,b,c); alert(result); function performCheck(a,b,c) { $.ajax({ type: "POST", url: "abc.php", data: { a: a, b: b, c: c }, success:function(da ...

Highcharts: Show tooltip above all elements

Is there a way to configure tooltip display above all elements? I want to define specific coordinates so that the tooltip remains open even if it is covering the chart, and only closes when interacting with the top block. Screenshot 1 Screenshot 2 For e ...