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

You can send JavaScript Array as data in the AJAX request which generally require when need to send a group of related values e.g. pass all checked checkboxes values.

In the demonstration, I will initialize JavaScript Array with all checked checkboxes values and send it as AJAX data.

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

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 new config.php for establishing the database connection.

Completed Code

<?php

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

$con = mysql_connect($host, $user, $password) or die("Unable to connect");

// selecting database
$db = mysql_select_db($dbname, $con) or die("Database not found");

 

3. HTML

Created a form layout which has two input elements and multiple checkboxes. Displaying the entered information in <div class='details'> after saving it on MySQL database table

Completed Code

<div class="container">
  <div class="content">
   <h1>Enter Details</h1>
   <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 PHP file getData.php for sending AJAX request.

Store $_POST values in the variables, and converts $lang which contains an Array to string using implode() function.

Check "jQuery" text find in the $_POST array $lang or not.

Storing values in the userinfo table and return an Array 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 = mysql_query($sql);
$row = mysql_fetch_array($result);
$count = $row['cntuser'];

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

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

echo json_encode($return_arr);

 

5. jQuery

On submit button click getting input value and initializing the Array lang with checked checkboxes values.

Passing the initialized variables as data in AJAX request.

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

Enter your name, email, and checked checkboxes and click the submit button.

 


 

7. Conclusion

In this tutorial, I showed how you can use JavaScript Array as data in AJAX request and how you can handle it in AJAX file.

The passed JavaScript Array works as normal PHP Array in AJAX file.

You may check my Previous tutorial on Return JSON response from AJAX using jQuery and PHP.

Related Post

Spread the love

2 Comments

  1. Manny said:

    It doesn’t work for me, is the Download missing something?

    July 28, 2017
    Reply
    • Yogesh Singh said:

      What issue are you getting while implementing the code?

      If the issue is related to AJAX file then you can use mysql_error() to find the error related to the database.

      July 30, 2017
      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *