Jquery autocomplete wont give any result - php

I am new to codeignitor and trying to get jquery autocomplete from database . There are already many questions asked about this topic but none of those helped me.
Here is my script function from view file
View
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js">
</script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js">
</script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-
ui.css" />
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js">
</script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function() {
$( "#vname" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "vendor/search",
data: { term: $("#vname").val()},
dataType: "json",
type: "GET",
success: function(data){
var resp = $.map(data,function(obj){
return obj.tag;
});
response(resp);
}
});
},
minLength: 2
});
});
</script>
</head>
.
.
.
.
<input type="text" class="form-control" name="vendor_name" id="vname" />
here is controller(vendor) function (search) from which I am trying to get array of suggestion from database
Controller
public function search()
{
$json = [];
$this->load->database();
if(!empty($this->input->get("term"))){
$this->db->like('name', $this->input->get("term"));
$query = $this->db->select('id,name as text')
->limit(10)
->get("vendors");
$json = $query->result();
}
echo json_encode($json);
}
the problem is that when I type in input field, nothing happen (no autocomplete appears) but my vendor/search function is working fine while accessing it directly and pass something as parameter. I think $_GET[term] is always empty or something.
I dont have any idea what to do now any suggestion would be appreciable.

Change this line:
url: "vendor/search",
to:
url: "<?php echo base_url('vendor/search'); ?>",

Change in controller
public function search(){
$json = [];
$this->load->database();
if(!empty($this->input->get("term"))){
$this->db->like('name', $this->input->get("term"));
$query = $this->db->select('id,name as text')
->limit(10)
->get("vendors");
$json = $query->result();
}
//set page header
$this->output
->set_content_type('application/json')
->set_output(json_encode($json));
}
replace script tag
<script type="text/javascript">
$(function() {
$( "#vname" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "<?=base_url(); ?>vendor/search?term="+request.term,
dataType: "json",
type: "GET",
success: function(data){
response($.map(data, function (value, key) {
return {
label: value.text,
value: value.id
}
}));
}
});
},
minLength: 2,
select: function(event, ui) {
//select event of autocomplete
console.log("id : ",ui.item.value);
console.log("text : ",ui.item.label);
$('#vname').val(ui.item.label);
return false;
},
});
});
</script>

Related

json_decode returns null - laravel

i am sending json object from front-end using ajax call as the following:
<button id="btn">click me</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$('#btn').click(function () {
$.ajax({
url:"/execute",
type:"POST",
contentType: 'json',
data:{
"test":"hello"
},
success:function (data) {
console.log(data.status);
}
});
});
</script>
and i want to decode this json object in laravel, here is my controller code:
public function executeFunction(Request $request){
if($request->header()['content-type'][0] === 'json')
{
Log::info(json_decode($request->getContent(),true));
}
return response()->json(["status"=>"success"]);
}
json_decode returns null here, what might be the problem? Thanks.
I found a solution to this problem, the trick is to use JSON.stringify(data) in front end and json_decode will works fine.
Front end code:
button id="btn">click me</button>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$('#btn').click(function () {
$x = {
"test":"hello"
};
$.ajax({
url:"/execute",
type:"POST",
contentType: 'application/json',
data:JSON.stringify($x),
success:function (data) {
console.log(data);
}
});
});
</script>
Controller code:
public function executeFunction(Request $request){
if($request->header()['content-type'][0] === 'application/json')
{
Log::info(json_decode($request->getContent())->test);
}
}
If you dump the content, this will be the result:
object(stdClass)#423 (1) {
["test"]=>
string(5) "hello"
}

not returning anything in ajax

this is simple test for ajax and i want to send variable t in my index.php and get data(t) in my process.php and alert digit 15 when i click on button but my problem is not alerting anything
this is my index.php
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{
't':t
},
success:(function (response) {
alert(response);
}
})
})
})
</script>
<button id="btn">Click!</button>
this is my process.php
<?php
$res = $_POST['t'] + 5;
return $res
?>
Change codes like below:-
1.jQuery:-
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{'t':t},
success:function (response) { //remove (
alert(response);
}
});
});
});
2.Php:-
<?php
$res = $_POST['t'] + 5;
echo $res; //use echo rather than return
?>
Reason:-
return is used for returning a value from a function to another piece of PHP code.jQuery is not part of the execution of the PHP code on the server, so it has no idea what is really going on server side. jQuery is waiting for the rendered server response, which is what echo provides.
Note:- After doing These changes, Please check the browser console while running the ajax and see any error happen there? If yes share with us
i) Change your code with following code
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'process.php',
data:{
't':t
},
success:(function (response) {
alert(response);
}) //Close brace missing
})
})
});
2) Change return to echo
$(document).ready(function(){
$("#btn").click(function (){
var t = 10;
$.ajax({
type:'post',
url:'process.php',
data:{
t:t
},
success:(function (response) {
alert(response);
// you didnt close )
}) // close of success
})// close of ajax
})// close of click
}); // close of document
Process.php
<?php
$res = $_POST['t'] + 5;
echo $res;
?>
You should add jQuery like this
<script src="jquery-3.2.1.min.js"></script>
If you actually have downloaded and placed the file in the same directory.
You can include in from a CDN if you don't want to download it.
use this instead:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
And fix your JS code: (remove the extra '}' ...)
$(document).ready(function () {
var t = 10;
$("#btn").click(function () {
$.ajax({
type:'post',
url:'test.php',
data:{
't':t
},
success:(function (response) {
alert(response);
})
})
});
});

How to get the return value of a php function when calling from jQuery?

I have a php function return a string value which will put into html file.
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
So in jQuery, I have a following function
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).text();
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("HIHIHIHI");
$("#directioninfo").append(data);
}
});
})
Now console.log prints the "HIHIHIHIHI", but jQuery does not append the data to html. Anyone know how to get the return value of php function when calling from jQuery?
Instead of return use:
echo json_encode($dirinfo);
die;
It's also good idea to add dataType field to your $.ajax() function params set to json, to make sure, that data in your success function will be properly parsed.
You just need to send the response back using echo
Use var routeNumber = $(this).val(); to get the button value
PHP:
<?php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> routeNumber". $routeNumber." </p>";
return $dirinfo;
}
if (isset($_POST['getDirectionInfo'])) {
echo getDirectionInfo($_POST['getDirectionInfo']);
}else{
echo "not set";
}
AJAX & HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = $(this).val();
console.log("routeNumber = " + routeNumber);
$.ajax({
url: "systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
success: function(data) {
console.log("data = " + data);
$("#directioninfo").append(data);
}
});
})
});
</script>
</head>
<body>
<div id="directioninfo"></div>
<input type="button" value="12346" class="onebtn" />
</body>
</html>
Thank you for everyone. I have just found that I made a very stupid mistake in jQuery. I should use var routeNumber = parseInt($(this).text()); instead of var routeNumber = $(this).text(); So the following code work to get the return value of php function when calling from jQuery.
in php
function getDirectionInfo($routeNumber) {
//some code here
$dirinfo = "<p> some text </p>";
echo json_encode($dirinfo);
}
if (isset($_POST['getDirectionInfo'])) {
getDirectionInfo($_POST['getDirectionInfo']);
}
in jQuery
$(".onebtn").click(function(){
$("#directioninfo").empty();
var routeNumber = parseInt($(this).text());
$.ajax({
url: "./systemView_Function.php",
type: "POST",
data: {"getDirectionInfo": routeNumber},
dataType: "JSON",
success: function(data) {
$("#directioninfo").append(data);
}
});
})

showing loading image php

I am trying to show loading image until php excutes, the query works on the second page but the results aren't showing on the first page, I know I am missing something here, can someone help me out? I am new to jquery or ajax thing.
home.php
<html>
<head>
<!--Javascript-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$('#loading_spinner').show();
var post_data = "items=" + items;
$.ajax({
url: 'list.php',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
},
error: function() {
alert("Something went wrong!");
}
});
$('#loading_spinner').hide();
</script>
<style>
#loading_spinner { display:none; }
</style>
</head>
<body>
<img id="loading_spinner" src="image/ajax-loader.gif">
<div class="my_update_panel">
<!--I am not sure what to put here, so the results can show here-->
</div>
list.php I tested the query and it prints the rows.
<?php
include_once("models/config.php");
// if this page was not called by AJAX, die
if (!$_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') die('Invalid request');
// get variable sent from client-side page
$my_variable = isset($_POST['items']) ? strip_tags($_POST['items']) :null;
//run some queries, printing some kind of result
$mydb = new mysqli("localhost", "root", "", "db");
$username = $_SESSION["userCakeUser"];
$stmt = $mydb->prepare("SELECT * FROM products where username = ?");
$stmt->bind_param('s', $username->username);
$stmt->execute();
// echo results
$max = $stmt->get_result();
while ($row = $max->fetch_assoc()) {
echo $row['title'];
echo $row['price'];
echo $row['condition'];
}
?>
The HTML. Put the img inside of the .my_update_panel div
<div class="my_update_panel">
<img id="loading_spinner" src="image/ajax-loader.gif">
</div>
The JS
var url = 'list.php';
var post_data = "items=" + items;
$('.my_update_panel').load(url, post_data, function() {
$(this +' #loading_spinner').fadeOut('slow');
});
You can find a good selection of loading images that are readily available for download here.
There is a issue with
var post_data = "items=" + items;
Make it
$(document).ready(function(){
$('#loading_spinner').show();
$.ajax({
url: 'list.php',
type: 'POST',
data: {"items":items},
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
$('#loading_spinner').hide();
},
error: function() {
alert("Something went wrong!");
}
});
});
let me know if works for you.
Try To add complete event in the ajax , I hope it will work. Refer
http://api.jquery.com/jQuery.ajax/
<html>
<head>
<!--Javascript-->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$('#loading_spinner').show();
var post_data = "items=" + items;
$.ajax({
url: 'list.php',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('.my_update_panel').html(data);
},
error: function() {
alert("Something went wrong!");
},
complete:function(){
$('#loading_spinner').fadeOut(500);
});
//$('#loading_spinner').hide();
</script>
<style>
#loading_spinner { display:none; }
</style>
</head>
<body>
<img id="loading_spinner" src="image/ajax-loader.gif">
<div class="my_update_panel">
<!--I am not sure what to put here, so the results can show here-->
</div>
It is better to chain the ajax callback functions. adding callbacks as options will be removed from jquery in the future.
http://api.jquery.com/jQuery.ajax/
Deprecation Notice: The jqXHR.success(), jqXHR.error(), and
jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare
your code for their eventual removal, use jqXHR.done(), jqXHR.fail(),
and jqXHR.always() instead.
var post_data = items;
$('#loading_spinner').show();
$.ajax({
url: 'list.php',
type: 'POST',
dataType: 'html',
data: {"items":post_data},
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
$('#loading_spinner').hide();
});
I hide the loading_spinner in the always() callback, that way the spinner also disappears when the ajax call throws an error. if this is not working you have to search in your server side code to solve the problem. First of, are you sure the response is html? you might have to set the dataType to text in the ajax call.

jQuery UI Autocomplete not working with codeigniter

I'm trying to get a field on my view to autocomplete with values from a database but can't seem to figure out what is going wrong....
In my view I have the following script:
$(document).ready(function() {
$(function() {
$( "#searchQuestion" ).autocomplete({
source: function(request, response) {
$.ajax({ url: "<?php echo site_url('contentmanagement/suggestions'); ?>",
data: { term: $("#searchQuestion").val()},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
});
});
Within my contentmanagement controller I have the "suggestions" function:
function suggestions() {
$this->load->model('onlinehelp');
$term = $this->input->post('term', TRUE);
if (strlen($term) < 2)
break;
$rows = $this->onlinehelp->GetAutocomplete($term);
$keywords = array();
foreach ($rows as $row)
array_push($keywords, $row->question);
echo json_encode($keywords);}
And Finally within my model I have the follow function -
function GetAutocomplete($term) {
$this->db->select('question');
$this->db->like('question',$term, 'both');
$query = $this->db->get('question');
return $query->result();
}
The query above is the equivalent to "SELECT question FROM question WHERE question LIKE %$term%.
Can anyone see where I am going wrong with this??
You might be getting a 500 Internal Server Error caused by CSRF protection being enabled. If so, every POST request must contain a CSRF value. You have a few options:
1. Include the CSRF value in your data using $this->input->cookie('your_csrf_name');
2. Perform GET request instead of POST.
Use $this->input->get('term', TRUE); in your controller. Remember to sanitize and validate the value.
3. Disable CSRF protection. Not recommended.
This works with the CSRF enabled:
Use the jquery cookie plugin
<script type='text/javascript' src='<?php echo base_url(); ?>/js/lib/jquery.cookie.js'></script>
Then on your autocomplete thing:
<script type="text/javascript">
$(document).ready(function() {
$(function() {
$("#searchQuestion").autocomplete({
source: function(request, response) {
$.ajax({ url: "<?php echo site_url('contentmanagement/suggestions'); ?>",
data: { term: $("#searchQuestion").val(), ci_csrf_token: $.cookie("ci_csrf_token") },
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2,
focus: function( event, ui ) {
$("#searchQuestion").val(ui.item.term);
return false;
}
})
.data("autocomplete")._renderItem = function( ul, item ) {
return $( "<li></li>" )
.data( "item.autocomplete", item )
.append( "<a>" + item.term + "</a>" )
.appendTo( ul );
};
});
});</script>

Categories