John Mack
John Mack

Reputation: 119

Beginner AJAX search function

I am working on a instant search function, currently i am having trouble passing the variable from JS to PHP file. I am also unsure about what to do once i have the results from the query. Any help would be fantastic. This is my current standing.

ERROR

Undefined index: partialSearch in \php\search.php on line 4

test.php

<?php
session_start();
?>  
<!DOCTYPE html>
<html lang="en"> 
<head>

<meta charset="utf-8">
<title>AJAX SEARCH</title>

<link rel="stylesheet" href="stylesheets/base.css">
<link rel="stylesheet" href="stylesheets/skeleton.css">
<link rel="stylesheet" href="stylesheets/layout.css">

<script type="text/javascript"     src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function search(partialSearch){
$.ajax({url:"PHP/search.php",data: partialSearch,success:function(result){
$("#results").html(result);
 }});
 };
</script>

</head>
<body>
<div class="container">

    <div class="one-third column index">
    <h3>Search Our Site</h3>
    <p>Simply type into the search bar below the video, article you are looking for.</p>

    <input type="text" name="partialSearch"onkeyup="search(this.value)"/>
    <div id="results"></div>

    </div>

</div>

</body>
</html>

search.php

<?php
include 'config.php';

$partialSearch = $_POST['partialSearch'];

$stmt = $mysqli->prepare("SELECT Name FROM videos WHERE Name LIKE ? ");
$stmt->bind_param('s',$partialSearch);
$stmt->execute();
$stmt->bind_result($Name);
while ($row = $stmt->fetch()) {
$searchResults[] = $Name;
echo "<div>".$searchResults."</div>";
}

?>

Upvotes: 0

Views: 107

Answers (3)

user1299518
user1299518

Reputation:

By default, $.ajax calls sends a GET request, so your $_POST is not valid in your .php file, unless you specify a ..type:"POST".. variable in your $.ajax(.. settings.

Secondly, you need to change this:

$.ajax({url:"PHP/search.php",data: partialSearch,success:function(result){

to this:

$.ajax({url:"PHP/search.php",type:"POST",data:{partialSearch:partialSearch},success:function(result){

It's perfectly ok to pass an object of variables to send.

Upvotes: 0

sebilasse
sebilasse

Reputation: 4618

1.) You did not tell jQuery to post, e.g.

    $.ajax({ type: "POST", ... });

You can also use the shorthand ".post" :

    $.post{url:"PHP/search.php",data: partialSearch,success:function(result){ $("#results").html(result);

2.) The PHP thinks of a named POST variable. So your partialSearch must be an object like so

    partialSearch = { partialSearch : "I AM your variable, NOT the object holding me !!!" }

Upvotes: 0

xdazz
xdazz

Reputation: 160833

You should change

data: partialSearch

to

data: {partialSearch: partialSearch} // or {"partialSearch": partialSearch}, which is the same

Where partialSearch is the data's index name.

Upvotes: 1

Related Questions