I have a special problem.
I am making an Ajax request to get data from the db without updating.
The response I get should be outputted in a advanced way like this:
#foreach ($tasks as $task)
<div class="pr-1">
<div onclick="openComponent('modal-task', {{ $task->id }});setGlobalIndex({{ $task->id }});" title="{{ $task->title }}" class="calendar-task hover:opacity-75 cursor-pointer" style="background-color: #{{ $task->color }};">#{{ $task->id }} {{ ucfirst(substr($task->title, 0, 23)) }}</div>
</div>
<div id="modal-task_{{ $task->id }}" class="hidden">
<div class="display">
<div class="top">
<div class="title">Opgave #{{ $task->id }} <div class="inline-block text-blue-600 underline text-sm">Se hele opgaven</div>
</div>
<div onclick="closeComponent('modal-task', {{ $task->id }})" class="close-button"><i class="fas fa-times-circle text-gray-700"></i>
</div>
</div>
#include('component.task')
</div>
#endforeach
Right now I get the correct response from the Ajax request.
color: "e53e3e"
company_id: 1
created_date: "2020-11-13"
created_time: "00:00:00"
description: null
id: 8
status_1: null
status_2: null
status_3: null
title: "Overskrift"
But how do I output it like that, with the include also and it should appear many times (its a calendar system that gets tasks from each days)
The Ajax request POST 2 dates (from and to) till a laravel controller which returns the tasks that have the date in between.
<script>
var datePeriodRow = "<?php echo $datePeriodRow; ?>";
var _token = $('input[name=_token]').val();
$.ajax({
url: "/task/get",
type:"POST",
data:{
datePeriodRow:datePeriodRow,
_token: _token
},
success:function(response){
if(response) {
console.log(response);
}
},
});
</script>
What you can do in your "/task/get" endpoint method is to return a view that returns a rendered html. then set the rendered response with javascript in a div element instead of that foreach loop.
So place the foreach code part in an include/partial like partial/tasks.blade.php and in your endpoint method:
/** route: /task/get **/
public function yourTasksMethod(){
//your code that retrieves your tasks
return view('partial.tasks')->with('tasks', $tasks)->render();
}
Keep in mind to clear/empty the div before you make another request to the task/get endpoint.
Related
I'm learning about Ajax and Symfony. Since I made a loop to show all rings from database, I would like to put checkbox on each ring and, want to show only selected ring on the top. So I'm trying to use Ajax so that I don't need to refresh the page. I simply put alert box to check whether it is working before making php controller, but seems it's not working
this is my twig file
'''
{% for ring in rings %}
<div class="row g-0 mb-5">
<div class="text-center ">
<p>Ring Name: {{ ring.ring_name }}</p>
<p>Ring Type: {{ ring.ring_type }}</p>
<p>Ring Shape: {{ ring.ring_shape }}</p>
<p>Ring Size: {{ ring.size }}</p>
<p>Price: {{ ring.price }}</p>
<input type="checkbox" id="select_ring" name="select_ring" value=ring.id >
</div>
<br>
<div class="text-center">
detail
Update Ring
</div>
</div>
{% endfor %}
'''
this is Ajax inside the twig
'''
$('#myCheckbox').click(function() {
var checked = $(this).is(':checked');
$.ajax({
type: "POST",
url: myUrl,
data: { checked : checked },
success: function(data) {
alert('it worked');
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
});
'''
What you want to do is just a front end manipulation, you don't need to use ajax for it.
Just define ID to your rings (based on ring id for exemple) and set all your rings as hidden at start.
Then in js/jquery (BTW forget about Jquery, it's lame), just set the selected element visible on click.
Don't forget to put the others element to hidden every time you click on a ring, otherwise the previous rings will stay visible.
I am beginner with Ajax. I try refresh a table when user select an option in form-select filter. I use Symfony and Twig.
I get the new datas in the Json format in my console when i select a new filter, but the table does'nt show with the new datas. I failed to find the solution when my request ajax is success.
My Select filter :
{{ form_start(form) }}
<div class="container-fluid">
<div class="row">
<div class="col-fluid">
{{ form_row(form.isAttending) }}
</div>
<button type="submit" class="btn btn-outline-success mb-2">{{ button_label|default('Envoyer') }}</button>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col-1-fluid">
{{ form_row(form.active) }}
</div>
</div>
</div>
{{ form_end(form) }}
In my Controller :
/**
* #Route("/ajax", methods={"GET", "POST"})
*/
public function testAjax(Request $request)
{
if (!$request->isXmlHttpRequest()) {
return new JsonResponse(array(
'status' => 'Error',
'message' => 'Error'),
400);
}
if($request->request->has('isAttending')) {
$preSelect = $request->request->get('isAttending');
return new JsonResponse(
$this->queryFollowingFilter($preSelect),
200);
}
}
In my Template :
<script>
$(document).on('change', '#campagnes_tel_isAttending', function () {
$('#flash').remove();
let $field = $(this)
let $preselect = $('#campagnes_tel_isAttending')
let $form = $field.closest('form')
let data = {}
data['isAttending'] = $field.val()
console.log(data)
$.ajax({
type: "POST",
url: "/campagnestel/ajax",
data: data,
dataType: "json",
success: function(response) {
console.log(response);
}
});
});
</script>
Any ideas ?
According to your question and comments your problem is not Symfony, not Ajax and also not Twig related. You get the correct data and you just do not know how to manipulate the DOM. DOM manipulation is a basic capability of JavaScript.
Here you can learn how to manipulate the DOM: https://www.w3schools.com/js/js_htmldom.asp
And here you can learn how to easily can manipulate it with jQuery which you are obviously using: https://www.w3schools.com/js/js_jquery_dom.asp
Sample:
$('#my-table').append(response.myWhatever);
I'm trying to implement a AJAX request in my laravel project that load html content when clicking on a specific item of a list.
My view :
#for($i=0; $i < count($extras); $i++)
<li data-cardid="{{$i+1}}" class="showCard">{{ $extras[$i]->type }} Extra: {{ $professional[$i] }}</li>
#endfor
then further :
<div style="display:flex; flex-direction:column; width:60%; align-items:center" id="card-container">
<!-- THE CONTAINER -->
</div>
My script:
<script type="text/javascript">
var url = "{{route('getCard')}}"
</script>
$(".showCard").click(function(){
var idCard = $(this).data('cardid');
$.ajax({
url: url,
type: "GET",
data: {id: idCard},
success: function(card){
$card = $(card)
$("#card-container").fadeOut().html($card).fadeIn();
}
});
});
My controller :
public function getCard(Request $request){
$cardId = $request->['id'];
$extra = DB::table('extras')->where('id', $cardId );
return view('user.card-content', ['extra' => $extra]);
}
Here is the card-content view :
<img src="{{ asset('../resources/assets/images/extra-background.png') }}" class="background-image" style="width:50%;"/>
<ul>
<li class="title">KEY DETAILS</li>
<li>SALARY: {{ $extra->salary }} CHF/Hr</li>
<li>BENEFITS: {{ $extra->benefits }}</li>
<li>LANG: FRENCH</li>
<li>TIME: {{ $extra->date.' at '.$extra->date_time }}</li>
</ul>
<p>
DESCRIPTION : {{ $extra->requirements }}
</p>
APPLY
Unfortunately i have this error :
500 (Internal Server Error)
What did i do wrong ?
In my page show.html.twig i have this block
<div class="col-md-9 col-sm-9 user-wrapper">
<div class="description">
{{ render(controller('FLYBookingsBundle:Post:new')) }}
</div>
</div>
As you can see there is a render that render the page new.html.twig, i want to render the page product << {{ render(controller('FLYBookingsBundle:Post:product')) }} >> in the div description only if the user click on the link My Product List . how do i do that with twig ?
Here is the solution I used to "pop-up" a form for sending an e-mail to an entity based on a button appearing with that entity.
You will need to install jquery if not already installed. There are many possible ways to do this. Use your pal Google & "symfony install jquery" to find one. You may also want to find a good javascript debugger for your browser. I use the Firebug add-on in Firefox.
Template with link (edited for brevity). The returned e-mail form appears in <div id="dialog"></div>:
<div id="dialog"></div>
{% for opp in opportunities %}
<div class="row">
<div class="col-md-9">
<ul class="list-unstyled">
...
<li><a href="#" value="{{ opp.id }}" id="emailOrganization" class="btn btn-xs btn-info" >E-mail {{ opp.orgName }}</a>
</ul>
</div>
</div>
{% endfor %}
Javascript:
$(document).on("click", "#emailOrganization", function () {
var where = $(location).attr('pathname');
var id = $(this).attr("value");
//replaces URI ending in 'search' with 'oppForm/' + id (of organization)
var url = where.replace('search', 'oppForm/' + id);
$.get(url, function (data) {
//creates dialog box containing e-mail form
$('#dialog').dialog();
$('#dialog').dialog({
modal: true,
buttons: [
{
text: "Send",
id: "send",
class: "btn-xs btn-primary",
click: function () {
var formData = $("form").serialize();
$.post(url, formData, function (response) {
if (response.indexOf("Email sent") >= 0) {
$("#send").hide();
}
$('#dialog').html(response);
})
}
},
{
text: 'Close',
id: "close",
class: "btn-xs btn-primary",
click: function () {
$(this).dialog("close");
}
}
],
resizable: true,
});
$('#dialog').dialog("widget").find(".ui-dialog-titlebar").hide();
$('#dialog').html(data);
});
});
Controller (edited for brevity)
/**
* #Route("/oppForm/{id}", name="opp_form")
* #Template("default/oppEmail.html.twig")
*/
public function oppFormAction(Request $request, $id)
{
...
$form = $this->createForm(new OpportunityEmailType($oppName, $orgName, $email, $id));
$form->handleRequest($request);
if ($request->getMethod() == 'POST') {
if ($form->isValid()) {
...
}
$response = new Response("Email sent: " . count($to));
return $response;
}
}
return [
'form' => $form->createView(),
'id' => $id,
];
}
Template:
<form role="form" action="{{ path('opp_form', {'id': id}) }}" method="post" name="opp_email">
{# hidden submit button allows functional test; also tested with codeception #}
<div style="visibility: hidden;"><input type="submit" value="Mail"></div>
{{ form_widget(form._token) }}
{{ form_row(form.id) }}
{{ form_row(form.to) }}
{{ form_row(form.from) }}
{{ form_row(form.subject) }}
{{ form_row(form.message) }}
</form>
I'm trying to use ajax to find the next page on my pagination. However it keeps bringing in the whole body. I've taken a print screen to show the problem.
I'm not an expert on ajax show would appreciate some help as to how I can rectify this issue?
My code is below:
public function viewall()
{
$data["projects"] = $projects = Auth::user()->projects()->paginate(3);
if(Request::ajax())
{
$html = View::make('projects.viewall', $data)->render();
return Response::json(array('html' => $html));
}
return View::make('projects.viewall')->with('projects', $projects);
}
Js/js.js
$(".pagination a").click(function()
{
var myurl = $(this).attr('href');
$.ajax(
{
url: myurl,
type: "get",
datatype: "html",
beforeSend: function()
{
$('#ajax-loading').show();
}
})
.done(function(data)
{
$('#ajax-loading').hide();
$("#projects").empty().html(data.html);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
viewall.blade.php
#extends("layout")
#section("content")
<div class="container">
<h4>Your Projects</h4>
<div id="ajax-loading" class="alert alert-warning" style="display: none;">
<strong>Loading...</strong>
</div>
#if (Auth::check())
#if (count($projects) > 0)
#foreach ($projects as $project)
<div class="one-third column" id="projects">
{{ $project->project_name }}
{{ $project->project_brief }}
{{ date("d-m-Y", strtotime($project->start_day)) }}
</div>
#endforeach
#else
<h5 class="errorslist">You have no projects click <a class="errorslist" href="/project/create">here to create a project</a></h5>
#endif
#endif
<div class="sixteen columns">
{{ $projects->links() }}
</div>
</div>
#stop
This line:
$("#projects").empty().html(data.html);
will fill the #project up with your returned html which you created here:
$html = View::make('projects.viewall', $data)->render();
So,you just need to change projects.viewall with only 'partial view' that you want to load.
Probably you don't need to extends your main layout.
But you render a view here:
$html = View::make('projects.viewall', $data)->render();
so html is created by Laravel and then you insert it as html into the #projects domElement.
I experienced this kind of problem, just run
dd( json_decode( json_encode( Products::paginate(5) ), true) );
and can get a hint :)
I have read a solution about this here:
http://www.tagipuru.xyz/2016/05/17/displaying-data-using-laravel-pagination-in-the-html-table-without-page-reload/