Jump to content

Learning AJAX - got stucked on the first example


B_CooperA

Recommended Posts

Hello, guys. I recently started to take a closer look into the world of AJAX. I'm trying to create a live search application, but for some reason it doesn't return the values from the database although it's still does something when I checked it with Googles "Inspect Element" tool. The only response I got with that tool is "This request has no responsive data available".

 

I have two files, index.php and search.php. Underneath, I've pasted both of them. The search engine works fine without AJAX, tested that while ago.

 

index.php 

<!DOCTYPE html>
<html>
<head>
<title>Ajax Search Engine</title>
<link rel="stylesheet" type="text/css" href="css/style.css" media="all" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {

	$("#search").on("keyup", function() {

		var search = $("#search").val();

		$.ajax({
			type: "POST",
			url: "search.php",
			data: {search:search},
			success: function(res) {

				$("#userslist").html(res);
			}


		});

	});
});
</script>
</head>
<body>

<div id="search">

	<input type="text" name="search" id="search" placeholder="Search for users...">
	<button type="submit" class="search-icon"><span class="magnifier"></span></button>



</div>

<div id="userslist">

</div>
</body>
</html>

search.php

<?php

	try {

		$conn = new PDO("mysql:host=localhost;dbname=search","root", "");


	} catch (Exception $e) {

		$e->getMessage();
	}

if(isset($_POST['search']) && $_POST['search'] != "") {

	$stmt = $conn->prepare("SELECT * FROM users WHERE username LIKE :name ");
	$stmt->execute(array(
			':name' => '%'.$_POST['search'].'%'
		));

	if($stmt->rowCount() == 0) {

		echo "No users was found";

	} else {

		while($data = $stmt->fetch()) {
		?>

		<div class="user-details">
		<img src="images/<?php echo $data['userimg'];  ?>" class="small-img" />
		<span class="username"><?php echo $data['username'];?></span>
		<span class="location"><?php echo $data['location'];?></span>
		</div>

<?php
	}

}

}


?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.