Laravel dynamic content from database clicking on navbar using ajax - javascript

I am using laravel 7.I am new in laravel and ajax . I have a 'product's name' navbar. I want , When I click on a product from the navbar , the details of the product will show in a div without reloading the page. demo : ( https://www.webslesson.info/2017/03/dynamic-content-load-using-jquery-ajax-php.html ) the demo is in PHP, I want to use this in laravel.
blade part:
<ul class="nav navbar-nav">
<?php
$group = DB::table('package')->where('group_id', 5)->get();
?>
#foreach ($group as $item)
<li id="{{ $item->package_id }}">{{$item->package_name }}</li>
#endforeach
</ul>
<span id="page_details"></span>
scipt part for ajax on blade file
<script>
$(document).ready(function () {
function load_page_details(id) {
$.ajax({
type: 'POST',
url: '/getmsg',
data: '_token = <?php echo csrf_token() ?>',
data: {id: id},
success: function (data) {
$('#page_details').html(data);
}
});
}
load_page_details(1);
$('.nav li').click(function () {
var page_id = $(this).attr("id");
load_page_details(page_id);
});
});
</script>
route:
Route::post('/getmsg','AjaxController#index');
controller:
public function index(Request $request)
{
$pack_id=$request->id;
$msg = DB::table('package')->where('package_id',$pack_id);
$output .= '
<h1>'.$msg->package_id.'</h1>
';
return $output;
}
Please help me to make a thing in laravel like the demo ( http://demo.webslesson.info/dynamically-loading-content-with-ajax/# )

First of all, you have 2 data properties on your ajax request. Make that as 1 :
data: { "_token" : "{{ csrf_token() }}", "id" : id}
Then, I would recommend setting dataType to json in the AJAX request, and from the controller returning a json response, instead of the $output = .. bit.
return response()->json(['package_id' => $msg->package_id]);
After that, from your .success callback, you can access the properties of data just as you would with a normal javascript object. To achieve what you want you can use $('#page_details').html(data.package_id).

Related

Ajax request not running used in codeigniter 4 [duplicate]

I am using codeigniter-4 version and trying to auto search in nav bar. I'm trying to send data in post method into controller using ajax. But its not work. And codeigniter 4 don't described details for ajax. below my code sample
input box is -
<input class="form-control mr-sm-2" type="search" placeholder="<?= lang('nav.search'); ?>" aria-label="Search" name='s' id="seachBox">
ajax code is -
$.ajax({
url:<?= base_url('search'); ?>,
headers:{'X-Requested-With':'XMLHttpRequest'},
data:{query:query},
success:function(data){
alert(data);
}
});
and my controller is -
<?php
class Search extends BaseController
{
public function __construct()
{
helper(['common_helper','aws_helper']);
}
public function index(){
echo 'string';
}
}
?>
route is -
<?php
$routes->get('/search', 'Search::index');
?>
Here is the sample code of ajax. (Make sure that you have defined route/controller method for search url)
$.ajax({
url:<?php echo base_url('search'); ?>,
type: 'post',
dataType:'json',
data:{query:query},
success:function(data){
alert(data);
}
});
CI4 Code to get the request data
if ($this->request->isAJAX()) {
$query = service('request')->getPost('query');
var_dump($this->request->getPost('query'));
}
Also, make sure to update csrf token on every request if you are not reloading a page on success. Also, you need to return csrf token in method.
So in that case your method will look like -
if ($this->request->isAJAX()) {
$query = service('request')->getPost('query');
//var_dump($this->request->getPost('query'));
return json_encode(['success'=> 'success', 'csrf' => csrf_hash(), 'query ' => $query ]);
}
So in that case your ajax code will look like -
$.ajax({
url:<?php echo base_url('search'); ?>,
type: 'post',
dataType:'json',
data:{query:query},
success:function(data){
var result = JSON.parse(data);
$("input[name='csrf_test_name']").val(result['csrf']);
}
});

Select2 POST AJAX Request 500 Error Laravel

I'm trying to use select2 retrieving large data in my dropdown using the following article.
Getting 500 Internal Server Error in my console log.
I have store token in HTML meta tag.
<meta name="csrf-token" content="{{ csrf_token() }}">
And sending a token as a parameter in my POST request.
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$(document).ready(function(){
$( "#test" ).select2({
ajax: {
url: "path/to/url",
type: "POST",
dataType: 'JSON',
delay: 250,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
});
<select class="test" id="test" style="width:100%;"></select>
I have checked routes using php artisan route:list and clear cache using php artisan config:cache. But still getting the same error link. and link.
Is there anything I'm missing? I would be grateful if you can help me out to debug/inspect my Request and Response.
Tried
error: function(err){
console.log(err)
}
Server-Side \ Controller
public function getdata(Request $request){
$search = $request->search;
if($search == ''){
$data = DB::table('table')
->orderby('name','asc')
->select('id','name')
->limit(5)->get();
}else{
$data = DB::table('table')
->orderby('name','asc')
->select('id','name')
->where('name', 'like', '%' .$search . '%')
->limit(5)->get();
}
$response = array();
foreach($data as $i){
$response[] = array(
"id"=>$i->id,
"text"=>$i->name
);
}
return response()->json($response);
}
Happy Coding.

Search bar by jquery ui autocomplete using PHP and MYSQL

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.

Get variable from javascript into controller

I need to have a variable from an java script function into my controller.
Here you can see my ajax function
<script>
$('#spielAuswahl').on('change', function(e){
console.log(e);
var spielID = e.target.value;
//ajax
$.get('/spieler?spielID=' + spielID, function(data){
console.log(data);
});
});
</script>
And this is my web router
Route::get('/spieler', 'SpielerController#getSpieler');
And here my controller function
public function getSpieler(){
$spielID = Input::get(spielID);
echo $spielID;
}
I have this issue
jquery.js:9664 GET http://localhost:8000/spieler?spielID=3 500
(Internal Server Error)
What I have to change?
I don't know what you exatly want to do, but here is a solution to pass a value.
You can name your routes, example:
Route::post('/spieler', ['as' => 'spieler', 'uses' => 'SpielerController#getSpieler']);
Your jquery:
var token = "{{ Session::token() }}";
$('#spielAuswahl').on('change', function(e){
console.log(e);
var spielID = e.target.value;
$.ajax({
method: "POST",
url: "{{ route('spieler') }}",
data: {id: spielID, _token: token}
});
}
Finally your controller:
public function getSpieler(Request $request) {
$id = $request['id'];
echo $id;
}
The code you have shown is missing some quotes:
public function getSpieler(){
$spielID = Input::get('spielID'); // quote `spielID` here
echo $spielID;
}
If you're using Laravel 5, you can use the request:
use Illuminate\Http\Request;
...
public function getSpieler(Request $request) {
echo $request->spielID;
}
You can find out more more details about your 500 Server Error in the web server logs, and storage/logs/laravel.log.

Ajax + Controller Action in Yii2

I'm new to programming, and I'm trying to call a function when the user inputs data and clicks submit button. I'm using Yii2 and I'm not familiar with Ajax. I tried developing a function, but my controller action isn't called.
Here is the example code I'm trying:
views/index.php:
<script>
function myFunction()
{
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
type: 'post',
data: {searchname: $("#searchname").val() , searchby:$("#searchby").val()},
success: function (data) {
alert(data);
}
});
}
</script>
<?php
use yii\helpers\Html;
use yii\widgets\LinkPager;
?>
<h1>Supermarkets</h1>
<ul>
<select id="searchby">
<option value="" disabled="disabled" selected="selected">Search by</option>
<option value="Name">Name</option>
<option value="Location">Location</option>
</select>
<input type="text" value ="" name="searchname", id="searchname">
<button onclick="myFunction()">Search</button>
<h3> </h3>
Controller:
public function actionSample(){
echo "ok";
}
My problem is that when I click on the Search button nothing happens, and when I try to debug it, the debugger runs no code!
This is sample you can modify according your need
public function actionSample()
{
if (Yii::$app->request->isAjax) {
$data = Yii::$app->request->post();
$searchname= explode(":", $data['searchname']);
$searchby= explode(":", $data['searchby']);
$searchname= $searchname[0];
$searchby= $searchby[0];
$search = // your logic;
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return [
'search' => $search,
'code' => 100,
];
}
}
If this will success you will get data in Ajax success block. See browser console.
$.ajax({
url: '<?php echo Yii::$app->request->baseUrl. '/supermarkets/sample' ?>',
type: 'post',
data: {
searchname: $("#searchname").val() ,
searchby:$("#searchby").val() ,
_csrf : '<?=Yii::$app->request->getCsrfToken()?>'
},
success: function (data) {
console.log(data.search);
}
});
you have to pass _csrf tokin as a parameter
_csrf: yii.getCsrfToken()
or you can disable csrf valdation
The correct way to get the CSRF param is this:
data[yii.getCsrfParam()] = yii.getCsrfToken()

Categories

Resources