Hi
Can I use the ajax to update a form feild by get a value of another feild on the same page(without submiting the page). This process involves the mysql as well.

Dani AI

Generated

As and pointed out, the typical pattern is: watch the source field in JavaScript, call a server endpoint (AJAX/fetch), let the server query MySQL and return JSON, then update the target field. Below is a compact, modern example and practical tips tuned for a form on the same page.

A minimal client-side pattern (debounced to avoid hammering the DB):

<!-- HTML -->
<input id="source" name="sku" />
<input id="target" name="price" readonly />

<!-- JS -->
<script>
const source = document.getElementById('source');
const target = document.getElementById('target');
let timer;

source.addEventListener('input', function() {
  clearTimeout(timer);
  const q = this.value.trim();
  if (!q) { target.value = ''; return; }
  timer = setTimeout(() => {
    fetch('/lookup.php?q=' + encodeURIComponent(q))
      .then(r => { if (!r.ok) throw new Error(r.status); return r.json(); })
      .then(data => { target.value = data.value || ''; })
      .catch(e => { console.error('lookup error', e); });
  }, 300);
});
</script>

A safe, simple server-side sketch in PHP (use your own credentials and table/column names):

<?php
header('Content-Type: application/json; charset=utf-8');
if (!isset($_GET['q'])) { http_response_code(400); echo json_encode(['error'=>'missing']); exit; }
$q = $_GET['q'];

$mysqli = new mysqli('DB_HOST','DB_USER','DB_PASS','DB_NAME');
if ($mysqli->connect_errno) { http_response_code(500); echo json_encode(['error'=>'db']); exit; }

$stmt = $mysqli->prepare('SELECT price FROM products WHERE sku = ? LIMIT 1');
$stmt->bind_param('s', $q);
$stmt->execute();
$res = $stmt->get_result();
$row = $res->fetch_assoc();
echo json_encode(['value' => $row ? $row['price'] : '']);
$stmt->close();
$mysqli->close();
?>

Quick tips and cautions:

  • Always use prepared statements to avoid SQL injection.
  • Use debounce (shown) to reduce queries on fast typing.
  • Test with browser DevTools Network/Console: check request URL, response code, and JSON payload.
  • If the endpoint is cross-origin, add correct CORS headers.
  • For sensitive operations use POST and CSRF protection; for simple lookups GET is fine.
  • Return clear error JSON and proper HTTP status codes to make debugging straightforward.

This pattern updates the form without submitting the page and keeps server logic separated and auditable.

Recommended Answers

All 2 Replies

yes you can use ajax for this purpose. as minitauros said.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.