How to add/include views in Laravel using Ajax - ajax

I'm bit stuck at a place. I've got some views of small HTML sections which when combined gives the complete HTML page. I'm trying to build a website builder with Jquery, where I'm having a drop event which adds those particular views:
For example I've got HTML for slideshow:
<div id="slideshow" data-nitsid="2">
<div class="revolution-slider">
<ul>
<!-- SLIDE -->
#foreach($contents->slider as $sliders)
<li data-transition="{{ $sliders->transition }}" data-slotamount="{{ $sliders->slotamount }}" data-masterspeed="{{ $sliders->masterspeed }}">
<!-- MAIN IMAGE -->
<img src="{{ URL::asset($sliders->url) }}" alt="">
</li>
#endforeach
</ul>
</div>
</div>
In my JQuery code:
nitsbuilder.dropeventhandler = function ($item, $position) {
var nits_id = $item.data('nitsid');
$.ajax({
method: 'POST',
url: dropurl,
data: { nits_id: nits_id, _token: token},
dataType: 'json',
success: function (data) {
nitsbuilder.adder($item, $position, data);
}
});
}
Before I was having html codes in the database so it was easier to pull out the html and add to the HTML page, now I'm having html in views, how can I push/include this HTML code or view to ajax request so that my nitsbuilder.adder function executes placing the view through my controller.
My present Controller is:
class DropeventController extends Controller
{
public function htmlcode(Request $request)
{
$pluginid = $request['nits_id'];
$code = Plugins::findOrFail($pluginid);
$htmlcode = $code->code;
return response()->json(['htmlcode' => $htmlcode]);
}
}
Please guide me. Thanks

You can easily create html strings from blade views using \View::make
e.g. let's assume you have the following folder strucutre
project
...
ressources
views
snippets
snippetA
snippetB
You could now create a route / controller accepting a "name" parameter and then do the following
$name = "snippetA"; // get this from parameters
$html = \View::make("snippets.$name")->render();
You might need to also add variables depending on your views
$name = "snippetA"; // get this from parameters
$errors = []; // error variable might be needed
$html = \View::make("snippets.$name", compact('errors'))->render();
You can then return this html string
return ['html' => $html];
And access it from your ajax done function.
I hope this helps

Suppose your html is in view file called abc.blade.php, you can return the rendered view from your controller in json.
return response()->json([
'htmlcode' => View::make('abc')->render();
]);

Related

URL::to('/') echoed as string (Laravel)

I'm working with my project which get new orders and append to DOM with jQuery.
jQuery
setInterval(function() {
$.ajax({
type:'POST',
url:'{{URL::to('/')}}/orders',
success:function(data)
{
let obj = JSON.parse(data)
let ordersDiv = $('#ordersDiv');
let queueCount = $('#queueCount');
queueCount.html(obj.count);
ordersDiv.html(obj.data);
}
});
}, 15000);
Controller
//some code here
$data .= "<a class=\"example-image-link\"
href=\"{{URL::to('/')}}/users/uploads/profiles/{{strlen($biker-
>picture_file_path)>0?$biker>picture_file_path:'avatar.png'}}\">
<img src=\"URL::to('/')/users/uploads/profiles/$biker-
>picture_file_path:.'avatar.png'\" data-toggle=\"tooltip\"
title=\"HiBes Biker\">
</a>";
//more code here
My problem is that I'm getting this result:
<a href=\"{URL::to('\/')}\/order-details\/3159\">Details<\/a>
I expect a result something like this:
<a href=\"http://127.0.0.1:8000/order-details\/3159\">Details<\/a>
The reason your URLs still contain the placeholders is you are building HTML in your controller, not your view.
Ideally, you should switch this logic into the view, where the {{ $var }} syntax will work.
Create a new blade file bikerimage.blade.php
#foreach($bikers as $biker)
<a class="example-image-link"
href="{{URL::to('/')}}/users/uploads/profiles/{{ $biker->picture_file_path ?: 'avatar.png' }}">
<img src="{{ URL::to('/')}}/users/uploads/profiles/{{ $biker->picture_file_path ?: 'avatar.png' }}"
data-toggle="tooltip"
title="HiBes Biker"
>
</a>
#endforeach
Then in your controller, you can do something like
//some code here
$data = view('partials/bikerimage.blade.php', ['bikers' => $bikers])->render();
return [
'html' => $data,
];
This means you can still return the data as part of an ajax call, without having to build HTML in your controller.

Preview post functionality (like in Wordpress) in a Laravel's blog

I'd like to add to my Laravel's blog app the ability to open a preview of a post in a new window/tab before saving it to the DB (like in Wordpress). Which is the best way to do it?
I've been reading a few posts about it, and for now I've tried something like this:
When I click the 'Preview' button in my create post view I make an ajax call to the store method, which will return a laravel's blade rendered view...
$('.preview-post').click(function () {
var formData = $('#post-form').serializeArray();
$.ajax({
method: 'POST',
url: '/admin/posts/store',
dataType: 'json',
data: formData
}).done(function (response) {
var w = window.open();
w.document.write(response);
});
});
Here's the method in my controller:
public function store(Request $request)
{
$title = $request->input('title');
$post = new Post();
$post->title = $title;
if ($request->ajax()) {
return response()->json(view('home.posts.ajax-post', compact('post'))->render());
}
}
As you can see, for the moment I've just included the title field, not the whole post, just to check if it works.
Finally, here's the view I'm returning and opening in a new window:
#extends('layouts.home')
#section('content')
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="post-content">
{{$post->title}}
</div>
</div>
</div>
</div>
#endsection
So that's it. The problem is: it seems to work (I'm able to get the view in a new tab with the expected title I typed in the form field), but I guess I'm doing something wrong, because I have for example some animated svg elements that don't render in the proper way in the new window. I've also started with Laravel Framework like a month ago, so I don't know if I'm following the correct workflow to do something like this.

codeigniter Click button to call a view

I am having a view with 2 buttons in my codeigniter view:
<div class="btn-main col-md-3 col-md-offset-3">
<button id="simu-mono" type="button" class="btn btn-default">SIMULATION MONO SITE</button>
</div>
<div class="btn-main col-md-3">
<button id="simu-multi" type="button" class="btn btn-default">SIMULATION MULTI SITE</button>
</div>
I would like to call another a controller to launch then a view when the button is clicked
I tried out to call the controller simu_mono by javascript, putted on /controller/simu_mono.php but doesn' t work
$(document).ready(function(){
$("#simu-mono").click(function(){
type:'GET',
url:'simu_mono'
});
$("#simu-multi").click(function(){
});
});
simu_mono.php:
<?php
class simu_mono extends CI_Controller {
public function index()
{
$this->load->view('simu_mono');
echo 'Hello World!';
}
}
?>
Thanks for your helps
Cheers
Please, if u want to redirect only use following code:
$(document).ready(function(){
$("#simu-mono").click(function(){
window.location = base_url + "/simu_mono";
});
$("#simu-multi").click(function(){
window.location = base_url + "/simu_multi";
});
});
Note that you might need base_url, use this snippet to load base_url in JavaScript variable
<script>
base_url = <?= base_url()?>
</script>
put code above in some kind of view that is loaded always (before any other JavaScript code is executed)
Additional step would be to set up routes that take care of ugly underscore symbol (_)
something like:
routes.php
$route['simu-mono'] = "simu_mono";
$route['simu-multi'] = "simu_multi";
this way you go to your page and controller following way: yourserver.ufo/simu-mono and yourserver.ufo/simu-multi
You're not doing any class of AJAX call within your javascript. I assume you're using jQuery, so, your call should be something like:
$("#simu-mono").click(function(){
$.ajax({
url: "http://your-url.com/controller/method",
type: 'post', // <- Or get option, whatever you prefer
dataType: 'json', // <- This is important to manage the answer in the success function
//data: { param1: "value1", param2: "value2"}, <- You could add here any POST params you wanted
success: function(data){
if (data.view) {
$('#here_view').html(data.view); // <- '#here_view' would be the id of the container
}
if (data.error){
console.log(data.error);
}
}
});
});
This will call your method, where you will have to indicate you want to pass the view:
<?php
class simu_mono extends CI_Controller {
public function index()
{
$return = array(
'view' => $this->load->view('simu_mono')
);
echo json_encode( $return );
}
}
?>
json_encode will allow you easily pass vars and data from PHP to your javascript, and manage them in the client view. As you see in the javascript, I added data.error, this is just in case you'll have more logic, maybe change the view you're sending, send an error if you sent data and want to control them, etc.
Of course, in your javascript you could take the url from the clicked button, and in data.view parat of the success function, you may print in the screen a modal, send the view to a container, whatever you wanted, XD

codeigniter and tab contents

I have some tabs whose contents are fully functional parts of my website.
For instance, in my admin area, I have tabs [add/delete album][add photo][delete photo]. I'm technically dividing the admin area via tabs.
I'm using ajax to load the content into these tabs. tab content area is a div.
The view that is inside the tab content area also uses ajax to load stuff.
These are ajax calls that operates inside the tab content area.
Everything works fine as long as the view inside the tab content area stays same or only part of it changes. But when certain interactions inside tab content area return a whole new view, tab content area would not show them.
I know what happens is that this new view that is returned is not passed into the tab content area div.
In firebug, I can see that ajax success function response shows the new view that is returned.
But I do not know how to pass that new view to the tab content area.
I would appreciate it if someone could help me out in explaining how this could be solved or how contents inside tabs are managed in CI.
adminTabsview.php
<ul id="adminTabs">
<li ><?php echo anchor('#album_addDelete', 'Album Add/Delete'); ?></li>
</ul>
<div id="adminTabsContent"></div>
$(document).ready(function(){
$('#adminTabs a').on({
click: function (evt){
evt.preventDefault();
var page = this.hash.substr(1);
adminTabsAjaxCall(page);
}
});
});
function adminTabsAjaxCall ($data){
$.ajax({
type: "POST",
url: "index.php/adminsite_controller/"+ $data + "/",
dataType: "html",
data: $data,
statusCode: {removed}
},
success: adminTabContent
});
function adminTabContent (data){
$('#adminTabsContent').html(data);
}
albumsEditDeleteView.php
(this is a view that gets loaded into the tab contentarea div)
<div id="adminTabsContent">
<div id="albumList">
<ul>
<li>
Asdf
<a class="add" href="http://localhost/myPHP/photoalbums/index.php/Albums_Controller/add_album/301/Asdf/1/28/0">[ add ]</a>
<a class="delete" href="http://localhost/myPHP/photoalbums/index.php/Albums_Controller/delete_album/301/Asdf/1/28/0">[ delete ]</a>
</li>
</ul>
</div>
</div>
$(document).ready(function(){
$('#albumList').on({
click: function (evt){
evt.preventDefault();
var $clickedElement = evt.target.tagName;
if ($clickedElement == 'A' ){
var urlarray = url.split('/');
$chosen.albumid = urlarray[8];
$chosen.albumname = urlarray[9];
$chosen.lft = urlarray[10];
$chosen.rgt = urlarray[11];
$chosen.nodeDepth = urlarray[12];
if ($class == 'add'){
albumajaxcall($chosen);
}
if ($class == 'delete'){
deleteajaxcall($chosen);
}
}
}
});
});
function albumajaxcall($data){
$.ajax({
type: "POST",
url: "index.php/Adminsite_Controller/add_album/",
dataType: "json",
data: $data,
statusCode: {removed}
},
success: adminTabContent
});
}
function adminTabContent(data){
$('#adminTabsContent').html(data);
}
//heres the view file that has to replace the original view inside
//tabcontent area
//addnode_view.php
<?php echo form_open('Albums_Controller/update_albumSet');?>
<input type="text" name="newAlbum" id="newAlbum" value=""/>
<input type="submit" name="submit" value="Submit" />
<?php echo form_close();?>
<?php
//heres the controller function
function add_album(){
$levelData ['albumid'] = $this->input->post('albumid');
<!-- removed-->
$levelData ['main_content'] = 'addnode_view';
$this->load->view('includes/template', $levelData);
}
//And heres the controller method that loads
//the original page (albumsEditDeleteView.php) - this is the original view
//that gets loaded into the tab- I get stuck when this view
//has to be **totally** replaced through links in the view)
function album_addDelete(){
$allNodes ['myAlbumList'] = $this->Albums_Model->get_albumList();
echo $this->load->view('albumsEditDelete_view', $allNodes);
}
thanx in advance.
basically what you need to do is load whatever new view youll be putting in the tab in the controller function(adminsite_controller/whatever function) that is handling your ajax.
this will basically echo out the view file, which will be viewed as the success variable of your ajax function.
so you have something like this then for the success part of your ajax
success:function(msg){adminTabContent(msg);}
and in your controller in codeigniter you'll load a view the standard way, but since this will be only loading a piece of the page you may need to create a new view file thats just the div that will be there. You will do all your data gathering the same way you would if it wasn't ajax.
$data['some_data'] = $this->some_model->some_function();
$this->load->view('someview', $data);

CodeIgniter's url segmentation not working with my JSON

It's my first post in here and I haven't yet figured out to format my post properly yet, but here it goes.
So basically I can only get my code to work if i point directly to a php-file. If I try to call a method within my controller, nothing seems to happen.
My JavaScript:
$(document).ready(function() {
$(".guide_button").click(function(){
var id = $(this).text();
var data = {};
data.id = id;
$.getJSON("/guides/hehelol", data, function(response){
$('#test').text(response.id);
});
return false;
});
});
My markup:
<div id="content_pane">
<ul>
<li>RL</li>
<li>LG</li>
<li>RG</li>
<li>SG</li>
<li>GL</li>
<li>MG</li>
</ul>
</div>
<div class="description">
<h3>Description</h3>
<p id="test">This text area will contain a bit of text about the content on this section</p>
</div>
My Controller:
<?php
class Guides extends CI_Controller {
public function Guides()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
}
public function index()
{
$this->load->view('guides_view');
$title = 'Some title';
}
public function hehelol() //The controller I am desperatly trying to call
{
$id = $_GET['id'];
$arr = array ('id'=>$id);
echo json_encode($arr);
}
}
It might be my controller I have done something wrong with. As it is the code only works if create a hehelol.php file and refer to it directly like this.
$.getJSON("hehelol.php", data, function(response){
$('#test').text(response.id);
});
Anyone who knows what I need to do to make my controller work properly? Help please! :)
i just put your exact code in its entirety in my codeigniter app and it worked for me. Meaning I used this: ...$.getJSON("/guides/hehelol",...
Because you are making a $_GET request, you have to enable query strings.
In your config.php file, make sure this line is set to TRUE:
$config['allow_get_array']= TRUE;

Resources