How to add more values to array on button click using PHP ?
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.
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.
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.
Steps of execution: We will first confirm that our “results.json” file is empty.
We will be running “http://localhost/index.html” in the browser. Type something in the input that you want to add to the array and click on the Add button. You will notice a dialog box appearing that confirms that the data is added, and it even shows the array. Repeat this a few times.
Check “results.json” file.