1

I'm trying to send input from a textbox to my PHP script, but it's not working.

When I change (in my PHP file)

$naam = $_POST["naam"];

to

$naam = "Marvin";

It's working!

AJAX/HTML

<td><lable>Naam</lable></td>
<td><input name="serarchName" class="tagert" type="text" id="searchName"/></td>   

    <script>
             $(document).ready(function(){
            $("#searchName").change(function(){
                 var name = $("#searchName").val();
        $.ajax({
            'url': 'ontwikkelpunten.php',
            'method': 'post',
            'data': 
            {
                 naam: $("#searchName").val()
            },
            'dataType': 'json'
        }).done(function(data){
            console.log(data);

                });
            });
        });

PHP

    $naam = $_POST["naam"];

$stmt = $conn ->prepare("SELECT * FROM ontwikkelpunten WHERE naam = "$naam");
$stmt ->execute();
$myarr = array();
while($data = $stmt -> fetch()){
    $myarr[] = $data;
}
echo json_encode($myarr);
11
  • $conn ->prepare("SELECT * FROM ontwikkelpunten WHERE naam = "$naam"); should be $conn ->prepare("SELECT * FROM ontwikkelpunten WHERE naam = '" . $naam . "'"); Commented Jul 15, 2018 at 12:22
  • You need to concatenate the variable $naam to the query as suggested by Nick Parsons.. Commented Jul 15, 2018 at 12:23
  • @NickParsons No it shouldn't. What's the point in preparing a query when you don't bind any parameters anyway? Besides that, it looks like there are a couple of things wrong with his code. Commented Jul 15, 2018 at 12:23
  • Are you using PDO or MySQLi? Commented Jul 15, 2018 at 12:24
  • 1
    @icecub dataType: specifies the type of the response, not the type of the request. Commented Jul 15, 2018 at 13:09

1 Answer 1

3

You're not substituting the parameter into the query correctly.

$naam = $_POST["naam"];

$stmt = $conn ->prepare("SELECT * FROM ontwikkelpunten WHERE naam = :naam");
$stmt->bindParam(":naam", $naam);
$stmt ->execute();
$myarr = array();
while($data = $stmt -> fetch()){
    $myarr[] = $data;
}
echo json_encode($myarr);
Sign up to request clarification or add additional context in comments.

Comments

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.