Miha Šušteršič
Miha Šušteršič

Reputation: 10052

$(form id).serialize() returns empty string

I have a simple search form whose content I want to send to my php query as a POST request. I'm using AJAX to send it, and so far everything works fine, but for some reason instead of sending the actual value of the input field, it always sends an empty string.

Can someone please explain what I'm doing wrong here?

my html:

<form id="searchbox">
    <input type="text" placeholder="author, title, keyword...">
    <input type="submit" value="Search">
</form>

my js (the console.log line is there in order to see what's getting posted, ie for checking what's wrong with my code):

$("#searchbox").submit(function(e) {
    e.preventDefault();
    console.log($("#searchbox").serialize());
    $.post(
        "db_queries/all_articles.php",
        $( "#searchword" ).serialize(),
        function(data) {
            console.log(JSON.parse(data));
        } //end response function
        ); //end search article POST request
})

my php:

try {
    $hostname = "localhost";
    $username = "root";
    $password = "";

    $db = new PDO("mysql:host=$hostname;dbname=topdecka_PTC",$username, $password);

    if (!empty($_POST)) {
        $query = $db->prepare('SELECT * FROM articles WHERE title = :title');
        $query->execute(array(':title' => 'test1'));

        $result = $query->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($result);
        die();
    } 
    else {
        $query = $db->prepare('SELECT * FROM articles');
        $query->execute();

        $result = $query->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($result);
        die();
    }
} catch (PDOException $e) {
    echo "Error!: " . $e->getMessage() . "<br/>";
    die();
}

Upvotes: 1

Views: 117

Answers (1)

Vince
Vince

Reputation: 3286

Your input tags must have a name attribute in order to be serialized.

Upvotes: 1

Related Questions