1

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();
}

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

now it's submitting name=value (in my case that's searchword=test). Could you suggest how to use the value as a php variable?
@MihaŠušteršič, you should be able to access it in php like $_POST{'searchword'}
I guess the ajax part is fine now, and I need to debug my php. It's still returning 2 objects (ie it runs the second block of the if/else statement), but I guess that's another question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.