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
Related
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
}
});
});
I'm trying to make AJAX request with button in Laravel 5.5. Console returns me POST: 500 (Internal Server Error).
My Javascript code here:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#insertForm').on('submit', function(e){
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr('action');
var post = $(this).attr('method');
$.ajax({
type: post,
url: url,
data: data,
dataType: 'json',
success:function(data)
{
console.log(data)
}
})
})
</script>
My HTML form code:
<form action="{{ URL::to('add') }}" class="translation-form" method="POST" id="insertForm">
<div class="language-area">
<textarea class="form-control wow fadeIn" data-wow-duration="0.5s" name="words" id="lang-input" rows="10"></textarea>
</div>
<p class="upload-info wow fadeInDown" data-wow-duration="0.5s" data-wow-delay="0.3s">
Add words from file
<input type="file" name="file-1" id="file-1" class="inputfile inputfile-1" data-multiple-caption="{count} files selected" multiple />
<label for="file-1"><span>"doc" or "docx"</span></label>
</p>
<div class="clearfix"></div>
<div class="text-center translate-option">
<button type="submit" class="btn btn-green btn-instant-translate wow fadeIn" data-wow-duration="0.5s">
Add
</button>
</div>
</form>
My AjaxController:
class AjaxController extends Controller
{
public function store(Request $request)
{
if($request->$ajax())
{
return "True request!";
}
}
}
And my route:
Route::post('/add', ['uses'=>'AjaxController#store', 'as'=>'ajaxAdd']);
Why does such an error occur? Ajax worked when I tried to just output the data in the console without usage requests to AjaxController.
the server responds with 500 because some exceptions are raised during the ajax call. i guess its because of the code in controller, the controller code should be like this
if($request->ajax())
{
return "True request!";
}
Edit: to respond to ajax request, you can use response objects and http response codes, instead of returning plain text, so that you can know the exact status of ajax call,
Doc link to laravel responses
Link to Http Response Codes
You got an rogue $ in $request->$ajax()
class AjaxController extends Controller
{
public function store(Request $request)
{
if($request->ajax())
{
return "True request!";
}
}
}
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
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', {})",
...
Greetings from some noob trying to learn JQuery,
I am attempting to make it when you type something in a box below a div layer it reloads that layer upon submission of the form with a php get of the text box in the form. Expected behavior is it would reload that box, actual behavior is it don't do anything. Can someone help me out here.... Below is the code.
<div id="currentwxdiv">This is where the new stuff happens
</div>
<form name="changewx" action="/">
<input type="text" id="city">
<input type="submit" name="submit" class="button" id="submit_btn" value="New City" />
</form>
<script>
/* attach a submit handler to the form */
$('form[name="changewx"]').submit(function(event) {
/* get some values from elements on the page: */
var $form = $( this ),
city = $('#city').val()
/* Send the data using post and put the results in a div */
$('#currentwxdiv').load('http://api.mesodiscussion.com/?location=' + city);
return false;
});
</script>
Its giving the Javascript Console Error Error....
"XMLHttpRequest cannot load http://api.mesodiscussion.com/?location=goodjob. Origin http://weatherofoss.com is not allowed by Access-Control-Allow-Origin."
You are using POST method? is impossible to post to an external url because with ajax, the url fails the "Same Origin POlice".
If you use GET method, is possible to do that.
Another solution is to make a proxy. A little script that recive the params and then... using CURL or another thing you have to post to the external URL... finally, you jquery have to do the post thing to the proxy:
For example:
$.ajax({
url: '/proxy.php?location=' + city,
success: function(data) {
$('#currentwxdiv').html(data);
}
});
I do it so:
<div id="currentwxdiv">This is where the new stuff happens
</div>
<form name="changewx" action="/">
<input type="text" id="city">
</form>
<script>
$('#city').keyup(function() {
var city = $('#city').val()
$.ajax({
url: 'http://api.mesodiscussion.com/?location=' + city,
success: function(data) {
$('#currentwxdiv').html(data);
}
});
});
</script>
To help you out, i need to test this.
What's the url address of your html code working ?
http://api.mesodiscussion.com/?location= doesn't work... only list the directory content... maybe that's de problem?
Greatings.