I have an AJAX autocomplete form. After many issues it works.
However I need help with three issues.
If the user type and result display, if the user backspace, the
results remain in schoollist. How do I clear schoollist
searchbox if is empty.
Some of the words contain letters like ë. When retrieved from the
database it display a ■ instead of ë.
If there is no results, it will display "School not found". If you click on school not found, it accepts the answer. I prevent clicking on "School not found?
HTML
<div class="ui-widget">
<label>What school does the child attend<input type="text" name="school" id="school" class="form-control" placeholder="Enter school Name"/></label>
<div id="schoollist"></div>
</div>
AJAX
$(document).ready(function(){
$('#school').keyup(function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#schoollist').fadeIn();
$('#schoollist').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#school').val($(this).text());
$('#schoollist').fadeOut();
});
});
PHP
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT School FROM Schools WHERE School LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['School'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
}
https://jsfiddle.net/47v1t3k4/1/
1- I think a simple empty before your AJAX call will solve the problem: $('#schoollist').empty();
2- Use <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> In your html, and also try to set the content type header of your response to utf-8 Like this: header('Content-Type: text/html; charset=utf-8');
3- To prevent click event if no result found you have to use off method:
$('#school').keyup(function(){
var query = $(this).val().trim();
$('#schoollist').empty();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#schoollist').fadeIn();
$('#schoollist').html(data);
if ( data.indexOf("School not found") > -1 ) {
// detach click event
$(document).off('click', 'li', go);
} else {
// attach click event
$(document).on('click', 'li', go);
}
}
});
}
});
function go(){
$('#school').val($(this).text());
$('#schoollist').fadeOut();
}
For 1. issue:
$(document).ready(function(){
// I added two new variables:
var $schoolInput = $('#school');
var $schoolList = $('#schoollist');
$schoolInput.on('keyup', function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$schoolList.html(data).fadeIn();
}
});
}
else { // It's answer for your 1. issue:
$schoolList.fadeOut().html('');
}
});
$(document).on('click', 'li', function(){
$schoolInput.val($(this).text());
$schoolList.fadeOut();
});
});
For 2. issue:
Probably your database has invalid charset. Try to use utf8_general_ci.
For 3. issue:
I suggest to do this if you find a list of schools then enter the response from the server to #schoollist - that is like now. Otherwise, if no school is found then pass a string such as 'notFound'. And then:
$(document).ready(function(){
// I added two new variables:
var $schoolInput = $('#school');
var $schoolList = $('#schoollist');
$schoolInput.on('keyup', function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
// 3. issue:
if(data == 'notFound') {
$schoolList.html('<div class="notFound">School not found</div>').fadeIn();
}
else {
$schoolList.html(data).fadeIn();
}
}
});
}
else { // It's answer for your 1. issue:
$schoolInput.val($(this).text());
$schoolList.fadeOut().html('');
}
});
$(document).on('click', 'li', function(){
$schoolInput.val($(this).text());
$schoolList.fadeOut();
});
// 3. issue
$(document).on('click', '.notFound', function(){
var text = $(this).text();
$schoolInput.val(text);
});
});
Related
i have implemented live search with jquery typeahead library, it is working fine for the case of data being received from database i have the issue on front end
right now the typeahead is working fine for displaying data what i want to do is add url in the href attribute of the li'sbeing generated from the dropdown but i havent still been able to even attach an onclick method with the li's here's my code so far.
HTML
<input autocomplete="off" id="type" placeholder="Search for product / category"/>
JAVASCRIPT
$('#type').typeahead({
source: function (query, result) {
$.ajax({
url: "<?php echo base_url()?>ajax_search/search2",
data: 'query=' + query,
dataType: "json",
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
}
});
PHP CI Model Function
public function search($query){
$keyword = strval($query);
$search_param = "{$keyword}%";
$conn =new mysqli($this->db->hostname, $this->db->username, $this->db->password , $this->db->database);
$countryResult[]=array();
$sql = $conn->prepare("SELECT * FROM category WHERE name LIKE ?");
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$countryResult[] = $row["name"];
}
echo json_encode($countryResult);
}
}
this is the html structure that is being generated when typeahead is called
this is what i have tried so far!
$(".typeahead").on( "click", "li", function() {
alert("1");
});
$(".typeahead .dropdown-item").delegate("click", function(){
alert("12");
});
$(".typeahead .dropdown-item").on("click", function(){
alert("123");
});
i copied one of the code from this thread stackoverflow thread but it is still not working for my case i have not idea why it is not working any help?
Since the element you are attaching the click event to will have been added to the DOM dynamically by typehead, you'll want to do so like this:
$('body').on('click', '.typeahead .dropdown-item', function() {
// do something
});
I am trying to create a chain of drop downs in a form. The first select is populating the second form, but I can't call a third from the results. I have figured out (I think) that it is a binding issue, but how would I go about correcting this.
The JavaScript on the page:
<script>
var selected_form_div = null;
var frm_submit_event = function(e){
var $this = $(this); // the button
//var frm = $this.closest(form);
var frm = $('#'+selected_form_div + " form");
console.log(frm);
console.log(frm.serialize());
e.preventDefault();
$.ajax({
type: "POST",
url: "classes/forms/ajaxPost.php",
data: frm.serialize(),
dataType: "text",
success: function($result) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
$('#'+selected_form_div).html($result);
},
error: function() {
alert('error handing here');
}
});
}
function loadSubSelects(value,form,select)
{
$.post("classes/forms/update_form.php",{catid : value,form : form,select : select},function(data)
{
jQuery('#sub_categories').html(data);
});
}
$(document).ready(function(){
$('._form_selector').click(function(e){
e.preventDefault();
var $this = $(this);
$.get('classes/forms/forms.php', {
form: $(this).attr('form_data')
},
function($result){
$('#'+$this.attr('form_div')).html($result);
//selected_form_div = $this.closest("form");
selected_form_div = $this.attr('form_div');
//console.log($result);
});
console.log($(this).attr('form_data'));
});
$(document).on("click", '.frm_submit_btn', frm_submit_event);
$('._pay').click(function(){
var $this = $(this);
console.log($this.attr('form_id'));
$('._form_pay').css('display', 'none');
$('#form_'+$this.attr('form_id')+'_pay').css('display','block');
});
});
function showForms(form,click_listen) {
jQuery.noConflict();
jQuery('form').hide();//hide initially
jQuery("#click_listen").click(function(e){
jQuery(form).toggle('fast');//or just show instead of toggle
});
}
function reportError(request) { alert("Something Went Wrong, Please Submit A Support Ticket.");}
</script>
and LoadSubSelects is the function in question, and the PHP results:
What I am trying to bind in the results (I think)
the PHP code:
$query="SELECT letter_id,letter_title FROM letter_template where letter_category_id = $catid";
$result = mysql_query ($query) or die(mysql_error());
echo'<select name="sselect1" class="e1" style="width:100% !important; height: 1.85em !important; color: #a8a8a8 !important; border-color:#d7d7d7 ! onChange="loadSubSelects(this.value,\'write_letter\',this.name)"><option value="0">Please Select A Letter</option>';
// printing the list box select command
while($catinfo=mysql_fetch_array($result)){
//Array or records stored in $nt
echo "<option value=\"".htmlspecialchars($catinfo['letter_id'])."\">".$catinfo['letter_title']."</option>";
}
echo"</select>";
echo htmlspecialchars($catinfo['letter_id']);
Any help would be most appreciated, thanks so much guys :)
I have this PHP CodeIgniter code where in the view I am getting input from a text field. Using AJAC I am trying to pass this value to the controller using GET request. The controller will then call a function from my model to retrieve a database record matching the search criteria.
For some reason it doesn't work. I tried to do a var dump in the controller to see if the value is passed by AJAX, but I am not getting anything. Any ideas what I am doing wrong and why I can't receive the form value in the controller?
View:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.13.3/jquery.min.js"</script>
<script language="Javascript">
$(document).ready(function () {
$('#submitbutton').click(function () {
$.ajax({
url: "../../index.php/testcontroller/getdatabasedata",
data: {
'searchvalue' : $('#inputtext').val()
},
method: 'GET'
}).done(function (data) {
var dataarray = data.split('##');
$('#question').html(dataarray[ 1 ]);
$('#answer1').html(dataarray[ 2 ]);
});
return false;
});
});
</script>
</body>
Controller
public function getdatabasedata()
{
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
$movie = $this->testmodel->findquestion($year);
$moviesstring = implode(",", $movie);
echo $moviesstring;
}
Model
function findquestion($searchvalue)
{
$this->db->where('answer1', $searchvalue);
$res = $this->db->get('questions');
var_dump($res)
if ($res->num_rows() == 0)
{
return "...";
}
$moviearray = $res->row_array();
return $moviearray;
}
Script:
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script language="Javascript">
$(document).ready(function ()
{
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
var data = {'searchvalue' : $('#inputtext').val() };
$.ajax ({
url : target_url,
type: 'GET',
data: data,
cache: false,
success: function(controller_data)
{
var dataarray = controller_data.split('#');
$('#question').html(dataarray[1]);
$('#answer1').html(dataarray[3]);
},
});
return false;
});
});
</script>
.bind("click",function() - add quotes to click event.
var dataarray = controller_data.split('#'); - split
data caracter must match character in implode function in controller.
Controller:
public function getdatabasedata(){
$this->load->model('testmodel');
$year = $this->input->get('searchvalue');
$movie = $this->testmodel->findquestion($year);
$separated = implode("#", $movie);
echo $separated;
}
Hope this helped.
I will share my usual ajax code that I use in my views , make sure your base url is correct
$("#submitbutton").bind("click",function()
{
var target_url = '<?php echo(base_url()."testcontroller/getdatabasedata") ; ?>';
$.ajax
(
{
url : target_url,
type: "GET",
// data: {'searchvalue' : $('#inputtext').val()},
cache: false,
success: function(data)
{
alert(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert("error during loading ....");
}
});
});// end loading via ajax
and in your controller just echo something
public function getdatabasedata()
{
//$this->load->model('testmodel');
//$year = $this->input->get('searchvalue');
//I TRIED TO DO A VARDUMP($YEAR) BUT I DON'T GET ANYTHING!
//$movie = $this->testmodel->findquestion($year);
//$moviesstring = implode(",", $movie);
//echo $moviesstring;
echo "hello";
}
Me and some mates have been trying to make a live search script on our search bar. Now this isn't going that well so now we are asking for ur help!
our external file to get the results is this :
$con = mysqli_connect('localhost', '*', '*', '*');
$key=$_POST['search'];
$query = ("select name, url from search where name LIKE '%{$key}%'");
$sql = $con->query($query);
while($row = $sql->fetch_array()){
echo json_encode($row);
}
and our script code looks like this :
<script>
$(document).ready(function(){
$( "#formGroupInputLarge" ).keyup(function() {
console.log( "Handler for .keyup() called." )
var string = $('#formGroupInputLarge').val();
$.ajax(
{
type: 'POST',
url: 'search.php',
data: {'search': string},
success: function(data){
var text= JSON.parse(data);
$("#suggesstion-box").show();
$("#suggesstion-box").html("<a href='#'>"+ text +"</a>");
$("#search-box").css("background","#FFF");
}
}
);
});
});
</script>
we've tried with multiple things like the next ones :
<script>
$(document).ready(function () {
$("#formGroupInputLarge").keyup(function () {
console.log("Handler for .keyup() called.");
var string = $('#formGroupInputLarge').val();
$.ajax(
{
type: 'POST',
url: 'search.php',
data: {'search': string},
success: function (data) {
var obj = eval('('+ data +')' );
console.log(obj['name']);
//var text = JSON.parse(data);
//$("#suggesstion-box").show();
//$("#suggesstion-box").html(text);
//$("#search-box").css("background", "#FFF");
}
}
);
});
});
</script>
but none of it seems to work. Please help us!
So many things could be wrong in your code !
You need to give more info on how each part behaves (error messages, etc).
Check this to get a good look at how everything work with AJAX, and nice and simple examples http://www.w3schools.com/php/php_ajax_intro.asp
I want to populate my div minimal_table through ajax onchange event based on the chosen dropdown value. The <div class="minimal_table"> is the area of my page that I want to update every time I choose a value from my dropdown form. However, after my contents load, it returns no values from my database. I have checked the value being passed in my javascript using alert but it returns a right value. I also notice that it seems like it doesn't return true in the other_function.php if(isset($val_id))line even if I already chosen a value in the dropdown. Can somebody help me point out what is the wrong of my codes and what I am lacking? Thanks a lot. Here are my codes:
my_courses.php (ajax part)
$(':input').change(function(event){
event.preventDefault();
$('.minimal_table').html('<img src="../images/loading_trans.gif" style="position:relative; margin:350px; margin-top:250px;" />');
alert($(this).val());
var val_id = $(this).val();
var postData = {'val_id':val_id};
$.ajax({
url: "../includes/other_functions.php",
async: false,
type: "POST",
data: postData,
dataType: "html",
success: function(data){
setTimeout(function(){
$('.minimal_table').html(data);
},2000);
console.log(data);
},
});
});
other_functions.php
<?php
function ajax_request_val(){
$val_id = $_POST['val_id'];
$field = "course_type";
if(isset($val_id)){
$plans = db::getTable('plan',$field,$val_id);
foreach ($plans as $plan) {
if (eventAccessLevel(null, $plan['plan_id']) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails(null, $plan['plan_id']);
$pid_shown[] = $plan['plan_id'];
}
}
$events = db::getTable('tbl_event',$field,$val_id);
foreach ($events as $event) {
if (!in_array($event['plan_id'], $pid_shown)) {
$event_id = $event['event_id'];
if (eventAccessLevel($event_id, null) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails($event_id, null);
}
}
}
return $course_array;
}
else{
$plans = db::getTable('plan');
foreach ($plans as $plan) {
if (eventAccessLevel(null, $plan['plan_id']) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails(null, $plan['plan_id']);
$pid_shown[] = $plan['plan_id'];
}
}
$events = db::getTable('tbl_event');
foreach ($events as $event) {
if (!in_array($event['plan_id'], $pid_shown)) {
$event_id = $event['event_id'];
if (eventAccessLevel($event_id, null) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails($event_id, null);
}
}
}
return $course_array;
}
}
?>
databaseconnect.php
public static function getTable($tableName,$field='',$type_id='') {
if (!self::$db) self::connect();
if(!empty($type_id)){
$tableName = self::$db->escape_string($tableName);
return self::getObjects('SELECT * FROM `' . $tableName . '` WHERE `'. $field .'` = `'. $type_id .'`;');
}
else{
$tableName = self::$db->escape_string($tableName);
return self::getObjects('SELECT * FROM `' . $tableName . '`;');
}
}
Output:
Initial load
Loading the form dropdown menu search
Choosing value from dropdown returns right value indicated by an alert
After content load (returns no value on the div mini_table)
In other_functions.php you define the function ajax_request_val().
As far as I can see, there is no call to that function within the same file, so when you call it with Ajax, you just define the function and never call it.
You make an ajax call to other_functions.php but that file only contains a function that is never called.
There are lots of ways to approach this and tidy it up a bit but to fix the problem quickly you could try putting this at the top of other_functions.php:
if(isset($_POST['ajax'])){ echo ajax_request_val(); }
and then change the data in your ajax call as follows
var postData = {val_id:val_id, ajax:1 }