How to Send JavaScript Array to the AJAX using jQuery and PHP

The process of sending JavaScript arrays to the server-side using AJAX is a frequent requirement in web development. JavaScript arrays allow us to store and manage data in a structured format.

This can be used to pass the group of related values as data to the $.ajax for processing and get the response.

E.g. pass all checked checkboxes values, selected values from the list.

In this tutorial, you will learn how to send a JavaScript array to the server-side using AJAX, jQuery, and PHP with a live example.

How to Send JavaScript Array to the AJAX using jQuery and PHP


Table of Content

  1. Create a Table
  2. Create file for Database connection
  3. HTML Layout
  4. AJAX – Receiving the JavaScript Array in PHP
  5. jQuery – Sending the JavaScript Array to Server-side using AJAX
  6. Demo
  7. Conclusion

1. Create a Table

I am using userinfo table in the example.

CREATE TABLE `userinfo` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `email` varchar(100) NOT NULL,
  `lang` varchar(100) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

2. Create a file for Database connection

Create a config.php file for the database connection.

<?php

$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
   die("Connection failed: " . mysqli_connect_error());
}

3. HTML Layout

Create a basic form layout that includes two input elements, multiple checkboxes, and a button.

To ensure that the data is sent correctly, make sure to use the same name attribute for the checkboxes, such as name="prolang".

Once the AJAX request is successful, the data received from the server can be displayed in the <div class='details'> element.

<div class="container">
    <div class="content">
         <h2>Enter Details</h2>
         <div class="element">
              <input type="text" id="txt_name" placeholder="Name">
         </div>

         <div class="element">
              <input type="email" id="txt_email" placeholder="email">
         </div>

         <div class="element">
              <div>Languages you now?</div>
              <input type="checkbox" name="prolang" value="JavaScript"> JavaScript <br/>
              <input type="checkbox" name="prolang" value="jQuery"> jQuery <br/>
              <input type="checkbox" name="prolang" value="AngularJS"> AngularJS <br/>
              <input type="checkbox" name="prolang" value="NodeJS"> NodeJS <br/>
              <input type="checkbox" name="prolang" value="TypeScript"> TypeScript <br/>
         </div>

         <div class="element">
              <input type="button" value="Submit" id="submit">
         </div>
    </div>

    <div class="details">
         Name : <span id="name"></span><br/>
         Email : <span id="email"></span><br/>
         Languages : <span id="lang"></span><br/>
         jQuery : <span id="foundjquery"></span>
    </div>
</div>

4. AJAX – Receiving the JavaScript Array in PHP

To handle AJAX requests, create a file named getData.php. In this file, retrieve the values from the $_POST.

Check if the $_POST['lang'] variable contains the string “jQuery”. If it does, convert the array into a string using the implode() function. This is required as MySQL does not support storing arrays. You can also store it in serialized form using serialize() function.

After that, store the retrieved values into the userinfo table. Initialize a new array called $return_arr with the stored values, and return it in the JSON format. This will enable you to send the data back to the client-side.

<?php
include "config.php";

$name = $_POST['name'];
$email = $_POST['email'];
$lang = $_POST['lang'];

$foundjquery = "Not found";
if(in_array('jQuery',$lang)){
    $foundjquery = "found";
}
// Converting the array to comma separated string
$lang = implode(",",$lang);

// check entry
$sql = "SELECT COUNT(*) AS cntuser from userinfo WHERE email='".$email."'";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result);
$count = $row['cntuser'];

if($count > 0){
    // update
    $updatequery = "UPDATE userinfo SET name='".$name."',lang='".$lang."' WHERE email='".$email."'";
    mysqli_query($con,$updatequery);
}else{

    // insert
    $insertquery = "INSERT INTO userinfo(name,email,lang) VALUES('".$name."','".$email."','".$lang."')";
    mysqli_query($con,$insertquery);
}
$return_arr = array('name'=>$name,'email'=>$email,'lang'=>$lang,"foundjquery"=>$foundjquery);

echo json_encode($return_arr);

5. jQuery – Sending the JavaScript Array to Server-side using AJAX

When the submit button is clicked, retrieve the input values and initialize an array called lang by looping through the checked checkboxes using the $("input[name='prolang']:checked") selector and the .each() function.

Passing the initialized variables as data in AJAX request.

data: {name:name,email:email,lang:lang}

Here, name and email are string type variables and lang is an Array variable.

Note – You can pass JavaScript Array variable as same as any other variable in AJAX request.

$(document).ready(function(){

    // submit button click
    $("#submit").click(function(){

        var name = $("#txt_name").val();
        var email = $("#txt_email").val();
        var lang = [];

        // Initializing array with Checkbox checked values
        $("input[name='prolang']:checked").each(function(){
            lang.push(this.value);
        });

        if(email != ''){
            $.ajax({
                url: 'getData.php',
                type: 'post',
                data: {name:name,email:email,lang:lang},
                dataType: 'JSON',
                success: function(response){
                    
                    $('.details').show();

                    // selecting values from response Object
                    var name = response.name;
                    var email = response.email;
                    var lang = response.lang;
                    var foundjquery = response.foundjquery;

                    // setting values
                    $('#name').text(name);
                    $('#email').text(email);
                    $('#lang').text(lang);
                    $('#foundjquery').text(foundjquery);
                }
            });
        }
    });

});

6. Demo

View Demo


7. Conclusion

Passing a JavaScript array variable in the $.ajax() method is as simple as passing any other variable.

You can use it as a typical PHP array variable in the PHP script. The data is sent and received accurately with this method, and it can be stored in the database or altered as necessary.

You can also view this tutorial to learn how to send JSON response from AJAX file and handle it using jQuery.

If you found this tutorial helpful then don't forget to share.