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

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.

Related

Getting response back from server but .html not sowing anything in wordpress ajax

On click I'm sending the id as data and then using query showing the name of user from WordPress database. I'm getting the response back from server but It is not adding when try to use .html(response).May be this is something to do with permission ?Like only admin can use the response?
If that's the case what I can do.
This is the ajax function:
function get_user_id() {
let get_current_user_id =jQuery(this).attr('id');
cur_user = '<?php echo get_current_user_id() ;?>';
var postdata_name = {action: "incoming_user_name_ajax_call",
param_user_to_chat: get_current_user_id,};
jQuery.post(ajaxurl, postdata_name, function (response) {
jQuery("#name-incoming-user").html(response);});
}
This is the function in functions.php
add_action("wp_ajax_incoming_user_name_ajax_call", "incoming_user_name_ajax_call_fn");
add_action("wp_ajax_nopriv_incoming_user_name_ajax_call", "incoming_user_name_ajax_call_fn");
function incoming_user_name_ajax_call_fn() {
global $wpdb;
$param_user_to_chat=isset($_REQUEST['param_user_to_chat'])?trim($_REQUEST['param_user_to_chat']):"";
if (!empty($param_user_to_chat)) {
$posts = $wpdb->get_results("SELECT distinct(display_name) FROM wp_users where
ID=$param_user_to_chat");
echo $posts[0]->display_name;
}
wp_die();}
Posting the HTML as well for everyone who want to know what jQuery(this).attr('id'); is doing. It is getting id "4" or "2" depending on click.
<div id="target">
<div class="user-list-hide" id="user-hide" style="display: block;">
<div id="4"><span>Jason Bradley</span>/div>
<div id="2"><span>John Saddington</span></div>
</div>
</div>
There was issue in your jquery code i.e : the way you were calling your get_user_id() function here you have use wrong selector to get your inner divs . So, to make it work change :
jQuery("#target").on("click", "div", get_user_id);
to
jQuery("#user-hide").on("click", "div", get_user_id);

How to add/include views in Laravel using 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();
]);

Updating the DOM with change in an object (vue.js) - binding not working?

I have the app.js file where gmarkers is an array of objects :
var vm = new Vue({
el: '#lili',
data: {
listings: gmarkers
}
});
In my HTML file :
<div id="lili" >
<div
v-repeat="gmarker : listings"
class="listing listing-list col-sm-12"
style="height:50px;line-height:50px;"
data-cat="#{{gmarker.mycategory}}"
data-id="#{{gmarker.id}}"
>
<span style="color:black;">
<a target="_blank" href="#{{gmarker.listlink}}">
#{{ gmarker.listname }}
</a>
</span>
<span class="tag blue-back" style="margin-left:5px;">
<a target="_blank" href="#{{gmarker.catlink}}">
#{{gmarker.listcat}}
</a>
</span>
<span style="margin-left:20px;color:#bbb;">
#{{gmarker.distance}}km
</span>
</div>
</div>
When loading the page, the DOM loads correctly, displaying the list I'm looking for but when (after an ajax call in js) the gmarkers object changes, the DOM doesn't change.
The new gmarkers is totally created from scratch and containing new objects.
What am I missing ?
It sound like you are wrong about what data is being bound here. You are expecting data: {listings: gmarkers} to do binding between vm.listings and the gmarkers array. This isn't what it does. It copies the gmarkers data into the listings and doesn't listen to gmarkers anymore. See this fiddle for an example of what I think you are doing wrong.
We can fix the above fiddle by setting the vm.listings to the new array of objects after the ajax request.
vm.$set('listings', gmarkers);
You can see this in action in this updated fiddle.
It is actually pretty common to see a blank listings until ajax returns them. Here is some sample code that will call an ajax request when vue is ready and update the listings once it is finished. Note: this exampe uses vue-resources to perform the ajax request. You may not have this. You can always just use jQuery or javascript to perform this.
data: {
listings: []
},
ready: function () {
this.fetchListings();
},
methods: {
fetchListings: function () {
this.$http.get('/your/api/listings', function (response) {
this.$set('listings', response);
});
}
}
This fiddle shows the above code but pay attention to the differences required for the fake ajax request I used.

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);

Resources