Sobes.tech
Junior — Middle

What methods can be used to update data in a database when submitting a form on a web page?

sobes.tech AI

Answer from AI

Updating data in a database when submitting a form on a web page can be implemented in several ways:

  1. Submitting the form via POST method with server-side processing — the server receives the data, validates it, and updates the record in the database.

  2. Using AJAX (for example, with fetch or XMLHttpRequest) — sending data asynchronously without reloading the page, after which the server updates the database and returns the result.

  3. Using REST API — the frontend sends an update request via API, the server processes and updates the data.

Example with Python Flask and AJAX:

from flask import Flask, request, jsonify
app = Flask(__name__)

@app.route('/update', methods=['POST'])
def update_data():
    data = request.json
    # logic to update in database
    # e.g., update_record(data['id'], data['value'])
    return jsonify({'status': 'success'})

On the client side:

fetch('/update', {
  method: 'POST',
  headers: {'Content-Type': 'application/json'},
  body: JSON.stringify({id: 1, value: 'new data'})
}).then(response => response.json())
  .then(data => console.log(data));

This approach allows flexible and efficient data updates.