I want to add a search bar in my website, so I added jQUery UI autocomplete search and it works like a charm and the results are showing from the database. But, I need if the user clicks on a result from the list I want to redirect the user to that product page. This is the code in navigation.php:
<div id="search-div">
<form action="#" id="form-search" method="POST" class="form-inline">
<input id="language" type="text" placeholder="Search for a product" style="padding-left:15px;">
</form>
</div>
<script>
$("#language").autocomplete({
appendTo: $("#language").parent(),
source: function(data, cb){
$.ajax({
url: '/tutorial/admin/parsers/ajax.php',
method: 'GET',
dataType: 'json',
data: {
title: data.term
},
success: function(res){
cb(res);
}
});
}
});
</script>
And this is ajax.php code:
<?php
require_once $_SERVER['DOCUMENT_ROOT'].'/tutorial/core/init.php';
$data = array();
if (!empty($_GET['title'])) {
$title = strtolower(trim($_GET['title']));
$sql = "SELECT title FROM products WHERE title LIKE '" .$title. "%'";
$result = $db->query($sql);
while ($row = mysqli_fetch_assoc($result)) {
array_push($data, $row['title']);
}
}
echo json_encode($data);
exit;
?>
The page that I want the user to be redirected to is products.php?details=20 where 20 is the id of the product it is a GET method page. How to make the ability to redirect the product page based on the id if the user clicks on this product from the search list?
Try this:
$(document).ready(function() {
$("#language").autocomplete({
source: function(data, cb){
$.ajax({
url: '/tutorial/admin/parsers/ajax.php',
method: 'GET',
dataType: 'json',
data: {
title: data.term
},
success: function(res){
cb(res);
},
select: function( event, ui ) {
window.location.href = ui.item.link;
}
});
});
select: function(event, ui) {
doSearch(ui.item.title);
}
function doSearch(term) {
window.location.href = 'Search.php?q=' + term;
}
search.php is your controller or contain business logic file.you can pass the query parameter as your need.
I am not sure how to do it in jquery ui autocomplete this OLD link might be helpful.
But it's easy if you can use Twitter Typeahead instead of JQ UI.
Related
I have a few caption boxes that I want to be able to edit inline and to save these to my database to update a certain record in my table.
For some reason, nothing happens when I click the save button.. not even in the console.
It's just using jQuery at the moment, will I have to use AJAX for this?
If so any tips would be great to point me in right direction as I'm not familiar that much with AJAX.
Here is my code:
index.php
<div class="caption" id="caption1" contenteditable="true" style="min-height: 450px;">
<?php
$query3 = "SELECT * From (select * from ckeditor ORDER BY id DESC LIMIT 2) AS name ORDER BY id LIMIT 1";
$show = mysql_query($query3, $con);
while ($row = mysql_fetch_array($show))
{
echo $row['file'];
}
?>
</div>
<button type="button" id="save"><span>Save</span></button>
<script>
$(document).ready(function (e) {
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
var options = {
url: "save.php",
type: "post",
data: { "editor" : encodeUriComponent(data) },
success: function (e) {
echo "Succesfully updated!";
}
};
}
});
</script>
</div>
save.php
<?php
$connection = mysql_connect("localhost", "", "");
$db = mysql_select_db("castle", $connection);
//Fetching Values from URL
$data = nl2br($_POST['caption1']);
//Insert query
$query ="INSERT INTO `ckeditor`(`file`) VALUES ('$data')";
echo "Form Submitted Succesfully";
mysql_close($connection);
?>
You need to send the data to the server like this;
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
//Success
},
type: 'POST'
});
Currently you are just creating an object called 'options'
Your code should look like this;
$("#save").click(function (e) {
var data = CKEDITOR.instances.caption1.getData();
$.ajax({
url: "save.php",
data: {
"editor" : encodeUriComponent(data)
},
error: function() {
//Error
},
success: function(data) {
alert('Success');
},
type: 'POST'
});
}
Just a side note, 'echo' doesn't work in js. You need to use 'alert()' or 'console.log()'
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;
}
});
});
});
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?
I am building a news page for my website but I'm stuck displaying the right comments with ajax...
commentsLoad.php
<?php
include('config.php');
$newsid = $_GET['newsid'];
$comments=array();
$commentsQuery = "SELECT * FROM comments
where fk_news like ".$newsid;
$result = $conn->query($commentsQuery);
if($result->num_rows>0){
while($row = $result->fetch_assoc()){
$comments[]=array('id' => $row['id'], 'name' => $row['cnick'], 'text' => $row['ctext'], 'date' => $row['cdate']);
}
}
//header('Content-type: application/json');
echo json_encode($comments);
exit;
?>
I dont know how to pass the right 'NEWSID'.
Website picture: http://prntscr.com/8nwy8k
How I want to pass that ID to the SQL Query
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
data:{newsid:'1'},
success: function(comments){
//console.log(komentarji);
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
So right now if I change the line data:{newsid:'1 or 2 or 3...'} I get the comments I want, but I dont know how to get that ID into a variable.
You can use onClick event for this.
Explanation:
Comment link will look as follows
Comments
Then you can have a fucntion in your JQuery code to pass it to PHP file.
function getComments(article_id)
{
var artid = article_id;
$.ajax({
type: 'POST',
url: commentsUrl,
dataType: "json",
data:{newsid: artid},
success: function(comments){
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
}
Try set onclick function in the comment link.
<a href="javascript:void(0)" onclick='myfunction <?php echo newsid ?>'Comment</a>
Get the newsid form the link.
<script>
function myfunction(newsid){
$.ajax({
type: 'GET',
url: commentsUrl,
dataType: "json",
data:{newsid:newsid},
success: function(comments){
//console.log(komentarji);
$.each(comments, function(i, komentar){
addComment(komentar);
})
},
error: function(e){
console.log(e);
}
});
}
</script>
Get the newid from commenntsUrl page.
I'm running a database with itemID's and a shelfnumber for every itemID..
As the user enters an itemID I want it to run through my database to get the shelfnumber using Ajax/PHP. Then post the shelfnumber back so the user can see where to find the item. (The items are in a room and are marked with unique ID's and shared shelfnumbers.) I need to use the onChange method (or anything similar) beacuse I want it to work like a tip/search engine. In other words automatic..
I'm totally new to ajax and I can't seem to get this to work at all.. No result is given and i'm at a roadblock right now.. Any form of help will be very appreciated
HTML
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js" type="text/javascript"></script>
<script type="text/javascript">
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
},
success:function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
}
});
});
</script>
</head>
<body>
<a>Enter Item ID 1:</a>
<input id="target" type="text" name="itemID" required />
<div id="hyllplacering">ENTER Shelfnumber here: </div>
</body>
</html>
PHP
<?php
$con = mysql_connect("localhost", "root", "") OR die(' Could not connect');
$db = mysql_select_db('book1', $con);
$itemID = filter_input(INPUT_POST, 'itemID', FILTER_VALIDATE_INT);
$query = "SELECT Hyllplacering from booking WHERE itemID = $itemID";
$result = mysql_query($query);
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo json_encode(array('itemID' => $itemID, 'Hyllplacering' => $row['Hyllplacering']));
?>
JavaScript is executed as soon as it is encountered. You bind the Event to an Element before it is available.
You need to wrap the script in a document.ready body.
As the other answers mentioned you want to use the success callback instead of done.
<script>
$(document).ready(function(){
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
};
})
.success(function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
});
});
});
</script>
You may add a sentence in AJAX function
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
};
success:function(data){
console.info(data);
}
})
to monitor what your PHP responsed, it's more easy to check what's wrong.
I think you incorrect to use the done method of the Ajax object. I am pretty sure you wont have your response available in that scope. Try to do it like..
$('#target').change(function() {
$.ajax({
url: 'shelfid.php',
type: 'POST',
dataType: 'JSON',
data:{
itemID: $(this).val()
},
success:function(response) {
alert("Item: "+response.itemID+", Shelf: "+response.Hyllplacering);
},
error:function(response){
alert('error '+response);
};
})
});