A while ago i made a search function with ajax and php. You could fill in a textbox with text and it would try to find a match among all countries stored in the database.
Now i am refining the code and making it PDO, but i broke something and i cant find out what.
this is my plain HTML
<head>
<title>Ajax</title>
<link href="style/style.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="scripts/Javascript.js"></script>
</head>
<body>
<div id="main">
<h1 class="title">Enter your country please</h1>
<input type="text" id="search" autocomplete="off" onchange="">
<h4 id="results-text">Showing results for: <b id="search-string">Array</b></h4>
<ul id="results"></ul>
</div>
</body>
here is my Jquery and javascript. note i have not changed anything to the HTML nor javascript so it can not by a type error.
$(document).ready(function() {
alert('asdf');
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}
return false;
}
$("input#search").live("keyup", function(e) {
clearTimeout($.data(this, 'timer'));
var search_string = $(this).val();
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}
else {
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
And here is my Search.PHP
<?php
class SearchEngine{
private $html;
public function __construct($conn){
$this->html = '<li class="result">
<h3>NameReplace</h3>
<a target="_blank" href="ULRReplace"></a>
</li>';
if (isset($_POST["query"])) {
$search_string = $_POST['query'];
}
else{
$search_string = '';
echo('Something went wrong, post query not set');
}
//$search_string = mysql_real_escape_string($search_string);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT * FROM country WHERE name LIKE "%' . $search_string . '%"';
$result = $conn->prepare($query);
$result->execute();
$result_array = $result->fetchAll();
foreach ($result_array as $result) {
$display_name = preg_replace("/" . $search_string . "/i", "<b>" . $search_string . "</b>", $result['name']);
$display_url = 'sadf';
$output = str_replace('NameReplace', $display_name, $this->html);
$output = str_replace('ULRReplace', $display_url, $output);
echo($output);
}
}
}
}
?>
The problem:
the Post query is never created, for this i made a isset so for now when there is no Post Query created. It will create a Post Query with value "B".
Any help will be much appreciated. Please be gentle i am new to Ajax and i rather want to understand than have the solution. Thank you
You're not point the right URL! Look:
You have pointed your ajax request to search.php :
$.ajax({
type: "POST",
url: "search.php",
But you have just a class in search.php. A class don't do anything by itself. You have to Instantiate and call its methods/functions. Please compare these 2 pieces of code:
<?php
//server.php
//Doing nothing
class SearchEngine{
private $html;
public function __construct($conn){
echo "I'm executing";
}
}
?>
let's say you have this in server.php
<?php
//server.php
//It will print "I'm executing" in the screen
class SearchEngine{
private $html;
public function __construct($conn){
echo "I'm executing";
}
}
$search = new SearchEngine($conn);
?>
To solve your original problem You have to to point your ajax to the page having the INSTANTIATION code, not the class, like this:
//index.php
//Let's suppose you have this code in your index.php
$SearchEngine = new SearchEngine($conn);
So your JQuery ajax code should looks like that:
$.ajax({
type: "POST",
url: "index.php",
As Mentioned by Sean, in the comments, the $.live jquery method is deprecated in your version of jQuery.
Try utilizing $.keyup instead
$("input#search").keyup(function() {
// stuff
});
Related
Hello I'm a beginner in Ajax and PHP so sorry if my question is useless or stupid. But I am trying to do a live search with ajax and I have looked over and over internet but nothing could help me... so here I am! :-) I have 4 files one for the html, one to connect to the database, one for jQuery and the last one for the script in php. I have looked on the console with chrome and I can see that the ajax works but there is no output and I have no idea why... I'll leave you the code below and an early thank you! Also there might be some French in the code but it's just the variables and I will secure my connection to the database later. Thank you again.
Html :
<html>
<head>
<meta charset="utf-8" />
<title>live search test</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche">
</div>
<br>
<div class="resultat" id="resultat">
</div>
</body>
</html>
PHP to connect to the database:
<?php
$host="localhost";
$user="root";
$password="";
$db="smartphone";
$conn=mysqli_connect($host,$user,$password,$db);
?>
jQuery:
$(document).ready(function(){
$("#recherche").keyup(function(){
var recherche = $(this).val();
var data = 'motclef = ' + recherche;
if (recherche.length > 1) {
$.ajax({
type : "GET",
url : "fetch.php",
data : data,
success : function(server_response){
$("#resultat").html(server_response).show();
}
});
}
});
});
And the script in PHP:
include'connect.php';
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn ->prepare($sql);
$req -> execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req -> fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result ->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
?>
Remove whitespace from 'motclef = '
var data = 'motclef= ' + recherche;
Other wise put underscore $_GET['motclef_'] in your PHP code(if you don't remove space then)
if (isset($_GET['motclef_'])) {
$motclef = $_GET['motclef_'];
$q = array('motclef' => $motclef. '%');
$sql = "SELECT name FROM smartphone WHERE name LIKE :motclef";
$req = $conn->prepare($sql);
$req->execute($q);
$count = $req->rowCount($sql);
if ($count == 1) {
while ($result = $req->fetch(PDO::FETCH_OBJ)) {
echo 'Smartphone :'.$result->title.' ';
}
}else {
echo "Aucun resultat trouvé pour:". $motclef;
}
}
Basically my program is a web page with 5 radio buttons to select from. I want my web app to be able to change the picture below the buttons every time a different button is selected.
My problem is coming in the JSON decoding stage after receiving the JSON back from my php scrip that accesses the data in mysql.
Here is my code for my ajax.js file:
$('#selection').change(function() {
var selected_value = $("input[name='kobegreat']:checked").val();
$.ajax( {
url: "kobegreat.php",
data: {"name": selected_value},
type: "GET",
dataType: "json",
success: function(json) {
var $imgEl = $("img");
if( $imgEl.length === 0) {
$imgEl = $(document.createElement("img"));
$imgEl.insertAfter('h3');
$imgEl.attr("width", "300px");
$imgEl.attr("alt", "kobepic");
}
var link = json.link + ".jpg";
$imgEl.attr('src', link);
alert("AJAX was a success");
},
cache: false
});
});
And my php file:
<?php
$db_user = 'test';
$db_pass = 'test1';
if($_SERVER['REQUEST_METHOD'] == "GET") {
$value = filter_input(INPUT_GET, "name");
}
try {
$conn = new PDO('mysql: host=localhost; dbname=kobe', $db_user, $db_pass);
$conn->setAttribute(PDO:: ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM greatshots WHERE name = :name');
do_search($stmt, $value);
} catch (PDOException $e) {
echo 'ERROR', $e->getMessage();
}
function do_search ($stmt, $name) {
$stmt->execute(['name'=>$name]);
if($row = $stmt->fetch()) {
$return = $row;
echo json_encode($return);
} else {
echo '<p>No match found</p>;
}
}
?>
Here's my HTML code where I am trying to post the image to.
<h2>Select a Great Kobe Moment.</h2>
<form id="selection" method="get">
<input type="radio" name="kobegreat" value="kobe1" checked/>Kobe1
<input type="radio" name="kobegreat" value="kobe2"/>Kobe2
<input type="radio" name="kobegreat" value="kobe3"/>Kobe3
</form>
<div id="target">
<h3>Great Kobe Moment!</h3>
</div>
And here's is what my database looks like:
greatshots(name, link)
name link
------ --------
kobe1 images/kobe1
kobe2 images/kobe2
kobe3 images/kobe3
Whenever I run the web app right now, the rest of the images on the page disappear and the image I am trying to display won't show up. I get the alert that "AJAX was a success" though, but nothing comes of it other than the alert. Not sure where I am going wrong with this and any help would be awesome.
As mentioned you should parse the JSON response using JSON.parse(json);.
Also, you should specifically target the div element with a simpler setup:
$("#target").append('<img width="300px" src="' + link + '.png"/>');
So I wish to replicate the following functionality in wordpress. Jquery calls a php file, which itself queries a mysql table, and returns the result encapsulated within an tag. How do I go about achieving this?:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
....
function initialize() {
....
feedData();
}
$(document).ready(function () { initialize(); });
function feedData() {
$(document).ready(function () {
$.ajax({
cache: false,
type: "POST",
async: false,
url: "page-gotw-search.php",
data:{"action=showcountries"},
success: function (data) {
$('#CountryList').append(data);
},
error: function (data, status, error) {
console.log(data);
console.log(status);
console.log(error);
}
});
});
}
</script>
<body>
<div style="width: 800px">
<div style="float: left">
<select id="CountryList" onchange="getRegion()" size="20"></select>
<select id="RegionList" size="20" onchange="getMap()"></select>
</div>
<div id="cityList" style="float: right"></div>
</div>
</body>
</html>
page-gotw-search.php
<?php
include_once("pdo_mysql.php");
pdo_connect("localhost","root","");
pdo_select_db("wpdb");
$action=$_POST["action"];
if($action=="showcountries"){
$showcountry = pdo_query("Select distinct meta_value from wp_usermeta where meta_key =?, pdo_real_escape_string('country_registration')");
if (!$showcountry) {
$message = 'Invalid query: ' . pdo_error() . "\n";
$message .= 'Whole query: ' . $showcountry;
die($message);
}else{
foreach($showcountry as $row){
echo '<option value=".$row[country_code].">.$row[country_name].</option>';
}
}
}
else if($action=="showregions"){
$country_id= $_POST["country_id"];
$showregion = pdo_query("Select region_code, region_name from regiontbl
WHERE country_id=?", pdo_real_escape_string($country_id));
if (!$showregion) {
$message = 'Invalid query: ' . pdo_error() . "\n";
$message .= 'Whole query: ' . $regionquery;
die($message);
}else{
foreach($showregion as $row){
echo '<option value=".$row[region_code].">.$row[region_name].</option>';
}
}
}
?>
Looks like you want to implement ajax into the wordpress.
I have a simple way to do this. Follow below given steps to use ajax calls in wordpress
add some code in footer.php
jQuery(‘#clickerid').change(function(){
var your_id = jQuery(‘#get_val').val();
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
jQuery.ajax({
cache: false,
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: ‘id='+ id + '&action=get_id',
success: function(data)
{
jQuery(‘#id').html(data);
}
});
});
Then use this ajax call into the functions.php
add_action( 'wp_ajax_get_your_action', 'prefix_ajax_get_your_action' );
add_action( 'wp_ajax_nopriv_get_your_action', 'prefix_ajax_get_your_action' );
function prefix_ajax_get_costofcare() {
// Do your php code used in ajax call and return it.
}
Ajax calls works via admin-ajax.php which is build in functionality provided by wordpress
I have been trying to make to make a page where i could select a customer and would get the corresponding customer details from a database.
It should look something like this:
<select id="select_customer">
<option value='1'>customer 1</option>
<option value='1'>customer 2</option>
</select>
public function getCustomerDetails($customerId) {
if(isset($customerId)) {
$customer = DB::getInstance()->query("select * from customers");
foreach($customer->results() as $customer) {
$str = "<li>{$customer->name}</li>";
$str .= "<li>{$customer->name_contactperson}</li>";
$str .= "<li>{$customer->email}</li>";
$str .= "<li>{$customer->address} {$customer->house_number}</li>";
$str .= "<li>{$customer->postalcode}</li>";
$str .= "<li>{$customer->city}</li>";
$str .= "<li>{$customer->country}</li>";
}
return $str;
}
return false;
}
What i now would like to do is to get the value from the select_customer post this with ajax to the getCustomerDetails method and get the corresponding details without a page reload.
I tried to make it work with ajax and with xAjax but i coulden't get it to work.
I tried this:
<?php include 'xajaxAIO.inc.php';
$xajax = new xajax();
$xajax->register(XAJAX_FUNCTION, 'getCustomers');
$xajax->processRequest(); ?>
<input type="button" onclick="xajax_getCustomerDetails(1);" value="Click Me" />
The other thing i tried was this:
<script>
document.getElementById('select_customer').addEventListener('change', function() {
var $userId = this.value;
$.ajax({
type: "POST",
url: "classes/invoice.php",
data: "getCustomerDetails("+$userId+")"
})
});
</script>
I dont get any error messages in my console but it seems like the requested function doesnt execute.
Anybody who could tell me how it could get this to work?
Thanks in advance!
I would recommend just sending $userId alone then call getCustomerDetails($userId) in the invoice.php page.
$.ajax({
type: "GET",
url: "classes/invoice.php",
data: $userId
})
});
OR
$.ajax({
type: "GET",
url: "classes/invoice.php&function=getCustomerDetails&userId="+$userId
dataType: "json", //Dont need this if youre returning a string
success: function(result) {
alert(result);
}
})
});
Then in the invoice page you could call the function using the $_GET variable like so:
$response = 'error;
if($_GET['function'] == 'getCustomerDetails'){
if(!empty($_GET['userId'])){
$_GET['userId'] = 0;
}
$userID = $_GET['userId'];
$response = getCustomerDetails($userID);
}
die(json_encode($response)); //for array
die($response); //for a string
If you use xajax framework... you need register the new function...
<?php include 'xajaxAIO.inc.php';
$xajax = new xajax();
$xajax->register(XAJAX_FUNCTION, 'getCustomers');
$xajax->register(XAJAX_FUNCTION, 'getCustomerDetails');
$xajax->processRequest(); ?>
<input type="button" onclick="xajax_getCustomerDetails(1);" value="Click Me" />
<?php function getCustomerDetails($id){
///////////////////////////////////////////////
///// And use framework xajax to response /////
///////////////////////////////////////////////
}?>
So far I have HTML:
<div id="box" style="width:400; height:400; margin-left:auto; margin-right:auto; margin-top:100;">
<h2>Enter a word</h2>
<input type="text" id="input" ></input>
</div>
<div id="suggest">
</div>
Javascript:
<script type ="text/javascript">
$(document).ready(function(){
$("#input").keyup(function(){
var input = $("#input").val();
$.ajax({
url: "PathToPHPFileThatConnectsToDatabaseAndRetreivesValues",
data: "input"+input,
success: function(msg){
alert(msg);
$("#suggest").html(msg);
}
});
});
});
</script>
PHP:
<?php
$dbh=mysql_connect ("localhost", "~", "~") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("~") or ("Database not found");
$input = $_REQUEST['input'];
$input = mysql_real_escape_string(trim($input));
$sql = "SELECT * FROM ~ WHERE ~ LIKE '%".$input."%'";
$data = mysql_query($sql);
$arrcnt = -1;
$dataArray = array();
while ($temp = mysql_fetch_assoc($data))
{
foreach($temp as $key=>$val) {
$temp[$key] = stripslashes($val);
$arrcnt++;
}
$dataarray[$arrcnt] = $temp;
}
$list = "<ul style='width:100;height:auto;'>";
foreach($dataArray as $val) {
$list .= "<li>".$val['DesiredColumnContainingDesiredData']."</li>";
}
$list .= "</ul>";
echo $list;
?>
Now, these codes are supposed to work together to autocomplete the div with id="suggest" then populate the text field with id="input" when selected ... I keep getting alert that reads: <ul style='width:100;height:auto;'></ul>
change ajax code like this,
$.ajax({
url: "PathToPHPFileThatConnectsToDatabaseAndRetreivesValues",
data: {"input":input},
success: function(msg){
alert(msg);
$("#suggest").html(msg);
}
});
The issue is because in php your variable name is different . You added $dataarray instead of $dataArray
Additionally for ajax
You can pass data as a string or as an object
data:{"input":input}
or
data:"input="+input
add type: 'POST' in ajax