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

An Array is used to store multiple values in a single variable.

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, I show how you can pass JavaScript Array to an AJAX request with an example.

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


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. PHP
  5. jQuery
  6. Demo
  7. Conclusion

1. Table structure

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
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a config.php file for the database connection.

Completed Code

<?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

Create a simple form layout that has two input elements, multiple checkboxes, and a button.

Here, I used the same name="prolang" on the checkboxes.

Display the AJAX response on successful callback in <div class='details'>.

Completed Code

<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. PHP

Create a new getData.php file.

Store $_POST values.

$_POST['lang'] contains an Array so first check whether it contains 'jQuery' string or not.

Convert it into string using implode() method for storing in the MySQL table.

Store values in the userinfo table and initialize $return_arr Array with values and return it in JSON format.

Completed Code

<?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

On submit, button click gets input values and initializing the Array lang with checked checkboxes values by looping on $("input[name='prolang']:checked") selector using .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.

Completed Code

$(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

You can simply pass a JavaScript Array variable in the $.ajax as any other variable.

On PHP script you can directly use it as a normal PHP Array.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

11 thoughts on “How to Send JavaScript Array to the AJAX using jQuery and PHP”

  1. I need result in a database like,
    id name email java script jquery anjularJs nodaljs ( Columns)
    ———————————————————–
    1 sanjeev [email protected] java script nodaljs (Rows)

    Suppose I selected any two languages not one lanuage (javascript, nodaljs), How it inserted in database each columns (Of Language, eg: javascript, jquery, anjularjs, nodaljs).

    Reply
  2. Hello, I am new at Javascript but I am thinking wouldn’t it better if you send the actual array(‘hello’, 1=>array(‘another’=>’hellowww’, ‘yes’)) would it work?

    Reply

Leave a Comment