Tengo una base de datos simple en un servidor (para pruebas). Este archivo PHP está en el servidor y funciona cuando abro la URL. (http://**.com/search.php?id=abc) Echo devuelve "30"
<?php $pdo = new PDO('mysql:host=*com; dbname=*test1', '*', '*'); $idV = $_GET['id']; $statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = :idV"); $statement->bindParam(':idV', $idV); $statement->execute(); while ($row = $statement->fetch(PDO::FETCH_ASSOC)) { $posV = $row['position']; }; echo $posV; ?>El HTML es solo para probar
<input type="text" id="txt1"> <button type="button" class="btn btn-info" id= "bt1">Info Button</button> <div id= "div1"> </div>Quiero que cuando ingrese un código en el campo de texto y presione el botón, el eco de PHP se muestre en la división. Sé que debería usar Ajax GET, pero probé muchas cosas y nada funcionó. ¿Me podrían ayudar por favor?
Editar: último intento: https://jsfiddle.net/qz0yn5fx/
<input type="text" id="txt1"> <button type="button" class="btn btn-info" id="bt1">Info Button</button> <div id="div1">Here </div> <script> $(document).ready(function() { $("#bt1").click(function() { $.ajax({ //create an ajax request to load_page.php type: "GET", url: "http://**.com/search.php?id=a10 ", dataType: "html", //expect html to be returned success: function(response){ $("#div1").html(response); alert(response); } }); }); }); </script>Mejor no mires el siguiente Fiddle, acabo de copiar todos los primeros intentos:
Simplemente podría usar una solicitud POST simple en lugar de una solicitud GET.
<form id="search" name="search" method="post"> <input type="text" id="txt1" name="search_input"> <button type="submit" class="btn btn-info" id="bt1">Info Button</button> </form> <div id="div1">Here </div> $(document).ready(function(){ $("#search").on("submit", function(e){ e.preventDefault(); $.post("/search.php", $("#search").serialize(), function(d){ $("#div1").empty().append(d); }); }); });Y luego en tu PHP, (no olvides usar try{}catch{}):
try { $pdo = new PDO('mysql:host=*com; dbname=*test1', '*', '*'); $pdo -> setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); $idV = (isset($_POST['search_input'])) ? $idV = $_POST['search_input'] : exit('The search was empty'); $statement = $pdo->prepare("SELECT position FROM idtabelle WHERE idnumber = ?"); $statement->bindParam(1, $idV); $statement->execute(); foreach($statement -> fetchAll() as $row){ echo $row['position']; } $pdo = null; } catch (PDOException $e) { die($e -> getMessage()); }Creo que esto debería funcionar (no lo he probado). Avíseme si no funciona y lo probaré y lo corregiré.