Jump to content

Learning AJAX - got stucked on the first example


B_CooperA
Go to solution Solved by requinix,

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
	}

}

}


?>
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.