Laravel/ajax retrieving data from database - php

I use laravel and now I want to search from DB by ajax. It work but I want to show the result any where that I want not in the footer in current situation.
Do you now how get and show data in this section?
<script>
$(document).ready(function() {
src = "{{ url('/')}}/users/searchhistory";
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
minLength: 1,
});
});
</script>
And controller
public function autoComplete(Request $request) {
$query = $request->get('term','');
$products=User::where('fullname','LIKE','%'.$query.'%')->get();
$data=array();
foreach ($products as $product) {
$data[]=array('value'=>$product->fullname,'id'=>$product->id);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}

use json() in return statment of controller
public function autoComplete(Request $request)
{
//othercodes
return response()->json($data);
}
Then in your ajax result you have the proper json-formatted response
You can add data to html tag
$.ajax({
success: function(data) {
$.each(data,function(prodcut){
// now you have every product
use javascript append function to a add new element with this product data
});
}
});

Related

Get date from datepicker using Ajax with Laravel controller

i want to get the datepicker value when user selected a date and send that using ajax to a laravel controller. this code is not worked for me..
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#date').datepicker({
format: 'dd-mm-yyyy',
onSelect: function(date, instance) {
$.ajax({
type: "POST",
url: '/process_date',
data: date,
success: function(result)
{
console.log(result);
}
});
}
});
here is my route,
Route::post('/process_date', 'TimeController#ajaxTime');
here is my controller,
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
$data = $request->all(); // This will get all the request data.
dd($data); // This will dump and die
}
}
Try changing your code to this because I have been reading the documentation and testing it with some code of my own and this is what I came up with
$('#date').datepicker({
format: 'dd-mm-yyyy',
}).on('changeDate', function(e) {
$.ajax({
type: "POST",
url: '/process_date',
data: {
date: e.date.toString(),
},
success: function(result) {
console.log(result);
},
error: function (error) {
console.log(error);
}
});
})
and also change your TimeController class from
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
$data = $request->all(); // This will get all the request data.
dd($data); // This will dump and die
}
}
to
class TimeController extends Controller
{
public function ajaxTime(Request $request)
{
return $request->all(); // This will get all the request data.
}
}
to receive better results in your browser console.

How to disable click when autocomplete Field "no rseult found" via ajax call

I have done almost everything and I have successfully implemented autocomplete searching with ajax. Now problem is that when no data is found in autocomplete searching by default it shows No Result found. When I click on "NO Results Found" it is appearing on textbox. I want when No Results Found and user tries to click on that it should be no clickable
Here is My jquery Code:
src = "{{ route('searchajax') }}";
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
});
And My laravel 5.2 function
public function autoComplete(Request $request) {
$query = $request->get('term','');
$states=DB::table('states')->where('state','LIKE','%'.$query.'%')->get();
$data=array();
foreach ($states as $state) {
$data[]=array('value'=>$state->state,'id'=>$state->id);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}
This is the answer you are looking for
You can use the response function to check if you do have results. If not, just push "No results found" to your list and then use _renderItem to disable this option.
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
response: function(event, ui) {
if( ui.content.length === 0 ) {
ui.content.push({
'label': 'No results found',
'value': ''
});
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
if( item.value == '' ) {
return $('<li class="ui-state-disabled">'+item.label+'</li>').appendTo(ul);
} else {
return $("<li>").append("<a>" + item.label + "</a>").appendTo(ul);
}
};
I made this fiddle so you can see it working.

How to Return JSON array to JQUERY alert in Laravel

I want JSON to return value is an array with Alert
Currently only returns the ID But need Array From Table Record.
I have table categry with 2 column: ID ,Category.I'm gonna give both displays
my controller:
public function create(messageRequest $request)
{
try {
$category = Category::create($request->all())->id;
return response()->json(['id'=>$category]);
}catch (Exception $e){
return response()->json(array('err'=>'error'));
}
}
my ajax code:
$.ajax({
type: 'post',
url: '{!! URL::route('category') !!}',
data: data,
success: function (data) {
alert(data.id);
},
error: function () {
alert(data.err);
}
});
I'm note quite sure to fully understand your question, but if you want to return the entire Category record with this controller, you only need to make:
public function create(messageRequest $request)
{
try {
$category = Category::create($request->all());
return $category
}catch (Exception $e){
return response()->json(array('err'=>'error'));
}
}
You will then be able to access to all your Category data into your ajax callback:
$.ajax({
type: 'post',
url: '{!! URL::route('category') !!}',
data: data,
success: function (data) {
alert('The category I just saved is named ' + data.name + ' and its ID is ' + data.id);
},
error: function () {
alert(data.err);
}
});
I hope this helps

Display results in twig json

I have in my controller a function to make a search filter.
The search parameter is obtained from a select field of my twig template.
The selected option is passed to the controller to see where results are with that value.
The query result is returned in JSON format.
Controller:
public function categoryAction(Request $request)
{
$category = $request->request->get('category');
$contentCategory = $em->getRepository('MyAppBundle:Content')->findByCategory($category);
$filterContent = new JsonResponse();
$filterContent->setData([
'categoryResult' => $contentCategory
]);
return $filterContent;
}
Twig template:
$('#selectCategory').change(function() {
var optionSelect = $(this).val();
$.ajax({
url: '{{path('playlist_category') }}',
data: '&category='+optionSelect,
type: 'POST',
success: function(filterContent) {
},
error: function(e){
console.log(e.responseText);
}
});
});
How I can display the result returned in JSON in my function 'success'?
You should change your JS code to the following. I would rather user $.post than $.ajax. And don't forget to pass json as fourth arg.
$('#selectCategory').on('change', function () {
var optionSelect = $(this).val();
$.post("{{path('playlist_category') }}", {category: optionSelect}, function (res) {
console.log(res);
}, 'json');
});

Get a single row from the database using AJAX in CodeIgniter?

I wonder how to get data from database using AJAX in CodeIgniter. Could you please check the code below to find out the reason of problem? Nothing happens when I click on the link from my view.
Here is my view:
<?php echo $faq_title; ?>
Here is my controller:
public function get_faq_data() {
$this->load->model("model_faq");
$title = $_POST['title'];
$data["results"] = $this->model_faq->did_get_faq_data($title);
echo json_encode($data["results"]);
}
Here is my model:
public function did_get_faq_data($title) {
$this->db->select('*');
$this->db->from('faq');
$this->db->where('faq_title', $title);
$query = $this->db->get('faq');
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Here is my JavaScript file:
$(".faq_title").click(function() {
var title = $(this).text();
$.ajax({
url: 'faq/get_faq_data',
data: ({ title: title }),
dataType: 'json',
type: 'post',
success: function(data) {
response = jQuery.parseJSON(data);
console.log(response);
}
});
});
Try this:
$(function(){ // start of doc ready.
$(".faq_title").click(function(e){
e.preventDefault(); // stops the jump when an anchor clicked.
var title = $(this).text(); // anchors do have text not values.
$.ajax({
url: 'faq/get_faq_data',
data: {'title': title}, // change this to send js object
type: "post",
success: function(data){
//document.write(data); just do not use document.write
console.log(data);
}
});
});
}); // end of doc ready
The issue as i see is this var title = $(this).val(); as your selector $(".faq_title") is an anchor and anchors have text not values. So i suggested you to use .text() instead of .val().
The way I see it, you aren't using the anchor tag for its intended purpose, so perhaps just use a <p> tag or something. Ideally, you should use an id integer instead of a title to identify a row in your database.
View:
<p class="faq_title"><?php echo $faq_title; ?></p>
If you had an id integer, you could use a $_GET request an receive the id as the lone parameter of the get_faq_data() method.
Controller:
public function faqByTitle(): void
{
if (!$this->input->is_ajax_request()) {
show_404();
}
$title = $this->input->post('title');
if ($title === null) {
show_404();
}
$this->load->model('model_faq', 'FAQModel');
echo json_encode($this->FAQModel->getOne($title));
}
FAQ Model:
public function getOne(string $title): ?object
{
return $this->db->get_where('faq', ['faq_title' => $title])->row();
}
JavaScript:
$(".faq_title").click(function() {
let title = $(this).text();
$.ajax({
url: 'faq/faqByTitle',
data: {title:title},
dataType: 'json',
type: 'post',
success: function(response) {
console.log(response);
}
});
});
None of these snippets have been tested.

Categories