K4tn1x K4tn1x - 4 months ago 9
Ajax Question

How to reload div with other SQL query when submiting form?

I have a

HTML
form
(using as searchbox) and when I submit this
form
with a word inside I want to reload a div with the result of research.

For example:

In my div, I have a query like this :

SELECT * FROM users;


and I display all the
ids
,
names
, etc.

And when I submit the form I want to have a query like this :

SELECT * FROM users WHERE name=$_POST['search'];


and display in my div users who are matching to the research without reload all the page but just this div.

How can I do this please? Thank you and have a good day !

Answer

You can use jQuery load function. I wrote to you a simple use of this function, I hope that you are a guiding light to solve the problem:

Of course, you need to change the links to your work environment.

index.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

if (isset($_GET["search"])) {
    $sth = $pdo->prepare("SELECT name FROM users WHERE name = '{$_GET["search"]}'");
    $sth->execute();
    $result = $sth->fetchAll(PDO::FETCH_ASSOC);
    $response = array();
    foreach ($result as $responseIndex => $responseValue) {
        $response[] = $responseValue["name"];
    }
    die(implode(",", $response));
}
?>

<form method="GET" action="http://localhost/test/index.php">
    <input name="search" type="text" id="search-value" />
    <input type="submit" id="search-button"/>
</form>

<div id="container"></div>

<script>
    $("#search-button").on("click", function (e) {
        e.preventDefault();
        $("#container").load("http://localhost/test/index.php?search=" + $("#search-value").val());
    });
</script>
Comments