Reload data without refreshing the page using Ajax and Twig - php

I have a page where a user can write a comment and post it by a simple form.
I'm trying, without success, to do this with ajax using twig.
I can send the ajax request to my controller without problem and the comment is saved in my database.
My issue is to reload a part of my twig template without refreshing the whole page.
The return of my controller:
return $app['twig']->render('#views_suivi/suivi_affaire.html.twig', array('cache' => false,
'auto_reload' => true,
'affaire' => $affaire,
'comments' => $comments
));
$comments countains all the comments of an article. When I send an ajax request, my table comment is updated. Is there a way to update the variable $comments and re-send it to my twig without refreshing the whole page?
Edit: sorry, here's the code of my controller (it just insert a comment in my db)
function addCommentAjax(Application $app, Request $request)
{
$cmt = new CommentaireQueries($app);
$postParams = $app["request"]->request->all();
//var_dump($postParams);
if(isset($postParams['files'])) unset($postParams['files']);
return !empty($postParams) ? $cmt->insertCommentAffaire($app,$postParams) : false;
}
Ajax: 'AjoutCommentaire' is the route to my controller addCommentAjax
$(document).ready(function() {
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type : "POST",
url : "AjoutCommentaire",
data: $(this).serialize(),
success : function() {
alert('success');
}
});
});
});
My form:
<form role="form" method="POST">
<div class="form-group">
<textarea class="summernote" id="contents" rows="10" name="comment"></textarea>
</div>
<input type="hidden" name="phase" value="1" />
<input type="hidden" name="id_affaire" value="{{ affaire.id }}" />
<center><button type="submit" class="btn btn-link btn-block">Envoyer</button></center>
</form>
Basically, I just want to add a comment without refreshing the page.
Thank you !

url in ajax request is not defined properly. You can't just specify route name, you should generate url by route:
$.ajax({
type: "POST",
url: "path('AjoutCommentaire', {})",
...

Related

laravel - target class does not exist error when using ajax to update form with formdata

I am using Laravel with AJAX to send form update request. With other method such as POST request, everything works fine. I managed to do Update method as well but with a different method which is defining it on data field one by one. But since my new form has a lot of input field, I try to serialize it using FormData, but then the error of target class does not exist came out. The error in specific is
Target class [App\Http\Controllers\Form] does not exist
The Controller that I am trying to send to is named FormController, somehow from the error it removes the "Controller" part.
I am not sure what causes it, hope someone would enlighten me on this issue, thank you.
Laravel Blade
<form enctype="multipart/form-data" id="formUpdate">
#csrf
<input type="hidden" name="flowId" id="flowId" value="1">
<input type="hidden" name="formId" id="formId" value="{{ $formData->id }}">
#component('components.form.form-section-a', ['formData' => $formData, 'projectMember' => $projectMember])
#endcomponent
<div class="grid w-full">
<div class="sm:px-1 md:px-0">
<button class="border-green-600 bg-green-600 w-full py-2 rounded mt-3 text-white submitForm" type="submit">Update</button>
</div>
</div>
</form>
AJAX Script
$("#formUpdate").on("submit", function (event) {
event.preventDefault();
var formId = $('#formId').val();
var url = '/Form/' + formId;
var form = this;
formData = new FormData(form);
console.log(Array.from(formData));
$.ajax({
url: url,
type: "PATCH",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: formData,
// dataType:'json',
processData: false,
success: function (response) {
console.log(response);
// return false;
},
});
});
in your button add data-url="route('Form')" or console.log(url); first then check

Make button do Controller method without changing page - Laravel

Hello I'm trying to make a button that once clicked I save the information written in the text field plus the current user logged in ID.
Once clicked just refresh the page (or just do nothing) and save that information in the database.
But my button is doing nothing...
My Controller:
public function addSchool(Request $request)
{
DB::table('schools')->insertGetId([
'id_professor' => Auth::id(),
'escola' => $request->input('escola')
]);
return redirect('/teacher');
}
My zone where i have the textfield and button:
<div class="form-group">
<h3 style="color: #000000" for="escola">Nome da Escola</h3>
<input type="text" id="escola" name="escola" class="form-control">
</div>
<div>
<button type="submit" class="btn btn-danger">Registar Escola</button
</div>
I didn't add any web.php (routes file) here because i don't want it to go any page.
These are my Database Columns
You cant save using a method without a route with only PHP.
If you want to do this, take a look on livewire component, who allow you to use Javascript with PHP.
But you need to few understand Javascript.
I propose you to create a route with a name and just point it to the method
Here in web.php
Route::post('/post-form', [YourController::class, 'addSchool'])->name('addschool');
Then after in your view
<form action="{{route('addschool')}}" method="post">
#csrf
<div class="form-group">
<h3 style="color: #000000" for="escola">Nome da Escola</h3>
<input type="text" id="escola" name="escola" class="form-control"/>
</div>
<div>
<button type="submit" class="btn btn-danger">Registar Escola</button>
</div>
</form>
You can do that by using ajax call from the front-end using on click event attach to button. it will dynamically send the request to your specified controller method and you can display the response(data) in the front-end specified place without page loading
for example take a look at the given code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit").click(function(e){
e.preventDefault();
var escola = $("input[name=escola]").val();
$.ajax({
type:'POST',
url:'{{route('addschool')}}',
data:{name:escola},
success:function(data){
alert(data.success);
//add your login here for the response
}
});
});

laravel api ajax form wont submit

This is my first api project. Can you help me with my code please?
I can't see the problem.
Here is my controller.
public function store(Request $request)
{
//
$valid=Validator::make($request->all(),[
'text'=>'required',
'body'=>'required'
]);
if($valid->fails()){
return response()->json(['message'=>$valid->messages()]);
}else{
$item= Item::create([
'text'=>$request->input('text'),
'body'=>$request->input('body')
]);
return response()->json($item);
}
}
and here is my form.Is there anything wrong in the form?
<form id="form">
<div class="form-group">
<label>Text :</label>
<input type="text" id="text" class="form-control col-sm-4">
</div>
<div class="form-group">
<label>Body :</label>
<textarea id="body" class="form-control col-sm-4"></textarea>
</div>
<div class="form-action">
<input type="submit" class="btn btn-primary" value="submit">
</div>
</form>
and the ajax code between the show function is working but I don't know where the problem is ?.
$('#form').on('submit', function (e) {
e.preventDefault();//prevent the form to submit to file
let text = $('#text').val();
let body = $('#body').val();
addItems(text, body);
});
function addItems(text, body) {
var item = {
text: text,
body: body
};
$.ajax({
method: 'POST',
url: 'http://localhost:8000/api/items',
data: item,
success: function (item) {
alert('done the item number' + item.id + ' has been added!!');
location.reload();
},
error: function () {
alert('error')
}
})
}
Thanks for helping!
if your front-end source separated from back-end source, then add cross-Origin Resource Sharing
package to your laravel project.
if its on your laravel view then add csrf token to meta tag -
<meta name="csrf-token" content="{{ csrf_token() }}">
and send it with your ajax request { _token : document.querySelector('meta[name="csrf-token"]').content}
The problem is that you're sending the form without sending the cross site request forgery token.
Add the directive #csrf to your view
Then send it has Hasan wrote ;)

Controller not getting inputs laravel

Currently I am trying to pass a creation form to a controller. I have the route and the ajax call setup and talking to the route. My problem is that when I use the ajax call the inspect tool for headers is showing my form values correctly but when I go into the controller the request->input doesnt show any values for the form.
Here is my ajax call
$(document).on("click", ".form-submit-btn", function() {
// Get the form id.
var formID = $(this).closest("form").attr("id");
var serializedForm = $(this).closest("form").serialize();
var substringEnd = formID.indexOf("-form");
var route = formID.substr(0, substringEnd).replace("-", "_");
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
// Submit the form.
$.ajax({
method: "POST",
url: "/" + route,
data: {
serializedForm
},
success: function(data) {
alert(data);
}
});
});
Here is my controller
// Create Role
public function create(Request $request)
{
// Get and validate request params
$role = $request->input('role_name');
$active = $request->input('role-active', false);
return $role;
}
And here is my route
Route::post('/create_role', 'RoleController#create');
Am I missing something that is preventing the ajax call from sending the values to the controller
Here is my form also if that helps.
<form id="create-role-form" class="form">
{{ csrf_field() }}
<button class="pull-right right-close-btn">X</button>
<h1>Add Role</h1>
<hr />
<div class="form-group">
<label>Role Name</label>
<input type="text" name="role_name" class="form-control" />
</div>
<div class="form-group">
<input type="checkbox" name="role_active" value="true" checked /> Active
</div>
<div class="form-group">
<button class="btn btn-primary form-control form-submit-btn">Create</button>
</div>
I think problem is this line
data: {serializedForm},
Just change it to
data: serializedForm,
and it should fix the problem.
Problems
I see two problems with your ajax request
Are you sure you're using ES-6 TransPiler because data:{serializedForm}, is ES-6 Syntax http://es6-features.org/#PropertyShorthand
If you're javascript is working fine. You should be able to get it like $request->get('serializedForm')['role_name'] with your existing code.
Hope it helps

Using Ajax Request with PHPUnit and Laravel testing

I am doing tests in Laravel with phpunit. I run a test that inserts that into a textbox and press a button. Then, theres an Ajax Post that sends the info to the server and returns the response. If I return a string has the following code, in the test I should get that string correct?
I have the following controller:
class MyController extends Controller{
public static function createNewComplaintStep_2(){
return "error";
}
}
The route:
Route::post('/createNewComplaint_Step2', 'MyController#createNewComplaintStep_2');
The view with form and ajax method:
<form id="formToSubmit" data-value="createNewComplaint_Step2" class="form-horizontal">
{!! csrf_field() !!}
<div class="form-group">
<label class="col-md-4 control-label">Customer:</label>
<div class="col-md-3">
<input class="form-control" name="customer_name" required>
</div>
</div>
<button type="submit" class="btn btn-success" name="subBTN"\>
</form>
(...)
<script>
$( '#formToSubmit' ).on( 'submit', function(e) {
var href = $(this).data('value');
e.preventDefault();
$.ajax({
type: "POST",
url: href,
data: $(this).serialize(),
success: function( msg ) {
$("#container-fluid").html(msg);
$('.se-pre-con').hide();
}
});
});
</script>
The phpunit test:
$this->visit('/createNew')
->type('NAME', 'customer_name')
->press('subBTN')
->see('error');
Is there something wrong? Because if I run the code, I get error
Failed asserting that the page contains the HTML [error]. Please check the content above
The content above is the view that is above. It seems that the ajax request is not working with phpunit.
Any suggestions??
thanks in advance!
You are working with jquery Ajax, which is a client side scripting language, basically executed in the browser at runtime it cannot be used by Laravel in tests.
Here your Ajax is not even execute so how can you get the string that's why this error is coming.
But you can try some extensions/drivers for laravel that can enable this feature.
Just check out Selenium:-
https://laracasts.com/discuss/channels/testing/has-anyone-tried-laravel-integrated-package-in-laravel-52

Categories