Using JavaScript to send form input in the form of a 2D array through AJAX

I am currently working on a form that looks like this:

<form name="chat" id="chat" action="" onsubmit="sendMessage()">
 <a name="chat">&nbsp;</a>
 <input type="text" name="chat" id="chat" size="38" maxlength="50" vertical-align="middle">
 <input type="hidden" name="action" id="action" value="checkresponse">
 <input type="hidden" name="response_Array[sessionid]" id="response_Array[sessionid]" value="keu88lh88ini89dgnccob54f27"><br>
 <input type="text" name="response_Array[top]" id="response_Array[top]" value="a">
 <input type="text" name="response_Array[second]" id="response_Array[second]" value="b"><br>
 <input type="text" name="response_Array[third]" id="response_Array[third]" value="c"><br>
 <input type="text" name="response_Array[fourth]" id="response_Array[fourth]" value="d"><br>
 <input type="text" name="response_Array[input][0]" id="response_Array[input][0]" value="input 0"><br>
 <input type="text" name="response_Array[that][0]" id="response_Array[that][0]" value="that 0"><br>
 <input type="submit" name="submit" id ="submit" value="SEND" style="width: 45px">
 </form>

My goal is to send all the input fields to the server without refreshing the page when the user clicks Submit. To achieve this, I have implemented sendMessage() function which utilizes XMLHttpRequest object for form submit request.

In order to extract input field values in sendMessage(), I have used:

var infoStr = "chat="+document.forms[0]['chat'].value;
infoStr += "&action="+document.forms[0]['action'].value;

I am seeking advice on how to properly retrieve and parse the 2D array :response_Array into a JSON string so that it can be transmitted to PHP server code.

Answer №1

It's incredibly straightforward

var dataString=""
for(var i=0;i<document.forms[0].elements.length;i++)
{
   dataString+=document.forms[0].elements[i].name+"="+document.forms[0].elements[i].value+"&";
}

alert(dataString); // You will receive all the name value pairs.

I trust this resolves your issue.

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

Error occurred while attempting to run 'postMessage' on the 'Window' object within GoogleTagManager

Recently, I encountered an error stating "postMessage couldn't be cloned". This issue seems to be affecting most of the latest browsers such as Chrome 68, Firefox 61.0, IE11, and Edge. Error message: Failed to execute 'postMessage' on &ap ...

"Failure encountered while trying to fetch JSON with an AJAX request

I am facing an issue with an ajax request. When I make the request with the property dataType: 'json', I get a parsererror in response. My PHP function returns the data using json_encode(), can someone assist me? On the other hand, when I make th ...

Access-Control-Allow-Origin causing a one-of-a-kind session problem

When trying to access data using cross-domain requests from multiple domains, I have included the following code in a PHP file at the backend: header("Access-Control-Allow-Origin: *"); Each time a new session is created for every request, resulting in a ...

Chrome and Firefox: Images cling together

I've encountered an issue with my recently launched website. Some images in a grid appear to be stuck together, but this problem only occurs in Firefox and Chrome browsers. Oddly enough, zooming in to around 110% then back to 100% seems to temporarily ...

What mistake have I made in my JavaScript code?

Data Entry: let name = 'Sophia'; console.log('Hello, my name is', + name + '.'); Result: SyntaxError: Unexpected identifier ...

React native and redux: Updating state with setState is not possible during an ongoing state transition

Currently in the process of developing an app utilizing React Native and redux, alongside Express js for handling Ajax requests. Encountering an issue where the data from my Ajax request fails to load, accompanied by the following warning: Warning: set ...

Having trouble installing gulp locally due to an error with ` ode_modulesansi-regex`

While attempting to set up Gulp on my Windows 10 system, I encountered an error during the local installation process. $ node -v v9.10.1 $ npm -v 5.6.0 I successfully installed Gulp globally: $ npm install --global gulp-cli $ gulp -v CLI version 2.0.1 ...

Unable to display values in Fusion Charts zoomline chart using the showValues chart property

I'm struggling to figure out how to display the data plot values with showValues: '1' in a zoomline chart using Fusion Charts. You can see and test it on this fiddle: http://jsfiddle.net/60oeahc1/4/ Is there a way to make this feature work ...

Transforming the format of multi-dimensional arrays in PHP

Is there a way to transform the initial array into the desired final array structure using PHP? Array ( [0] => Array ( [month] => 2007-02 [clicks] => 94 ) [1] => Array ( [month] => 2007-03 [clicks] => 6930 ) [2] => Ar ...

Tips for stopping Ajax page reload when a button is clicked

Summary: I have successfully implemented an Ajax POST method within a JQuery button click event, preventing page refresh by using evt.preventDefault();. However, I encountered an issue when adding $createForm.submit(); to trigger validation before submitt ...

I offer a unique service that creates custom toolbars with a variety of classes to choose from

menu component import { QueryParam } from "./query-param"; import { QueryRouterLink } from "./query-router-link"; export class Menu { link: string; name: string; queryParam: QueryParam[]; queryRouterLink?: QueryRouterLink; } QueryParam class e ...

Load the template.html file using pure JavaScript without relying on jQuery

At the moment, I am implementing a template load process in the following way: $('#mydiv').load("template1.html") While I am currently relying on jQuery for this functionality, I am curious to know how I can achieve the same outcome using pure ...

The video does not begin playing automatically after utilizing react-snap

I included a background video in my react app that auto-plays upon page load and functions perfectly. Here is the JSX code I used: <video autoPlay loop style={{ backgroundImage: `url(${topVideoImage})`, }} muted playsInl ...

Achieve seamless integration of PHP function execution with Javascript onClick without the need for page

After delving into my research, it seems like Ajax and/or JQuery may be the way to go for what I'm trying to achieve. However, I wanted to double-check before moving forward in that direction. The task at hand involves using a javascript onclick func ...

What is the process for storing a block of JavaScript code within a JavaScript variable?

My objective is to assign a block or JavaScript code into a JavaScript variable so that I can display a block similar to the one shown below in my Vue template. https://i.sstatic.net/rE0UV.png It is possible to add a block of HTML code into a JavaScript v ...

Sending File from React to Express Causes 404 Error

My current project setup involves a React application housed in a client folder and an Express server located in the root directory. Within the React app, there are functionalities for selecting files and submitting them. I aim to transfer these files from ...

Ways to dynamically modify page content following a successful submission without refreshing the page

I'm working on an MVC application and trying to update page content automatically without refreshing it using AJAX. I've been searching for a solution, but couldn't find anything that works for me. Specifically, I have a JStree where I want ...

The getJSON() function in jQuery's Ajax module appears to be failing to execute

Below is the code I am currently working with: <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $(&apos ...

The implementation of a Like Button in Django using JS and DOM resulted in a 404 error

I am facing an issue with the 'live' like/unlike button functionality in Django and JavaScript DOM Upon clicking the button, an error is triggered POST http://127.0.0.1:8000/like/24 404 (Not Found) likePost @ javascripts.js:24 (anonymous) @ java ...

Error: Node Command Line Tool cannot be located using NVM bash

Creating a basic node CLI tool has proven to be challenging when using NVM. Despite installing node locally and attempting to switch to system with nvm use system, the CLI file remains inaccessible. The code snippet includes the following shell designation ...