Background: I am attempting to run some AJAX on keyup in a search box that will go to the database for a lookup, then return the results without refreshing the page.
The Problem: I'm not confident that it's actually connecting to my database. I've tested the connection using THIS METHOD, and it says that it's successful for the credentials I'm using. However, I can change the host from locahost to www.MYDOMAINNAME.com OR the server name from my cPanel, and it still says it's a successful connection. If it's successful, then why isn't it running my SQL?
The Question: Is there something wrong with my code below, and if not, is there a better way for me to test what's happening?
Notes: The output in my console is "Error [object Object]". It's hitting search.php successfully, so I don't think it's a file path issue. I also ran the PHP on page load instead of doing it through AJAX and everything seemed to work just fine. I was able to get some results back when I hard-coded a value for $query.
File Structure:
(ROOT FOLDER)
index.php (where the form is)
(PHP FOLDER)
search.php
(JS FOLDER)
search.js
HTML:
<form action="php/search.php" method="post">
<input type="search" class="main-search" name="query" />
<div class="btn btn-lg btn-primary">Search</div></form>
</form>
jQuery:
$(function() {
$(".main-search").keyup(function() {
search($(this).val());
});
});
function search(query) {
$.ajax({
url:"./php/search.php",
type:"POST",
dataType:"json",
data: { query:query },
success: function(data) {
$(".result").html(data);
},
error: function(data) {
$(".result").html(data);
}
});
}
PHP:
<?php
$query = $_POST["query"];
$link = mysqli_connect('localhost', 'USER', 'PASS') or die ('Error connecting to mysql: ' . mysqli_error($link));
mysqli_select_db($link, 'DB_NAME');
/* check connection */
if (mysqli_connect_errno()) {
echo mysqli_connect_error();
exit();
}
/* Select queries return a resultset */
if ($result = mysqli_query($link, "SELECT actual FROM icons WHERE synonym = '$query'")) {
$row = mysqli_fetch_array($result);
echo $row["actual"];
mysqli_free_result($result);
}
else {
echo "No results found.";
}
mysqli_close($con);
?>