When request is ajax, i am rendering content section and inserting it to DOM. It is working as expected.
However.. i can't find out the way, how to render multiple sections, like content and title and more in the same time.
Controller:
public function awesome(Request $request) {
if($request->ajax()){
return view('awesome')->renderSections()['content'];
}
return view('awesome');
}
Ajax and pushstate
var load = function (url) {
$.get(url).done(function (data) {
$("#content").html(data);
})
};
$(document).on('click', 'a[data-request="push"]', function (e) {
e.preventDefault();
var $this = $(this),
url = $this.attr("href"),
title = $this.attr('title');
history.pushState({
url: url,
title: title
}, title, url);
// document.title = title;
load(url);
});
layouts.app
<title>#yield('title')</title>
<meta name="description" content="#yield('desc')"/>
<a data-request="push" title="AWESOME" href="<?= url('/'); ?>/awesome">Awesome</a>
<a data-request="push" title="RANDOM" href="<?= url('/'); ?>/random">Random</a>
<div id="content">
#yield('content')
</div>
Blade:
#extends('layouts.app')
#section('title', 'Awesome')
#section('desc', 'About awesome')
#section('content')
some text from awesome page
#endsection
Question:
How to render both or more of them in same time? Should i use an array or something else? Please give example or full explanation.
Thanks for any answers.
You can just send a json object of title and content, and then use JS to parse the array and extract both sections. Like so:
Controller
public function awesome(Request $request) {
if($request->ajax()){
$view = view('awesome')->renderSections();
return response()->json([
'content' => $view['content'],
'title' => $view['title'],
]);
}
return view('awesome');
}
Ajax and pushstate
var load = function (url) {
$.get(url).done(function (data) {
$("#content").html(data.content);
document.title = data.title;
})
};
$(document).on('click', 'a[data-request="push"]', function (e) {
e.preventDefault();
var $this = $(this),
url = $this.attr("href"),
title = $this.attr('title');
history.pushState({
url: url,
title: title
}, title, url);
// document.title = title;
load(url);
});
Related
I'm wanting to load list of names from SQL DB. I then want to click the name and have corresponding image load. The first image should load when page loads. Names are loading. Image is not loading and ng-click does not load image. Made similar code work using JSON, but not able to make work using DB. Cats is the name of table. ImagePath and CatName are the fields in DB. New to PHP. Thank you.
<!doctype html>
<html>
<head>
<title>Load Images from DB</title>
<script src="angular.min.js"></script>
</head>
<body ng-app='myapp'>
<div ng-controller="userCtrl">
<div ng-repeat="user in Cats">
<h3 ng-click = "$scope.selectCat(cat)">{{user.CatName}}</h3>
</div>
<img ng-src="{{$scope.selectedCat.ImagePath}}"/>
<!-- Script -->
<script>
var fetch = angular.module('myapp', []);
fetch.controller('userCtrl', ['$scope', '$http', function ($scope, $http) {
$http({
method: 'get',
url: 'getData.php'
}).then(function successCallback(response) {
$scope.Cats = response.data;
$scope.selectCat=selectCat;
$scope.selectedCat=$scope.Cats[0];
function selectCat(pos) {
$scope.selectedCat = pos;
};
});
}]);
</script>
</div>
</body>
</html>
Here is PHP code
include 'config.php';
$sel = mysqli_query($con,"select * from Cats");
$data = array();
while ($row = mysqli_fetch_array($sel)) {
$data[] = array("CatName"=>$row['CatName'],"ImagePath"=>$row['ImagePath']);
}
echo json_encode($data);
Change you controller script by moving the selectCat outside of promise. Also assign it scope.
fetch.controller('userCtrl', ['$scope', '$http',
function ($scope, $http) {
$scope.selectCat = selectCat;
function selectCat(pos) { $scope.selectedCat = pos; }; });
}
$http({ method: 'get', url: 'getData.php' }).then(function successCallback(response) { $scope.Cats = response.data; $scope.selectedCat=$scope.Cats[0]; }]);
The php will be executed server side and render the data as json array.
Anyways i will update my answer.
I finally got it to work by changing the HTML to:
<div ng-controller = "MainController as **vm**">
<div ng-repeat = "cat in Cats">
<h3 ng-click = "vm.selectCat(cat)">{{cat.CatName}}</h3>
</div>
<hr>
<h3>{{vm.selectedCat.CatName}}</h3>
<img ng-src="{{vm.selectedCat.ImagePath}}"</img>
I then changed the controller to :
angular.module('myApp').controller('MainController', ['$scope','$http',function($scope,$http) {
**var vm = this;**
vm.selectCat=selectCat;
function selectCat(pos) {
vm.selectedCat = pos;
};
$http({
method: 'get',
url: 'getData.php'
}).then(function successCallback(response) {
**$scope.Cats = response.data;
vm.selectedCat=$scope.Cats[0];**
});
I want to show an image in img tag. when ajax is called in CodeIgniter.
this is the code which receives the data from the database and displays it in a bootstrap model. but the main problem is that I want to show an image in img tag but it not showing.
$(".Edit-modal").on("shown.bs.modal", function (e) {
var button = $(e.relatedTarget);
var ID = button.parents("tr").attr("data-id");
var modal = $(this);
$.ajax({
url: "'.base_url().'Employees/master_get_employees",
data: {ID:ID},
type: "POST",
success:function(output){
try{
var outputData = JSON.parse(output);
modal.find("#EditImage").attr("'.base_url().'src",outputData.pic);
}
catch(ex){
var split = output.split("::");
if(split[0] === "FAIL"){
Shafiq.notification(split[1],split[2])
}else{
Shafiq.notification("Could Not Load Data, Please Contact System Administrator For Further Assistance","error");
}
}
}
});
});
And This is the Img tag where I want to display image.
<div class="col-md-3">
<div class="form-group">
<label for="EditcontactNoSelector">Employee Picture</label>
<img src="" id="EditImage" alt="Not Found">
</div>
</div>
And this is the function through which data is fetched from the database
public function master_get_employees()
{
if ($this->input->post()) { //If Any Values Posted
if ($this->input->is_ajax_request()) { //If Request Generated From Ajax
$ID = $this->input->post('ID');
if (!isset($ID) || !is_numeric($ID)) {
echo "FAIL::Something went wrong with POST request, Please contact system administrator for further assistance::error";
return;
}
$table = "employees e";
$selectData = "e.id AS ID,e.Phone,e.Mobile,e.CNIC,e.Perm_Address,e.Picture as pic,d.name as Designation,s.title as Shift, e.Name,e.Father_Name AS FatherName,e.Phone AS Contact,e.JoinDate,e.BasicSalary, e.Pres_Address AS Address,e.IsEnabled";
$where = array(
'e.id' => $ID, 'e.IsActive' => 1
);
$result = $this->Common_model->select_fields_where_like_join($table, $selectData,$where, TRUE);
print json_encode($result,JSON_UNESCAPED_SLASHES);
}
}
}
I guess you have base_url() function in javascript to find base url of you site.
If so then you can use
$("#EditImage").attr("src",base_url()+outputData.pic);
If you don't have base_url() function in javascript you can find it here:
how to get the base url in javascript
instead of this
url: "'.base_url().'Employees/master_get_employees",
You can use below,
url: "<?php echo site_url('Employees/master_get_employees'); ?>",
Also at server side if you need only image url then just create image url from $result, store it in variable like $img_path in "master_get_employees" function and then just
echo json_encode(['img_path'=>$img_path]);
And in ajax success just do below
$("#EditImage").attr('src',outputData.img_path);
I'm having some conflicting issues with my Laravel setup, specifically with the pagination and product filters.
Both pagination and product filters is being handled via jQuery so the page doesn't completely refresh.
This is my jQuery pagination code, working with the standard Laravel ->paginate functionality.
$(function() {
$('body').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
var page_number = $(this).attr('href').split('page=')[1];
getProducts(page_number);
window.history.pushState("", "", url);
});
function getProducts(page_number) {
$.ajax({
url : '?page=' + page_number
}).done(function (data) {
$('.devices-holder').html(data);
}).fail(function () {
alert('Data could not be loaded.');
});
}
});
This works great, the issue is when we filter the products, and then try and go to another page on the filtered results.
Right after filtering, the paginate links are correct for example /devices/filter?filter=1&page2, however on clicking this the page loads all devices without the filter, even though if I copy that url and load that page, it succesfully goes to page 2 with the filters included.
Then the paginate URL's are completely ignoring the filter afterwards, and is /devices?&page=2. I figured it must be to do with me rendering and appending the paginate links in the view, but am unsure what I am doing wrong:
{!! $devices->appends(Input::all())->render() !!}
This is my controller:
public function devicesByFilter(Request $request) {
$type = 'devices';
$types = Input::get('types');
$devices = Device::where('type', '=', $type)->where('approved', '=', 1);
if(!empty($types)) {
$url = 'filter';
$check = 0;
foreach($types as $deviceType) {
if($check == 0) {
$devices = $devices->where('device_type', 'LIKE', $deviceType);
} else {
$devices = $devices->orWhere('device_type', 'LIKE', $deviceType);
}
$url = $url.'&types%5B%5D='.$deviceType;
$check++;
}
}
$devices = $devices->orderBy('match_order', 'asc')->paginate(10);
$devices->setPath('filter');
if ($request->ajax()) {
return view('devices.ajax.loadfilter', ['devices' => $devices, 'type' => $type, 'types' => $types])->render();
}
return View::make('devices.all', compact('devices', 'type'));
}
And this is my filter jQuery code:
$(document).ready(function () {
var types = [];
// Listen for 'change' event, so this triggers when the user clicks on the checkboxes labels
$('input[name="type[]"]').on('change', function (e) {
e.preventDefault();
types = []; // reset
if ( document.location.href.indexOf('filter') > -1 ) {
var url = '../devices/filter?type=device';
} else {
var url = 'devices/filter?type=device';
}
$('input[name="type[]"]:checked').each(function()
{
types.push($(this).val());
url = url+'&types%5B%5D='+$(this).val();
});
if ( document.location.href.indexOf('filter') > -1 ) {
$.get('../devices/filter', {type: 'devices', types: types}, function(markup)
{
$('.devices-holder').html(markup);
});
} else {
$.get('devices/filter', {type: 'devices', types: types}, function(markup)
{
$('.devices-holder').html(markup);
});
}
window.history.pushState("", "", url);
});
});
So at a poor attempt to clarify:
Pagination jQuery works perfect
Filtering works perfect
Trying to go another page after filtering displays all devices not just the filtered ones, even though the URL is correct and if I load this URL again on another tab, it has the right results.
After trying to go to another page of filtered results, the pagination links are missing the append input.
It's very difficult to debug this from here, anyone who can point in the right direction or something to try/test would be great.
Fixed it by changing
$(function() {
$('body').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
var page_number = $(this).attr('href').split('page=')[1];
getProducts(page_number);
window.history.pushState("", "", url);
});
function getProducts(page_number) {
$.ajax({
url : '?page=' + page_number
}).done(function (data) {
$('.devices-holder').html(data);
}).fail(function () {
alert('Data could not be loaded.');
});
}
});
to
$(function() {
$('body').on('click', '.pagination a', function(e) {
e.preventDefault();
var url = $(this).attr('href');
getProducts(url);
window.history.pushState("", "", url);
});
function getProducts(url) {
$.ajax({
url : url
}).done(function (data) {
$('.devices-holder').html(data);
}).fail(function () {
alert('Data could not be loaded.');
});
}
});
I need when I click anchor tag I need load controller function and get data from calling function in the model and send it to view_content page and display data
here is my code
view
<div id="loading"></div>
Click Here
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".company").click(function(e){
e.preventDefault();
var id = $(this).attr('id');
var site_url = "<?php echo site_url('site2/home2/'); ?>" +id; //append id at end
$("#loading").load(site_url);
//alert(id);
//alert("aawa");
});
});
</script>
controller
public function home2($id){
$this->load->model('get_click_data');
$data['company_data'] = $this->get_click_data->get_company($id);
$this->load->view('view_content',$data);
}
model
<?php
class Get_click_data extends CI_Model{
public function get_company($id){
$query = $this->db->query("SELECT * from companydetails where id = '$id'");
return $query->result();
}
view_content
<div id="content">
<h3>Welcome to Home Page 12345</h3>
<?php
print_r($company_data);
?>
as you are using codeigniter, try changing to:
...
var id = $(this).attr('id'); //you need to have 'id' attribute in your anchor
$("#loading").load("<?php echo site_url('site2/home2/); ?>" + id, function() {
alert("aawa");
});
...
and in your controller file,
function some_function($your_id) {
//get data
//do something with $your_id
//pass view as string
echo $this->load->view('view_content', $data, TRUE);
}
Update::
to put js variable in your site url, do:
var id = $(this).attr('id');
var site_url = "<?php echo site_url('site2/home2/'); ?>" + id; //append id at end
$("#loading").load(site_url, function() {
alert("aawa");
});
one more update::
if you want to pass multiple parameters to your function from js, you can do:
var id = $(this).attr('id');
var second_param = "some value here";
var site_url = "<?php echo site_url('site2/home2/'); ?>" + id + "/" + second_param;
$("#loading").load(site_url, function() {
alert("aawa");
});
and in your controller function
function some_function($your_id, $other_param) {
do something with $your_id and $other_param
//pass view as string
echo $this->load->view('view_content', $data, TRUE);
}
addition::
in your home2() function your are trying to load view, change
$this->load->view('view_content',$data);
to
echo $this->load->view('view_content',$data, TRUE);
so that its returned as string to your .load() jquery function
its working
<script type="text/javascript">
$(document).ready(function(){
$(".company").click(function(e){
e.preventDefault();
var id = $(this).attr('id');
$("#loading").load('<?php echo site_url('site2/home2/'); ?>'+id);
alert(id);
//alert("aawa");
});
});
How to change my page title <title></title> after content is loaded in #container div?
$(document).ready(function () {
$("a.view").live('click', function () {
var id = $(this).data("id");
$('#container').load("view.php?" + id);
});
});
If without .load() I retrieve it by get the id via URL, example view.php?id=1
if (isset($_GET['id'])) {
$pageid = intval($_GET['id']);
$select = $db->query('SELECT id, title FROM content WHERE id="'.$id.'"');
$data = $db->fetch($select);
$title = $data['title'];
}
So in my header.php just call it <title><?php echo $title; ?></title>
If in this case file is load after header.php so how can I create dynamic my page title according to current .load("view.php?" + id)?
You can set the document.title property:
document.title = "My new title!";
add a callback function in the .load call, the responseText, textStatus, XMLHttpRequest are all arguments that will be passed to the callback.
function myCallback(responseText, textStatus, XMLHttpRequest)
{
document.title = "Set new title";
}
$(document).ready(function () {
$("a.view").live('click', function () {
var id = $(this).data("id");
$('#container').load("view.php?" + id,myCallback);
});
});