How to add more values to array on button click using PHP ? - GeeksforGeeks

02 Jul, 2021
In this article, we will learn to add elements to an existing array with the click of a button using PHP.
PHP is a server-side language, and it only responds to requests (GET, POST, PUT, PATCH, and DELETE). The button click action happens as a part of the client-side to directly call a PHP function.
We need an intermediary language to perform this action. In this case, we will be using JavaScript. When a user will click on the button, the button will call the JavaScript function. The function will then send a POST request to our PHP script on the server to append data to the array. 
Each time the button will be clicked, a new request will be sent to the PHP script and thus will reinitialize our array. To overcome this, we will store our array in a JSON file on the server, and then for each request, we will append data to it. We will be dealing with three files “index.html” containing text input and button, “data.php” which handles the request, read from JSON file and append data to it and “array.json” to store array.
 
Example:
index.html
<!DOCTYPE html><html>  <head>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">    </script></head>  <body>      <!--We are taking array elements from user-->    <input type="text" value="name" id="name" />      <!--It will call our JS function-->    <button type="button" id="add">Add</button>      <script>        $(document).ready(function () {            var he = $("#name").value;            $("#add").click(function () {                $.post(                    "data.php", {                        data: document.getElementById("name").value,                    },                    function (data, status) {                        alert("Data: " + data + "\nStatus: " + status);                    }                );            });        });    </script></body>  </html>
The following is the PHP code for “data.php” used in the above HTML file. We are using post() method of jQuery, to make a request.
data.php
<?php  if(isset($_POST['data'])) {    $data= $_POST['data'];    $inp = file_get_contents('array.json');    $tempArray = json_decode($inp);        if($tempArray) {        array_push($tempArray, $data);        $jsonData = json_encode($tempArray);    }    else {        $jsonData=json_encode(array($data));    }          file_put_contents('array.json', $jsonData);    $inp = file_get_contents('array.json');    $tempArray = json_decode($inp);    print_r($tempArray);}  ?>
We are handling the request along with the data sent to “data.php“. Whenever a request is sent, it opens the JSON file and reads the previous array from it. If there is no previous array i.e. the “array.json” file is empty then it creates an array. It then appends data to it.
Output:
Steps of execution: We will first confirm that our “results.json” file is empty.
empty file 
user entry screen
first entry
Check “results.json” file.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML  course.
HTML-Questions
PHP-function
PHP-Questions
Picked
HTML
PHP
Web Technologies
HTML
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
How to place text on image using HTML and CSS?
How to auto-resize an image to fit a div container using CSS?
How to pop an alert message box using PHP ?
PHP in_array() Function
How to pass a PHP array to a JavaScript function?
PHP | Converting string to Date and DateTime
How to execute PHP code using command line ?