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);
Related
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.
I am trying to take amount from the html tags and store the amount into database but the about here
ajax code is not working and data is not stored in the database. And how to know if ajax code is redirected it's control to the laravel controller
#include('layouts.students.header')
<meta name="csrf-token" content="{{csrf_token()}}">
<body>
<div class="col">
<p class="text-right" style="font-size: 18px;">
<i class="fa fa-rupee"></i><strong
class="amount">299</strong>
</p>
</div>
<div class="form-group text-right">
<button class="btn btn-warning btn-block btn-lg
buy_now">Proceed</button>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('button').click(function(event){
e.preventDefault();
var amount = $('.amount').html();
$.ajax({
url : '{{route('razorpay')}}',
method : 'POST',
dataType : 'jason',
data : {amount :amount * 100},
success : function (Response) {
console.log(Response);
}
});
});
});
</script>
</body>
</html>
controller :
public function dopayment(Request $request)
{
$data = $request->all();
$result = Payment::insert($data);
echo "inserted";
}
In ajax method can you use dataType : 'json', instead of jason
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>
Thanks guys for looking into my question. I have this form that I use ajax to submit to the mysql database using laravel. I'm trying to pull the most recent entry which would be the user's submission. I am error free, however I'm getting the most recent before the user submitted form. I wrote the code in the IndexController. Maybe i should use Jquery/Java? Here is what I have:
Route:
Route::resource('/', 'IndexController');
IndexController:
public function index()
{
$recent = Contact::orderby('created_at', 'desc')->first();
return view('index', compact('recent'));
}
Html:
<div class ="row">
<div class ="col-lg-12 contact">
<div id = "ctn-box" class = "row pad-med">
{!!Form::open(array('url' => 'contacts', 'class' => 'contacting')) !!}
<h1 class = "txtc">CONTACTO</h1>
<div class = "form-group col-xs-3">
{!!Form::label('name', 'Nombre:')!!}
{!!Form::text('name', null, ['class'=> 'form-control area'])!!}
</div>
<div class = "form-group col-xs-3">
{!!Form::label('email', 'Email:')!!}
{!!Form::email('email', null, ['class'=> 'form-control area', 'placeholder' => 'example#gmail.com'])!!}
</div>
<div class = "form-group col-xs-3">
{!!Form::label('phone', 'Número de Teléfono:')!!}
{!!Form::text('phone', null, ['class'=> 'form-control area', 'placeholder' => '657-084-052'])!!}
</div>
<div class = "form-group col-xs-3">
{!!Form::submit('Contacto', ['class'=> 'btn btn-danger outline form-control contact', 'id' => 'fuck'])!!}
</div>
{!! Form::close() !!}
<div id = "thankCtn" class = "txtc">
<h1>Muchas Gracias {{$recent->name}}!</h1>
<p>Siguemos en contacto. Mientras tanto, visítanos en nuestro officina abajo.</p>
</div>
</div>
<div class = 'contact-info'>
<iframe class = "googimg" frameborder="0" scrolling="no" src="https://maps.google.com/maps?hl=en&q=Passatge hort dels velluters, 5&ie=UTF8&t=roadmap&z=15&iwloc=B&output=embed"><div><small>embedgooglemaps.com</small></div><div><small>multihoster premium</small></div></iframe>
<div class = "address txtc">
<h1 class = "contacts">Passatge Hort dels Velluters<br> 5, 08008 Barcelona</h1>
<h2 class = "contacts">657-084-052</h2>
</div>
</div>
</div>
</div>
Ajax:
//INDEX CONTACT SUBMISSION//
$('.contacting').on('submit', function(e) {
var base_url = 'http://rem-edu-es.eu1.frbit.net/';
e.preventDefault();
var data = $(this).serialize();
$.ajax({
type: "POST",
url: base_url + "contacts",
data: data,
success: function (data) {
$('.contacting').css('opacity', '0');
$('.contacting').animate({
top: '50px'
}, 100, function(){
$('#thankCtn').fadeIn(500);
$('#thankCtn').css('top', '-100px');
});
}
});
});
Before suggesting anything, I should tell you that there could be a little issue with the site. I clicked the "Contact" button without filling the fields. Guess what? I got a response: "Muchas Gracias New Guy..." I guess the last person used "New Guy" as his name. Sounds insecure?!
Now, to my answer, I'll suggest you do it with jQuery, in the success callback of $.ajax(). Something like this:
IndexController
public function index()
{
$recent = Contact::orderby('created_at', 'desc')->first();
return json_encode(compact('recent')); // Returning view(...) means the ajax call will receive HTML page content
}
HTML
<div id = "thankCtn" class = "txtc">
<h1>Muchas Gracias <span id = "newGuy"></span>!</h1>
<p>Siguemos en contacto. Mientras tanto, visítanos en nuestro officina abajo.</p>
</div>
jQuery
success: function (res) { // note that I'm changing "data" to "res". It is the result of the ajax call
$('.contacting').css('opacity', '0');
$('.contacting').animate({
top: '50px'
}, 100, function(){
$('#newGuy').text(res.name);
$('#thankCtn').fadeIn(500);
$('#thankCtn').css('top', '-100px');
});
}
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/