Why don't I see any value from autocomplete search in jQuery - codeigniter

Why can't I see any value suggestion from text input. I already use autocomplete code with JSON and jQuery. But no value is displayed in the text input
bookstore/views/admin/auto_complete.php
<script>
$('#swSearch').keypress(function () {
var dataObj = $(this).closest('form').serializeArray();
$.ajax({
url: 'http://localhost/boostore/admin_d_book_groups/search',
data: dataObj,
dataType: 'json',
success: function (data) {
$("#suggestion_tab").html('');
$.each(data.name, function (a, b) {
$("#suggestion_tab").append('<li>' + data.b + '</li>');
});
// Display the results
///alert(data);
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
</script>
<div id="swSearch">
<form>
<input type="text" value="" id="swSearch" class="swSearch" />
</form>
<div class="suggestion_tab" id="suggestion_tab"></div>
</div>
Admin_d_book_groups controller
function search(){
$searchterm = $this->input->post('search_hotel');
echo json_encode($this->d_book_groups->sw_search($searchterm));
}
d_book_groups_model
function sw_search($searchterm)
{
$query = $this->db->order_by("bg_id", "desc")->like('bg_name', $searchterm, 'after')->get('d_book_groups');
$data = array();
foreach ($query->result() as $row)
{
$data[] = $row->bg_name;
}
return $data;
//return mysql_query("select * from hotel_submits where name LIKE '".$searchterm."'");
}

Is $config['compress_output'] = TRUE; in your application/config/config.php?
If it is, you can't output content directly from the controller methods. You must use a view. You can create a view as simple as:
<?php echo $response;
and just pass the json data like this:
function search()
{
$searchterm = $this->input->post('search_hotel');
$data['response'] = json_encode($this->d_book_groups->sw_search($searchterm));
$this->load->view('ajax/json_response', $data);
}

I dont know why, but you make a mistake in this code:
$.each(data.name, function (a, b) {
$("#suggestion_tab").append('<li>' + data.b + '</li>');
});
You can not use "data.b" in $.each method, b is an object of data.name
for more help, actually "b" equal to data.name[a]
(data.name[a] == b)
So data.b is false, (data.name[a] == b) && data.name[a] != data.b
Use console.log(b) in $.each loop to see your array object (you need firefox and firebug extention)
$.each(data.name, function (a, b) {
console.log(b);
});
I think you want to put each name, in li element, if its true, use this code:
$.each(data, function (a, b) {
$("#suggestion_tab").append('<li>' + b.name + '</li>');
});
// here b.name == data[a].name

Related

Jest only - addEventListener ~ click assertion

I want to mock a normal dom click as indicated in the Jest docs:
test('displays a user after a click', () => {
document.body.innerHTML =
'<div>' +
' <span id="username" />' +
' <button id="button" />' +
'</div>';
// Use jquery to emulate a click on our button
$('#button').click();
expect($('#username').text()).toEqual('Johnny Cash - Logged In');
});
My function is as follows:
function clickTrack() {
const data = {};
document.addEventListener('click', function clicked(e) {
if (e.target.matches('a')) {
e.preventDefault();
data['click.Classes'] = e.target.classList;
data['click.ID'] = e.target.id;
data['click.Destination'] = e.target.href;
data['click.ElementText'] = e.target.innerText;
}
}, false);
return data;
}
And the test:
describe('Click Tracking', () => {
test('Clicking on an a tag will collect its information', () => {
clickTrack();
document.body.innerHTML = '<a class="j1 j2 j3" id="j" href="http://www.google.com/">Jest</a>';
document.getElementById('j').click();
expect(clickTrack()).toEqual({a:'b'});
});
});
I expect the output to be vaguely:
{
click.Classes: ["j1 j2 j3"]
click.Destination: "https://www.google.com/"
click.ElementText: "Jest"
click.ID: "j"
}
But an empty object is returned instead.
clickTrack hooks up a click event listener and returns a data object that will be updated whenever a click event happens, so you only have to call clickTrack once.
Right now you are calling it again after your click event so it is creating an additional click listener and returning a new, empty data object.
You'll also want to use e.target.text for the text and get the class names by calling split(' ') on e.target.className:
function clickTrack() {
const data = {};
document.addEventListener('click', function clicked(e) {
if (e.target.matches('a')) {
e.preventDefault();
data['click.Classes'] = e.target.className.split(' ');
data['click.ID'] = e.target.id;
data['click.Destination'] = e.target.href;
data['click.ElementText'] = e.target.text;
}
}, false);
return data;
}
describe('Click Tracking', () => {
test('Clicking on an a tag will collect its information', () => {
const data = clickTrack();
document.body.innerHTML = '<a class="j1 j2 j3" id="j" href="http://www.google.com/">Jest</a>';
document.getElementById('j').click();
expect(data).toEqual({
'click.Classes': ['j1', 'j2', 'j3'],
'click.Destination': 'http://www.google.com/',
'click.ElementText': 'Jest',
'click.ID': 'j'
}); // Success!
});
});

Ajax returned title value for tooltip isn't in one line, in Bootstrap

I am having a weird bug with dynamic created tooltips using ajax. I am creating a simple notes function. When data is coming from the database everything looks nice
But when i am creating a new note, using ajax i am creating the new entry in the db and then return the value to be shown in the new tooltip...But this is how it comes out to the user.
Is there a way to 'force' it to one line like the 1st image ?
Here is the code in question:
.js part
$('[data-toggle="tooltip"]').tooltip({
placement : 'left'
});
////////
var inText = $('.evnt-input').val(); //Whatever the user typed
$.ajax({
type: 'POST',
url: 'request.php',
data: {action:'addnotes', data: inText},
dataType: 'json',
success: function(s){
if(s.status == 'success'){
$('<li id="'+s.id+'">' + inText + ' ✕ </li>').appendTo('.event-list');
}
},
error: function(e)
{
console.log('error');
}
});
.php part
if ($_POST["action"] == "addnotes"){
function addnotes($data)
{
$insert = db_query("insert into notes(description) values('$data')");
if($insert)
return db_inserted_id();
}
$data = $_POST['data'];
$status = addnotes($data);
if($status != ''){
$timestamp = strtotime(date('Y-m-d G:i:s'));
$curTime = date( 'F j, Y, g:i a', $timestamp );
$output = array('status'=>'success','id'=>$status, 'curTime'=>$curTime);
}
else
$output = array('status'=>'error');
echo json_encode($output);
}
I have an identical code with the .js part to show the notes when the page loads...of course that works fine.
Lol it was so easy.... I changed the .js part to this, to 'reinitialize' the tooptip:
if(s.status == 'success'){
var curTime = s.curTime;
$('<li id="'+s.id+'">' + inText + ' ✕ </li>').appendTo('.event-list');
$('[data-toggle="tooltip"]').tooltip({
placement : 'left'
});
}

flickr API does not provide any results

Hi I am trying this Flickr API, where I want to display title + image, for the first 3. But it's not working.
http://jsfiddle.net/28hEb/6/
var tag = "mount";
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=" + tag + "&tagmode=all& format=json&jsoncallback=?", function (data) {
$.each(data.items, function (index, item) {
$("<div>").html(item.title).appendTo("#content");
$("<img/>").attr("src", item.media.m).appendTo("#content");
if (index == 3) {
return false;
}
});
});
You have a syntax error:
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "mount",
tagmode: "any",
format: "json",
}, function (data) {
var $content = $('#content');
$.each(data.items, function (i, item) {
$("<div>").html(item.title.m).appendTo($content);
$("<img/>").attr("src", item.media.m).appendTo($content);
if (i == 3) {
return false;
}
});
});
Check this fiddle
The } should end before the callback. Hence the issue. Your browser's console should give you a hint of what the error is.

How can i define a variable in Json?

i want define a variable in Json callback.
Code;
$("select").change(function () {
var $variable = "";
$("select option:selected").each(function () {
$variable += $(this).text() + " ";
});
$("div.yaz").text($variable);
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON){
$('#result').empty();
$.each(JSON.$variable, function(i, program){
$('#result')
.append(program.isim +'<br />')
.append(program.bilgi+'<br />')
.append(program.adres+'<hr />');
});
});
})
.trigger('change');
program-bilgileri.php returns;
{
"programlar":[
{
"isim":"Zone Alarm",
"bilgi":"bilgisayarın güvenliğini sağlar",
"adres":"www.zonealarm.com"
},
{
"isim":"Opera",
"bilgi":"güvenli ve hızlı bir web tarayıcısıdır",
"adres":"www.opera.com"
},
{
"isim":"Photoshop",
"bilgi":"güçlü bir imaj işleme yazılımıdır",
"adres":"www.adobe.com"
}
]
}
The problem is here "$.each(JSON.$variable, function(i, program)" if I define $variable in JSON it isn't working.
Any idea?
The problems i see are
Inside the change event you are using $("select option:selected") which finds all select elements in the page, and not the changed one only.
use $(this).children('option:selected') instead.
I am assuming that you are allowing multiple selection on the select element and that is why you are doing += with the $variable.. (you are also adding a space at the end). That means, though, that the variable will be something like "programlar " or "programlar somethingelse".
Your returned JSON though has a key of programlar. A single word, no spaces.. so when you do JSON[$variable] which is the correct way to access an element based on the name in a variable, it does not match.
If the <select> element does not allow multiple selection then the solution is
$("select").change(function() {
var $variable = $(this).children("option:selected").text();
$("div.yaz").text( $variable );
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON) {
$('#result').empty();
$.each(JSON[$variable], function(i, program) {
$('#result')
.append(program.isim + '<br />')
.append(program.bilgi + '<br />')
.append(program.adres + '<hr />');
});
});
}).trigger('change');
If indeed it is a multiselect and each option can appear in the JSON then you must check for each option found in the variable.
$("select").change(function() {
var $variable = $(this).children("option:selected").map(function(){
return $(this).text();
}).get();
$("div.yaz").text( $variable.join(' ') );
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON) {
$('#result').empty();
for (index=0, length = $variable.length; index < length; index ++) {
$.each(JSON[$variable[index]], function(i, program) {
$('#result')
.append(program.isim + '<br />')
.append(program.bilgi + '<br />')
.append(program.adres + '<hr />');
});
}
});
}).trigger('change');
Try
$.each(JSON['programlar'], function(i, program) ... );
This will iterate over this part of your returned JSON object from PHP:
{
"isim":"Zone Alarm",
"bilgi":"bilgisayarın güvenliğini sağlar",
"adres":"www.zonealarm.com"
},
{
"isim":"Opera",
"bilgi":"güvenli ve hızlı bir web tarayıcısıdır",
"adres":"www.opera.com"
},
{
"isim":"Photoshop",
"bilgi":"güçlü bir imaj işleme yazılımıdır",
"adres":"www.adobe.com"
}

Make a if loop according to what returns the ajax html(data)

I want to make a if loop according to what returns html(data), so how can I get in my ajax script a var returned by "form_treatment.php" ? I want to close the colorbox (a lightbox) containing myForm only if "form_treatment.php" returns a var PHP with a "true" value.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
$('#message').html(data);
// Make a if loop according to what returns html(data)
}
});
return false;
});
form.php :
<form method="post" action="form_treatment.php" >
<input type="text" name="user_name" value="Your name..." />
<button type="submit" >OK</button>
</form>
form_treatment.php :
if ( empty($_POST['user_name']) ){
$a = false;
$b = "Name already used.";
} else {
$already_existing = verify_existence( $_POST['user_name'] );
// verification in the DB, return true or false
if( $already_existing ){
$a = false;
$b = "Name already used.";
} else {
$a = true;
$b = "Verification is OK";
}
}
Try adding dataType : 'json' inside your $.ajax() call, and then, in your php file, respond with nothing but a json object such as:
{ "success" : true, "msg" : 'Verification is OK' }
Then, inside your $.json() success function, you can access anything from the server's response like so:
if (data.success) {
alert(data.msg);
}
I know you said you want to loop, but that's just an example. Note that PHP has a great little function called json_encode() that can turn an array into a json object that your JavaScript will pick up just fine.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
// if data is a variable like '$a="Verification is OK"':
eval(data);
if ($a == 'Verification is OK')
$("#colorBox").close() // or whatever the close method is for your plugin
else
$('#message').html($a);
}
});
return false;
});
The var "data" is the response being passed back from your PHP file. Therefore, you can do something like:
...success: function (data) {
if (data == 'Verification is OK') {
// Make a if loop according to what returns html(data)
}
}
You just have to make a simple comparison in your success function in the ajax request, like this:
success: function (data) {
$('#message').html(data);
if(data == 'Verification is OK')
{
// make the lightbox show
}
}

Resources