K4tn1x K4tn1x - 1 year ago 68
Ajax Question

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

I have a

(using as searchbox) and when I submit this
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
, 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 Source

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.


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

if (isset($_GET["search"])) {
    $sth = $pdo->prepare("SELECT name FROM users WHERE name = '{$_GET["search"]}'");
    $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"/>

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

    $("#search-button").on("click", function (e) {
        $("#container").load("http://localhost/test/index.php?search=" + $("#search-value").val());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download