Using AJAX and PHP to Save Multiple Form Inputs to a Database
AJAX (Asynchronous JavaScript and XML) enables real-time data exchange between a web browser and a server without refreshing the page. In this context, it can be employed to transfer form inputs to a database using PHP.
Implementation
HTML Form
Generate a form with multiple input fields, ensuring that their names correspond to the PHP $_POST variable you intend to access.
Ajax Function
Craft a JavaScript function like the one below to handle form submission:
function saveData() { // Collect all input values var inputs = $("input[type=text]"); var data = {}; $.each(inputs, function() { data[$(this).attr("name")] = $(this).val(); }); // Convert data to JSON var jsonData = JSON.stringify(data); // Send data to PHP file via AJAX $.ajax({ url: "save.php", type: "POST", data: { data: jsonData }, dataType: "json", success: function(response) { if (response.success) { alert("Data saved successfully."); } else { alert("Error saving data."); } } }); }
PHP Script
In save.php, decode the JSON data and perform the database operations:
<?php // Decode JSON data $data = json_decode($_POST['data']); // Connect to database and execute query // ... // Prepare response $response = array(); if ($result) { $response['success'] = true; } else { $response['success'] = false; } // Encode response as JSON and echo echo json_encode($response);
Additional Notes
The above is the detailed content of How Can I Use AJAX and PHP to Save Multiple Form Inputs to a Database?. For more information, please follow other related articles on the PHP Chinese website!