Javascript Code
$( "#cusname" ).autocomplete({
source: function(request, response) {
$.ajax({
url: base_url+'admin/auto_cusname',
data: { term: $("#cusname").val()},
dataType: "json",
type: "GET",
success: function(data){
var resp = $.map(data,function(obj){
return obj.tag;
});
response(resp);
}
});
},
minLength: 1
});
Controller
public function auto_cusname(){
$term = $this->input->get('term');
if (isset($term)){
$result = $this->mod_admin->autocusname($term);
}else{
$data['error'] = $term;
$this->load->view('error', $data);
}
print json_encode($result);
}
Model
public function autocusname($search_term) {
$this->db->select('Firstname');
$this->db->like('Firstname', $search_term);
$response = $this->db->get($this->tbl_costumer,$this->uri->segment(2))->result_array();
// var_dump($response);die;
return $response;
}
View
<div class="ui-widget">
<input id="cusname" name="cusname" placeholder="Customer Name"/>
</div>
My problems is when i try to query it on the browser i got this
localhost/PPDOIMS/admin/auto_cusname?term=s
it outputs the data
[{"Firstname":"Crisa"},{"Firstname":"Thomas "}]
but when try to view it on my page and type something i got no response.
is there something wrong on my code?
Related
i want to highlight the keywords according to its autocomplete search, like if i type a then the results it gives:
java
javascript
so in this java
javascript
and then if i type av then java
javascript should get highlight or bold according to the search.
Below is my code:
javascipt
$(this).ready( function() {
$("#id").autocomplete({
minLength: 1,
source:
function(req, add){
//alert("xdhf");
$.ajax({
url: "<?php echo base_url(); ?>/trainer_dashboard/autocomplete_batchsearch",
data: req,
dataType: 'json',
type: "post",
cache: false,
success: function (data){
//alert(data);
if(data.response =="true"){
add(data.message);
console.log(data);
}
},
error: function (xhr, ajaxOptions, thrownError)
{
alert(thrownError);
}
});
},
});
});
controller
public function autocomplete_batchsearch()
{
//$user_id=get_cookie('trainer_login_user_id');
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->trainer_dashboard_model ->batchsearch($keyword); //Search DB
//echo"";print_r($query);
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->id,
''
); //Add a row to array
}
}
if('IS_AJAX')
{
echo json_encode($data); //echo json string if ajax request
}
else
{
$this->load->view('trainer_dashboard_view',$data); //Load html view of search results
}
}
I want to make the result list for my Bootstrap typeahead list clickable and if the user clicks on any of the items in the dropdown list it will be redirected to the url [on my site, not external links] of the selected item. I made my changes regarding this Stackoverflow topic: jquery autocomplete json and clickable link through
The problem is, that I'm not into JS and Jquery and I can't tell why I get this error (Firefox Firebug Console output). I get this error everytime I enter any letter in my input textbox:
TypeError: it.toLowerCase is not a function bootstrap3-typeahead.min.js (1. line, 3920. column)
I see that the results of my PHP seems okay, so it must be something in the jQuery statement...
This is my result from the PHP:
[{"name":"TEXT-ONE","url":"\/textone-postfix"},{"name":"TEXT-TWO","url":"\/texttwo-postfix"},{"name":"TEXT-THREE"
,"url":"\/textthree-postfix"}]
This is my JQuery code:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
This is my PHP code:
<?php
require_once('../config/config.php');
require_once('../functions/functions.php');
require_once('../config/db_connect.php');
$query = 'SELECT name_desc FROM tbl_name ';
if(isset($_POST['query'])){
$query .= ' WHERE LOWER(name_desc) LIKE LOWER("%'.$_POST['query'].'%")';
}
$return = array();
if($result = mysqli_query($conn, $query)){
// fetch object array
while($row = mysqli_fetch_row($result)) {
$array = array("name" => $row[0], "url" => "/" . normalize_name($row[0])."-some-url-postfix");
$return[] = $array;
}
// free result set
$result->close();
}
// close connection
$conn->close();
$json = json_encode($return);
print_r($json);
?>
Can someone please help me what could be the problem here?
Thank you very much!
The problem was that the displayText wasn't defined:
$(document).ready(function() {
$(function() {
$('#namesearch').typeahead({
source: function(request, response) {
$.ajax({
url: '/functions/search-autocomplete.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + request,
success: function(data) {
response($.map(data, function(item) {
return {
url: item.url,
value: item.name
}
}))
}
})
},
displayText: function(item) {
return item.value
},
select: function( event, ui ) {
window.location.href = ui.item.url;
}
});
});
});
I have a POST method Jquery. Ajax and I can't send my data to the controller, I have tried every solution on the net, but no result.......
My JavaScript
$(document).ready(function(){
$('#submitForm').click(function(){
var data1 = {request : $('#request').val()};
$.ajax({
type: "POST",
url: "/Manufacturer",
data: data1,
success: function(dataBack) {
console.log(dataBack);
},
contentType: "application/json",
dataType: 'json'
});
});
});
MY controller
public function indexAction(Request $request)
{
//$name = $request->request->get('data');
//return new Response($name);//or do whatever you want with the sent value
if($request->isXmlHttpRequest()){
$name = $request->request->get('data1');
If($name == 1)
{
return new Response('Yeap');
}
else
{
return new Response(';(');
}
}
return $this->render('MyIndex/Manufacturer_LIST.html.twig' );
}
HEre is my Console ::
And my response is as it's obvious ";("
First you need to install FOSJsRoutingBundle to be able to "expose" your Symfony routes into the javascript code. Follow the steps in the official documentation.
Then, in your twig template if you have a form like:
<form>
<input type="text" id="name"> <br>
<button type="submit" id="submitForm">Submit</button>
</form>
your js code could look liks this:
$('#submitForm').click(function(e){
e.preventDefault();
var name = $('#name').val();
$.ajax({
method: 'POST',
url: Routing.generate('Manufacturer_LIST');
// OR: url: "/Manufacturer", if you don't want to install FOSJsRoutingBundle
data: { name:name }
}).done(function(msg){
console.log(msg);
}).fail(function(XMLHttpRequest, textStatus, errorThrown){
console.log(textStatus + ' ' + errorThrown);
});
});
And in your controller:
/**
* #Route("/Manufacturer", name="Manufacturer_LIST", options={"expose"=true})
*/
public function indexAction(Request $request){
if($request->isXmlHttpRequest()){
$name = $request->request->get('name');
return new Response($name);//or do whatever you want with the sent value
}
return $this->redirectToRoute('homepage');
}
When I see on the debug developer tool ajax request responded with data but the data is not rendered in the text box. The data contains some special characters as you can see in the picture.
What is exactly wrong with the response function ? What (like utf-8 encoding maybe) should I add to the ajax call to display the special character ?
html:
<select name="selCat">
<option>....</option>
</select>
<input class="col-3" type="text" id="txtPOI" name="txtPOI" />
jquery:
$("#txtPOI").autocomplete({
source: function(request, response) {
$.ajax({
url: '<?php echo site_url("crowd/get_POIs") ?>',
data: {cat: selectedCode, q: request.term},
dataType: "json",
type: "post",
success: function(data) {
response(data);
},
fail : function ( jqXHR, textStatus, errorThrown ) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
},minLength: 3
});
}
});
Controller :
function get_POIs(){
$cat = $this->input->post('cat');
$q = $this->input->post('q');
//echo $cat;
if (isset($cat) && isset($q)){
$cat = strtolower($cat);
$q = strtolower($q);
$data=$this->crowd->get_POIs($cat,$q);
//echo "aa";
$a_json = array();
if(count($data) > 0){
foreach ($data as $row){
$a_json_row["title"] = $row->title;
$a_json_row["contentid"] = $row->contentid;
$a_json_row["latitude"] = $row->latitude;
$a_json_row["longitude"] = $row->longitude;
array_push($a_json, $a_json_row);
}
echo json_encode($a_json);
}
}
}
Model :
function get_POIs($cat, $q){
$this->db->DISTINCT();
$this->db->select('title, a.contentid, latitude, longitude, address');
$this->db->from('attraction a');
$this->db->join('geographicdata g', 'a.contentid = g.contentid', 'left');
$this->db->where('cat3 = "'.$cat.'"');
$this->db->where('title like "%'.$q.'%"');
$this->db->order_by('title','ASC');
$query = $this->db->get()->result();
//die(var_dump($query));
//echo $this->db->get_compiled_select();
return $query;
}
I managed to solve this problem by modifying the code inside the success event. Here how I did it.
change from
success: function(data) {
response(data);
}
to
success: function(data) {
response( $.map( data, function( item )
{
return{
label: item.title,
value: item.title,
contentid: item.contentid,
latitude: item.latitude,
longitude: item.longitude
}
}));
}
I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}