Advertisement
Guest User

Untitled

a guest
Apr 25th, 2017
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.32 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Ajax with php</title>
  5. </head>
  6. <body>
  7. <input type="text" id="search-box" placeholder="type something..">
  8. <br><br><br>
  9. <h2>Ajax Results:</h2>
  10. <div id="result">Waiting for response...</div>
  11.  
  12. <script type="text/javascript" src="js/script.js"></script>
  13. </body>
  14. </html>
  15. //the first thing to do is to target your input box
  16. // targeting the input box
  17. var inputBox = document.getElementById('search-box');
  18. //attaching an event handler with the inputBox
  19. inputBox.onkeyup = function(){
  20.  
  21. // alert(inputBox.value);
  22. //declare a variable.it can be any name
  23. var http = null;
  24.  
  25. //checking for browser type
  26. if(window.XMLHttpRequest){
  27. //creating an object
  28. //Safari,chrome,firefox,Opera, IE > 8
  29. http = new XMLHttpRequest();
  30. }else{
  31. http = new ActiveXObject('Microsoft.XMLHTTP');
  32. }
  33.  
  34. http.onreadystatechange = function(){
  35. if(http.readyState == 4 && http.status == 200){
  36. document.getElementById('result').innerHTML = http.responseText;
  37. //responseText = getting the response in a string of characters
  38. }
  39. };
  40.  
  41. // http.open("GET","data.php?v="+inputBox.value,true);
  42. // http.send(null);
  43.  
  44. http.open("POST","data.php",true);
  45. http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
  46. http.send('v='+inputBox.value);
  47.  
  48. };
  49. <?php
  50.  
  51. if(isset($_REQUEST['v']) && !empty($_REQUEST['v'])){
  52. // echo "Server says:".$_REQUEST['v'];
  53. $username = "root";
  54. $dsn = "mysql:host=localhost;dbname=country";
  55. $password = "0545804166";
  56. // $name = "";
  57.  
  58. try{
  59.  
  60. $db = new PDO($dsn,$username,$password);
  61. // echo 'working';
  62. $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  63.  
  64. $search = $_REQUEST['v'];
  65. $query = "SELECT `country_name` FROM `app_countries` WHERE `country_name` LIKE ':search'";
  66. $result = $db->prepare($query);
  67. $result->execute(array('search'=>$search));
  68. // $name = "%$name%";
  69. // $query=$db->prepare("SELECT * FROM `app_countries` WHERE `name` like :name");
  70. // $query->bindParam(':name',$name);
  71. // $query->execute();
  72. if($result->rowCount() > 0){
  73. while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
  74. echo $row['country_name']."<br>";
  75. }
  76. }
  77.  
  78. }catch(PDOException $ex){
  79.  
  80. // echo "connection failed".$ex->getMessage();
  81. }
  82. }else {
  83. echo "Nothing matched your query";
  84. }
  85.  
  86.  
  87.  
  88.  
  89. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement