I can't figure out what's going on here. I'm trying to make a pretty simple ajax post to do an autocomplete in laravel.
I have an input box and a spot for the results:
<div class="form-group">
<input type="text" name="tag_name" id="tag_name" class="form-control input-lg" placeholder="Enter Country Name" />
<div id="tagList">
</div>
</div>
and my JS
$('#tag_name').keyup(function(){
var query = $(this).val();
if(query != '')
{
//var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('campaigns.search') }}",
method:"POST",
data:{query:query, _token: '{{ csrf_token() }}'},
success:function(data){
$('#tagList').fadeIn();
$('#tagList').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#tag_name').val($(this).text());
$('#tagList').fadeOut();
});
});
The route points to my controller function:
public function searchTags(Request $request)
{
if($request->get('query'))
{
$query = "%" . $request->get('query') . "%";
$data = CampaignTags::where('TAG_DATA', 'LIKE', $query)->get();
$output = '<ul>';
foreach ($data as $row) {
$output .= '<li>' .$row->TAG_DATA. '</li>';
}
}
return json_encode($data);
}
When I inspect as I type, I get 200 codes on the search but I'm not getting actual results to show from the database, the response seems to be null
I did this using typeahead. and answered it in another thread. before
heres the link. Auto Complete Laravel
Related
I am trying to call ajax query in my code but it is not working. I have common header and footer (php) for all other files. It is returning the required data but showing inside html code. I tried and searched everywhere but couldn't get through this.
I am really sorry for not posting code here because i tried for an hour to post code but i couldn't as this editor was giving an error about code not formatted.
Html Part of code
<div class="form-group">
<select class="selectpicker" data-live-search="true" data-style="form-control"
name="" id="sale_customer" required>
</select>
</div>
<div class="row cus-note">
<p class="note-field col-6" id="note_customer" name="search"> </p>
<textarea type="text" class="form-control note-field col-6" name="" value=""
placeholder="New Note..." required></textarea>
</div>
JQuery Part
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function loadCustomer(notes, cust) {
// console.log("cust");
$.ajax({
url: "<?php echo $folder;?>crud.php",
type: "POST",
data: {
note: notes,
customer: cust
},
success: function(data) {
if (data.note == "notes") {
// alert('haaalp');
$("#note_customer").html(data);
} else {
$("#sale_customer").append(data);
alert('haaalp');
}
}
});
}
loadCustomer("noteD","");
$("#sale_customer").on("change", function() {
var customer = $("#sale_customer").val();
console.log(customer);
if (customer != "") {
loadCustomer("notes", customer);
}
else {
$("#note_customer").html("");
}
});
});
</script>
Server Side Code
if($_POST['note'] == "noteD"){
$sql = "SELECT * FROM customer";
$query = mysqli_query($db, $sql) or die("Query Unsuccessful.");
$sale_customer = "<option selected value='wic'><sub>test</sub></option>";
while($row = mysqli_fetch_assoc($query)){
$sale_customer .= "<option value='{$row['name']}'>{$row['name']}</option>";
}
echo $sale_customer;
}
else if($_POST['note'] == "notes"){
$customer = $_POST['customer'];
$query = mysqli_query($db, "SELECT * FROM customer WHERE name = 'Ali'") or die("Query
Unsuccessful.");
$sale_customer = "";
while($row = mysqli_fetch_assoc($query)){
$sale_customer .= "{$row['note']}";
}
echo $sale_customer;
}
I can see successfully returned data in console. it is also gong inside condition but not displaying in selector. and in if condition if use only note instead of data.note it throws exception that note is not defined..
Ajax code for successful return
Data returned on console
data.note to only note
note object not found
Hurrah!!!
After searching here and there I found a solution to overcome this issue.
The main problem was the bootstrap selectpicker. The ajax was returning the data but select was not showing it. In
success: function(data) {
if (note == "notes") {
$("#note_customer").html(data);
} else {
$("#sale_customer").append(data);
}
}
I just added $("#sale_customer").append(data).selectpicker('refresh');
and it worked but again the other issue preserved that in if (note == "notes") { "note" is not defined.
for that purpose I took 2 variables outside ajax as var note = notes;, var customer = cust; and then posted in data object as
data: {
note,
customer
},
and the result occurred which was expected.
The issue was with bootstrap selectpicker and data objects.
I am trying to implement a message system in my project by using AJAX, but I have got some problems because I am new to AJAX.
The code below is able to send input data from the MsgMain.php file to MsgInsert.php perfectly. But when I try to get $_POST['msgSend'] from MsgMain.php on MsgInsert.php it fails.
AJAX Code is on MsgMain.php
$(document).ready(function(){
$("#chatBtn").click(function(){
$("#msgBtn").val("chat");
});
$("#pmBtn").click(function(){
$("#msgBtn").val("pm");
});
});
$(function() {
$("#msgBtn").click(function() {
var textcontent = $("#msgInput").val();
var dataString = 'content='+ textcontent;
if(textcontent=='')
{
alert("Enter some text..");
$("#msgInput").focus();
}
else
{
$.ajax({
type: "POST",
url: "msg/MsgInsert.php",
data: dataString,
cache: true,
success: function(response){
document.getElementById('content').value='';
$("#msgBtn").focus();
}
});
}
return false;
});
});
MsgMain.php file code just for the HTML form
<form action="MsgInsert.php" id="frmBox" name="msgSend" method="POST" onsubmit="return formSubmit();">
<div class="input-group ">
<input type="text" class="form-control" name="msgBox" id="msgInput" title="Enter your message" required>
<div class="input-group-btn">
<button class="btn btn-success w3-hover-white w3-hover-text-green" type="submit" id="msgBtn" title="Send your message" value="chat"><i class="glyphicon glyphicon-send"></i></button>
</div>
</div>
</form>
MsgInsert.php file code, which works well when I remove the if statement of $_POST['msgSend']
<?php
if(!isset($_SESSION['login_user'])){
header("location: ../index.php"); // Redirecting To Home Page
}
if (isset($_POST['content'])) {
if (isset($_POST['msgSend'])) {
$conn = mysqli_connect("localhost", "root", "", "msg");
if (!$conn) {
die('Could not connect: ' . mysqli_error($conn));
}
$content=$_POST['content'];
mysqli_query($conn, "INSERT INTO `msgpm`(`id`, `msgFrom`, `msgTo`, `msg`) VALUES ('','bob','ram','$content')");
}
}
?>
Sorry if this type of question has already been asked.
You are not sending the msgSent attribute, according to this line in your JS:
var dataString = 'content='+ textcontent;
I can see only the content which you will be able to use via $_POST['content'].
Try this:
var dataString = 'content='+ textcontent + '&msgSent' + '<?php echo $_POST['msgSent']; ?>';
You have to pass the msgSend Parameter according to your implementation of MsgInsert.php like so:
$("#msgBtn").click(function () {
var textcontent = $("#msgInput").val();
if (textcontent == '') {
alert("Enter some text..");
$("#msgInput").focus();
}
else {
var dataString = 'content=' + textcontent + '&msgSend=1';
$.ajax({...});
}
});
Always think of escaping your content via i.e. prepared statements when saving user generated content into your database to avoid sql injection!
I have problem with ajax results when trying to search some id for example: 0205P, 04066H etc, it give me result correctly but when I click it, in input is some other number like 616, 7,13... So everything working perfect except when my search starting with 0 (zero).
My ID in database(MYSQL) is Varchar(8).
Here is my code:
dob.php
<input type="text" name="konto1" id="konto" class="form-control konto" value="<?php if(isset($_POST['konto1'])) echo $_POST['konto1']; ?><?php if(isset($_GET['konto1'])) echo $_GET['konto1'];?>" />
<div class="boja"><div style="margin-top: 0px" id="selectKonto" class="list-group"></div></div>
<script>
// ajax call
$('#konto').keyup(function() {
var konto = $(this).val();
$.ajax({
type: 'POST',
url: 'konto.php',
data: {
search: konto
},
beforeSend: function() {
$('#konto').css("background", "#FFF url(LoaderIcon.gif) no-repeat 165px");
},
success: function(data) {
if (!data.error) {
// var reply = data.replace(/\s+/, "");
$('#selectKonto').show();
$('#selectKonto').html(data);
$("#konto").css("background", "#FFF");
}
}
});
});
function selectKonto(val) {
$("#konto1").text(val);
$("#selectKonto").hide();
}
</script>
konto.php
if(!empty($konto)) {
$q = "SELECT * FROM konto WHERE ... LIMIT 10";
$result = $db->query($q);
if(!$result){
die('QUERY FAILED' . $db->error);
}
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<div><font size="2em"><a href="#" class="list-group-item konto" style="width: 555px;border: 1px solid grey;"
onclick="selectKonto(\''.trim($row['kp_sif']).'\')">...
<script>
$('.konto').click(function() {
var text = $(this).html();
$('.ime-konto').html(text);
$("#selectKonto").hide();
});
</script>
P.S. Field type in database must stay varchar, I can not change it to INT.
So, it works fine with quotes in php.
onclick="selectKonto(\''.trim($row['kp_sif']).'\')">
Obviously I had other problem in syntax.
I have made a simple search bar in which on every .keyup() event,an asynchronous request goes to a php file which then fills the data in the bootstrap popover.
The problem is that in the popover,the data is filled only once,i.e.,when I type the first character,after that the same data is shown even after multiple .keyup() events.
Here is the code:
HTML:
<input type="text" data-placement="bottom" id="search" name="search1" class="search-box" placeholder="Search..." title="Results"/>
AJAX:
$("#search").keyup(function(){
console.log('erer');
//var searchString = $("#search").val();
var data = $("#search").val();
console.log(data);
var e=$(this);
//if(searchString) {
$.ajax({
type: "POST",
url: "do_search.php",
data: {search:data},
success: function(data, status, jqXHR){
console.log('html->'+data+'status->'+status+'jqXHR->'+jqXHR);
e.popover({
html: true,
content: data,
}).popover('show');
},
error: function() {
alert('Error occured');
}
});
//}
});``
PHP:
$word = $_POST['search'];
//echo $word;
//$word=htmlentities($word)
$sql = "SELECT FName FROM user WHERE FName LIKE '%$word%' ";
//echo $sql;
// get results
//$sql = 'SELECT * FROM Profiles';
$end_result = '';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
#$end_result.='<li>'.$row["FName"].'</li>';
#$_SESSION['fnamer'] = $row['Fname'];
#$end_result.='<li>'.'<a href =view_search.php>'.$row["Fname"].'</a>'.'</li>';
echo '<a href =view_search.php>'.$row["FName"].'</a>';
}
#echo $end_result;
}
Even though in the success parameter of the $.ajax,the data is being printed fine,i.e.,it changes as I enter different alphabets,but the popover content does not change.
Please provide some suggestions to resolve this problem.
The popover is already shown. This is not the correct way of changing the popover content dynamically.
Your code: https://jsfiddle.net/gsffhLbn/
Instead, address the content of the popover directly:
var popover = e.attr('data-content',data);
popover.setContent();
Working solution
Fiddle: https://jsfiddle.net/gsffhLbn/1/
Hey So I have an issue with my code where I am trying to filter the data coming from the database and display it in a table. I am using AJAX to send the request to the PHP page. I have not had any luck in searching for a solution. (It will be similar to your common real estate website, or retail, etc. where the user can input a location in the search box, search for it, and then filter the displayed data using the 2 dropdown menus).
My index.php page has 3 inputs (a textbox and 2 dropdowns)
<form action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" class="searchForm" id="search" placeholder="Stuff" autocomplete="off">
<div id="here"></div>
<select class="orderType" name="type" id="orderByType" data-toggle="dropdown" onchange="displaySelection(this.value)">
<option value="" selected>--------</option>
<option value="dropdown1" selected>Dropdown1</option>
<option value="dropdown1" selected>Dropdown1</option>
</select>
<select class="order" name="order" id="orderBy" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="lowest">Lowest</option>
<option value="highest">Highest</option>
</select>
</form>
<div id="searchTable">
Then my ajax calls on the index.php page (The AJAX will be another question later, as I'm sure there is a better way than what I have, to send the data)
function fill(Value)
{
$('#search').val(Value);
$('#here').hide();
}
$(document).ready(function(){
$("#search").keyup(function(){
var x = $('#search').val();
if(x==""){
$("#here").html("");
$('#searchTable').html("");
}
else{
$.ajax({
type:'POST',
url:'test.php',
data:'q='+x,
success:function(html){
$("#here").html(html).show();
}
});
}
});
$('.searchForm').change(function(){
var type = $('#search').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { search : type, city : city },
success: function(response){
$("#searchTable").html(response);
$('#search').live("keypress",function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13){
e.preventDefault();
e.stopPropagation();
$('#searchTable').show();
}
});
}
});
});
$('.orderClass').change(function(){
var order = $('#orderBy').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { orderBy : order, city : city },
success: function(response){
$("#searchTable").html(response);
}
});
});
$('.orderType').change(function(){
var type = $('#orderByType').val();
var city = $('#city').text();
$.ajax({
type: 'POST',
url: 'test.php',
data: { orderByType : type, city : city},
success: function(response){
$("#searchTable").html(response);
}
});
});
});
And then on test.php
(I can filter the data with the 2 dropdown menus and that will work fine, but i'm not sure how to filter the data that is displayed from the search input box.)
$stmt = "SELECT * FROM places";
if(isset($_POST['search'])){
$search = htmlspecialchars($_POST['search']);
$stmt .= " WHERE name = :search";
}
if(isset($_POST['orderByType'])){
$selection = $_POST['orderByType'];
$stmt .= " AND type = :selection";
}
if(isset($_POST['orderBy'])){
$order = $_POST['orderBy'];
$selection = $_SESSION['id'];
$stmt .= " ORDER BY".$order;
}
$stmt = $conn->prepare($stmt);
$search = "%".$search."%";
$stmt->bindValue(':search', $search, PDO::PARAM_STR);
$stmt->bindParam(":selection", $selection);
if($stmt->rowCount() > 0){
$result = $stmt->fetchAll();
foreach($result as $row){
echo $row['data'];
}
}
//Search input live search
if(!empty($_POST['q'])){
$name = $_POST['q'];
$name = htmlspecialchars($name);
$liveSearch = $conn->prepare("SELECT name, city FROM places WHERE name LIKE :name OR city LIKE :name");
$name = "%".$name."%";
$liveSearch->bindValue(':name', $name, PDO::PARAM_STR);
$result = $liveSearch->fetchAll();
if($liveSearch->rowCount() > 0){
foreach($result as $row){
echo $row['name'];
}
}
else{
echo "No results found";
}
}
(If there is a great system in place that can search using user input and then filter it using dropdown menus, then please let me know)
Thanks in advance.
If I was going to do this, I would probably make an ajax object for reuse reasons and a php object to handle queries:
/defines.php
You may or may not have defines for your db credentials. I use these in the class below.
define("DB_USER",'root');
define("DB_PASS",'password');
define("DB_HOST",'localhost');
define("DB_NAME",'dbname');
/classes/Query.php
This is a stripped-down query engine which makes basic queries. I use it to save on rewriting a bunch of prepares and executes, but you can do whatever you like there.
class Query
{
private static $singleton,
$con;
private $rquery,
$bind;
public function __construct()
{
if(self::$singleton instanceof Query)
return self::$singleton;
self::$singleton = $this;
}
public function connect()
{
if(self::$con instanceof PDO)
return self::$con;
self::$con = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME,DB_USER,DB_PASS);
return self::$con;
}
public function query($sql,$bind = false)
{
$this->bind = false;
try {
if(empty($bind)) {
$this->rquery = $this->connect()->query($sql);
}
else {
foreach($bind as $key => $value) {
$bkey = ":{$key}";
$this->bind[$bkey] = $value;
}
$this->rquery = $this->connect()->prepare($sql);
$this->rquery->execute($this->bind);
}
}
catch (PDOException $e){
die('An application error occurred.');
}
return $this;
}
public function getResults()
{
while($results = $this->rquery->fetch(PDO::FETCH_ASSOC)) {
$row[] = $results;
}
return (!empty($row))? $row : 0;
}
}
/functions/searchPlaces.php
function searchPlaces($search,$type = false,$orderby = false)
{
$sVal = "%".$search."%";
array();
$sql[] = 'SELECT * FROM places WHERE `name` LIKE :0 or `city` LIKE :1';
$bind = array_fill(0,2,$sVal);
if(!empty($type)) {
$bind[] = $type;
$sql[] = 'AND `type` = :2';
}
if(!empty($orderby)) {
$order = ($orderby == 'lowest')? 'ASC' : 'DESC';
$sql[] = "order by `ID` {$order}";
}
// Here is where I use the query to send back results from DB
// you can just use a regular prepare/bind/execute if you like
$qEngine = new Query();
return $qEngine->query(implode(' ',$sql),$bind)->getResults();
}
/test.php
<?php
// Put our db credentials
require_once(__DIR__.'/defines.php');
if(!empty($_POST)) {
// Needs the search function and the query class
// (disregard class if you don't use it)
require_once(__DIR__.'/functions/searchPlaces.php');
require_once(__DIR__.'/classes/Query.php');
// I am just sending an array back, but you can format it as you please
print_r(searchPlaces($_POST['search'],$_POST['type'],$_POST['order']));
exit;
}
/index.php
<script>
// I like to make an ajax engine, it saves on rewriting all the same stuff
// on later ajax calls
var AjaxEngine = function($)
{
this.send = function(data,func)
{
$.ajax({
url: '/test.php',
data: data,
type: 'post',
success: function(response){
func(response);
}
});
return this;
};
}
// You only need one document ready
$(document).ready(function(){
// Make an ajax engine
var Ajax = new AjaxEngine($);
// If form changes or key up in text field
$('.searchForm,.ajaxer>select').on('keyup change',function(e) {
e.preventDefault();
// Serialize the form
var formData = $('.ajaxer').serialize();
// Send the ajax and return results
Ajax.send(formData,function(response) {
$('#searchTable').html(response);
});
});
});
</script>
<!-- Note changes to the form for classes and ids -->
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" class="ajaxer">
<input name="search" type="text" class="searchForm" id="search" placeholder="Stuff" autocomplete="off" />
<div id="here"></div>
<select class="orderType" name="type" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="dropdown1" selected>Dropdown1</option>
<option value="dropdown1" selected>Dropdown1</option>
</select>
<select class="order" name="order" data-toggle="dropdown">
<option value="" selected>--------</option>
<option value="lowest">Lowest</option>
<option value="highest">Highest</option>
</select>
</form>
<div id="searchTable"></div>