URL::to('/') echoed as string (Laravel) - 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.

Related

Laravel 9 pass model object into view

I am trying to pass a model object into view and use it in JS, but I can't make it work. It looks broken and throws a syntax error Uncaught SyntaxError: Unexpected token '&' if I just use the variable.
I tried using compact() but this does not work aswell compact(): Argument #1 must be string or array of strings, App\Models\Quiz given
Here is how I return the view with the object:
$result = Quiz::where('id', $quiz_id)->first();
if (!$result['active'] || $result['hidden_by_admin']) {
return abort(404);
}
$result['classic_questions'] = ClassicQuestion::where('quiz_id', $quiz_id)->with('classic_answers')->get();
$result['quiz_tags'] = QuizHasTags::where('quizzes_id', $quiz_id)->with('quiz_tag')->get();
return view('play_quiz')->with('quiz', $result);
Here is how I want to access it in blade.php:
<script>
const quiz = {{ $quiz }};
console_log(quiz);
</script>
Assign your data into the window global object which will make it
available everywhere and you can access it from your JS file:
<ul>
#foreach ($quiz as $quiz_data)
<li> {{ $quiz_data }} </li>
#endforeach
</ul>
<script type="text/javascript">
window.data = {!! json_encode($quiz) !!};
</script>
<script src="...."></script>
// trying to access the model $data from the view.
$(function() {
var values = window.data;
alert(values);
}
You can also send data to view like this:
In controller:
return view('play_quiz', $result);
In view
foreach($quiz_tags as quiz){
//code
}

Cloning item. The GET method is not supported for this route. Supported methods: POST

I'm trying to clone a model but when I try to I get the error in the title. This is what I'm doing
Button in vue.js
<a class="btn-link-clone action-button" :href="'survey/clone/'+scope.row.id">
<i class="fas fa-clone col-margin"></i>
</a>
Route in web.php
Route::post('survey/clone/{id}', 'SurveyController#cloneSurvey');
CloneSurvey in SurveyController
public function cloneSurvey($id)
{
$survey = Survey::findOrFail($id);
DB::beginTransaction();
$now = Carbon::now();
$activePeriod = Period::whereDate('start_date', '<=', $now)
->whereDate('end_date', '>=', $now)->get();
$clone = new Survey();
$clone->fill($survey->toArray());
$clone->name .= ' Clonado';
$clone->save();
$eval = Evaluation::findOrFail($clone->id);
if (empty($eval)) {
$eval = new Evaluation();
}
$eval->survey_id = $clone->id;
if (!empty($activePeriod)) {
$eval->init_date = $activePeriod->start_date;
$eval->end_date = $activePeriod->end_date;
}
$report = $activePeriod->end_date;
$date = strtotime($report);
$date = strtotime('+ 1 week', $date);
$eval->report_date = $date;
$eval->save();
$questions = $survey->surveyQuestions()->get()->pluck('survey_question_id')->toArray();
if (count($questions) > 0) {
$clone->surveyQuestions()->sync($questions);
}
DB::commit();
return back();
}
What is making this happen?
I've also tried this
button in vue.js
<div class="btn-link-clone action-button"
#click="clone(scope.row)">
<i class="fas fa-clone col-margin"></i>
</div>
method in vue.js
clone(row) {
this.$http.post('survey/clone/' + row.id)
.then(
() => {
this.surveys = this.$page.surveys;
},
(res) => {}
)
},
with the route the same and I get a 419 (unknown status)
You need your Route to use the get method rather than the post method. Like so:
Route::get('survey/clone/{id}', 'SurveyController#cloneSurvey');
When a user clicks on a link, that is almost always a GET request.
EDIT:
Based on the comments, I agree that changes should not be done via a get request anyway. This example should be a POST request.
Your Vue component:
<template>
...
<form>
<button
class="btn-link-clone action-button"
#click.prevent="submit(scope.row.id)"
>
<i class="fas fa-clone col-margin"></i>
</button>
</form>
...
</template>
<script>
export default {
...
methods: {
submit (id) {
// use whatever http request library you choose to execute POST HTTP request.
}
}
...
</script>
Alternatively, you could use #submit.prevent on the form tag instead of the #click.prevent on the button.
Then, as long as scope.row.id was defined on the frontend, you can use:
Route::post('survey/clone/{id}', 'SurveyController#cloneSurvey');
The GET method is not supported for this route. Supported methods: POST
You are making a GET request to a Route that only supports the POST method.
Either your vue app is making a ajax request to your server with missing headers or form incorrect form action.
You may also be passing something like a GET parameter as part of your request
i.e. http://my-app/api/example?var1=asdasdasdas

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

AJAX example in magento

Hello everyone,
I am a newbie to Magento. I want to learn **ajax process in Magento.** Can anyone help me to understand ajax in Magento with one simple example?
Your help will be highly appreciated.
I give you a simple example for you. To work with basic jQuery Ajax in Magento you have work in phtml page and Controller.
Just add the script in phtml page:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery(".like-result").click(function() {
//alert(this.id);
var id = this.id;
//alert(custid);
jQuery(".notify-status").hide();
jQuery(".notify-loader").show();
jQuery.ajax({
type: "POST",
data: 'pid=' + id,
url:'http://192.168.2.3/subhranil-demo/blog/index/likecount',
success:function(response){
if (response) {
jQuery(".notify-loader").hide();
jQuery(".notify-status").show();
jQuery("#un"+id).html(response);
}
}
});
});
});
</script>
In the above script under jQuery.ajax you can also see type, data, url. type is used for sending process like POST or GET; in data, you will send information to the controller; in URL, you can declare the controller path. Here I have a 'blog' module and I write the public function under 'index' controller and I give the function name 'likecount'. Also here my base path is http://192.168.2.3/subhranil-demo/. So I add the link to URL as following structure: http://192.168.2.3/subhranil-demo/blog/index/likecount.
Now I go to 'IndexController.php' in my controller's folder of blog module and open it. Under the class I add the following function:
public function likecountAction()
{
$blogload = Mage::getModel('blog/blog')->load($_POST['pid']);
$newid = $blogload['like']+1;
$data = array('like'=> $newid);
$blogload->addData($data);
try {
$blogload->setId($_POST['pid'])->save();
echo $newid;
} catch (Exception $e){
echo $e->getMessage();
}
}
Here in the Blog Database, I have the fields like pid (as a primary key) and like. the function works like that when you click on 'like-result' class the like increase +1.
My div structure also like that:
<?php
$allCollection=Mage::getModel("blog/blog")->getCollection();
$allCollection->addFieldToFilter('status',1);
if ($allCollection->count() >= 1)
{
$news = array();
?>
<div class="blog clearfix">
<?php
foreach ($allCollection as $news)
{?>
<p class="like-result" id="<?php echo $news->getId(); ?>"> <?php echo $news->getLike(); ?> </p>
<a style="display: none;" class="notify-loader"><img src="http://www.sendhersomething.com/skin/frontend/megatron/default/images/ajax/notify-loader.gif"></a>
<a style="display: none;" class="notify-status"><img src="http://www.sendhersomething.com/skin/frontend/megatron/default/images/ajax/ststus.png"></a>
<?php } ?>
</div>
<?php } ?>
Try this!

add submit to delete comment using ajax , php

Hi, I use a php code to view the all comments to any post from my sql and I want to add a submit button to every comment in order to delete it without refreshing the page, I mean using AJAX i don't know how to write that codes and connect it with html codes i want add submit like this :
<form>
<input type="submit" id="deletecomment">
</form>
and connected it with AJAX and delete.php page to delete the comment (ajax,delete.php)???????
this is my codes
$result = mysql_query ("select * from post_comments WHERE link ='$getlink' order by link asc");
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$link = $row['link'];
$time = $row['time'];
$content = nl2br($row['content']);
$name = ($row['link'] != '') ? '<h3 style="color:blue">'.$row['name'].'</h3>' : $row['name'];
$imge = $row['imge'];
echo '
<div class="commentuserbackground">
<img src="'.$imge.'" width="30px" height="30px">
<div id="comment-'.$id.'" class="username1">'.$name.'</div>
<div class="username2">'.$content.'</div><div class="commenttime"><h4 style="color:#5a5a5a">'.$time.'</h4>
</div></div>';
}
If you already have the jquery lib included in your html, you could do something like this:
# html page
<button data-id="1" class="delete_comment" /> # no need to wrap in form
# At the bottom of the body tag
$(".delete_comment").click(function(e){
e.preventDefault();
var $button = $(this), $comment = $button.parent(), id = $button.data("id");
$.ajax({
type: 'DELETE',
url: "/path/to/comment/" + id,
success: function(){ $comment.remove(); }
});
});

Resources