Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html>
- <head>
- <title>Ajax with php</title>
- </head>
- <body>
- <input type="text" id="search-box" placeholder="type something..">
- <br><br><br>
- <h2>Ajax Results:</h2>
- <div id="result">Waiting for response...</div>
- <script type="text/javascript" src="js/script.js"></script>
- </body>
- </html>
- //the first thing to do is to target your input box
- // targeting the input box
- var inputBox = document.getElementById('search-box');
- //attaching an event handler with the inputBox
- inputBox.onkeyup = function(){
- // alert(inputBox.value);
- //declare a variable.it can be any name
- var http = null;
- //checking for browser type
- if(window.XMLHttpRequest){
- //creating an object
- //Safari,chrome,firefox,Opera, IE > 8
- http = new XMLHttpRequest();
- }else{
- http = new ActiveXObject('Microsoft.XMLHTTP');
- }
- http.onreadystatechange = function(){
- if(http.readyState == 4 && http.status == 200){
- document.getElementById('result').innerHTML = http.responseText;
- //responseText = getting the response in a string of characters
- }
- };
- // http.open("GET","data.php?v="+inputBox.value,true);
- // http.send(null);
- http.open("POST","data.php",true);
- http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
- http.send('v='+inputBox.value);
- };
- <?php
- if(isset($_REQUEST['v']) && !empty($_REQUEST['v'])){
- // echo "Server says:".$_REQUEST['v'];
- $username = "root";
- $dsn = "mysql:host=localhost;dbname=country";
- $password = "0545804166";
- // $name = "";
- try{
- $db = new PDO($dsn,$username,$password);
- // echo 'working';
- $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $search = $_REQUEST['v'];
- $query = "SELECT `country_name` FROM `app_countries` WHERE `country_name` LIKE ':search'";
- $result = $db->prepare($query);
- $result->execute(array('search'=>$search));
- // $name = "%$name%";
- // $query=$db->prepare("SELECT * FROM `app_countries` WHERE `name` like :name");
- // $query->bindParam(':name',$name);
- // $query->execute();
- if($result->rowCount() > 0){
- while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
- echo $row['country_name']."<br>";
- }
- }
- }catch(PDOException $ex){
- // echo "connection failed".$ex->getMessage();
- }
- }else {
- echo "Nothing matched your query";
- }
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement