laravel 5.1 Request::ajax return false - ajax

Hello i use same script for Laravel 4.2 and Laravel 5.1 and problem is for Laravel 4.2 work perfectly, but on Laravel 5.1 i can't understand why it's return bad result
Problem is why I got $request->ajax() false for Laravel 5.1?
routes.php
Route::post('/upload-image', [
'as' => 'upload-image-post',
'uses' => 'PageController#profileImage'
]);
PageController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class PageController extends Controller
{
public function profileImage(Request $request)
{
//here is problem
//result good: (Laravel 4.2 shows true)
//result bad: (Laravel 5.1 shows false)
var_dump($request->ajax());
}
}
upload-image.blade.php (js)
<script>
jQuery(document).ready(function($) {
$('#upload_image').click(function(event) {
$('#image').trigger('click');
});
$('#image').change(function(event) {
/* Act on the event */
$('#imageform').submit();
});
$('#imageform').ajaxForm({
beforeSubmit: function() {
},
success: function(msg) {
},
error: function(request, status, error) {
},
complete: function(xhr) {
if(xhr.status != 401) {
$('#image').val('');
result = xhr.responseText;
result = $.parseJSON(result);
if( !$.isEmptyObject(result.file_base_url) ) {
var img = new Image();
img.onload = function() {
$('#register_profile_photo').attr('src', img.src);
$('#register_profile_photo').attr('alt', result.image_alt);
//spinner.stop();
$('#upload-image-error').text('');
}
img.src = result.file_base_url;
} else {
$('#upload-image-error').text(result.image[0]);
}
}
}
});
});
upload-image.blade.php (html)
<form enctype="multipart/form-data" name='imageform' role="form" id="imageform" method="post" action="{!! route('upload-image-post') !!}">
{!! csrf_field() !!}
<div style="display:none;">
<input type="file" name="image" id="image" placeholder="Please choose your image" >
</div>
</form>
<div class="profile-img">
<img style="float: right" id="register_profile_photo" src="default.png" alt="Default image">
<div style="float: right" class="img-edit">Edit picture</div>
</div>
PS. If you test for laravel 4.2 this code need change from "{!! .. !!}" to "{{ .. }}"

I do not think this problem is caused by Laravel version. Laravel sources show, that ajax() call is propagated to Symfony's request component. And that source changed good 5 years back.
You should trace if X-Requested-With header is sent to your application in both cases. You can also set breakpoint to Symfony\Component\HttpFoundation\Request::isXmlHttpRequest() and see what you have in headers.

Related

How to display data from controller to blade view and how to do routings from remote api? Laravel

WelcomeController
class WelcomeController extends Controller
{
public function ajaxRequestPost(Request $request){
$request->session()->put('data', $request->all());
return redirect('dashboard');
}
public function readSession(Request $request){
$email = $request->session()->get('data');
return $email;
}
}
Routes (Web.php)
return view('welcome');
});
Route::post('/', [App\Http\Controllers\WelcomeController::class, 'ajaxRequestPost'])->name('ajaxRequest.post');
Route::get('/dashboard/read', [App\Http\Controllers\WelcomeController::class]);
Route::post('/dashboard/read', [App\Http\Controllers\WelcomeController::class, 'readSession']);
Route::get('/dashboard', function () {
$email = session()->has('data');
if(!session()->has('data')){
return redirect('/');
}
return view('dashboard', ['name'=> $email]);
});
Route::get('/logout', function () {
session()->forget('data');
return redirect('/');
});
Welcome.blade For popuplogin from remote API
<div class="hidden fixed top-0 right-0 px-6 py-4 sm:block">
<!-- insert at the bottom part of body -->
<script src="provided.js"></script>
<!-- add button to show login window -->
<button id="btnShowLogin" type="button">Login</button>
<form id="login" action="{{ url('/') }}" method="POST">
#csrf
</form>
<script type='application/javascript'>
//create new instance
var api = new API("Givenapikey");
//initialize api
api.init(function(){
//attach click event to the button
$("#btnShowLogin").click(function(){
//show login window
api.login({type:'student'},function(result){
//check result
if(result.error==0){
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrftoken"]').attr('content')
},
url: "{{ route('ajaxRequest.post') }}",
data: { username: result.details.usr_name} ,
type: 'POST',
async: false,
success: function(result){
console.log(result);
document.getElementById('login').submit();
}
});
}
});
});
});
</script>
dahsboard.blade My target blade to display my username and other details. Snippet of the code from dashboard.blade.
<span class="info">{{ $name }}</span>
I don't know if I am doing right. Routing and controllers I think I am doing it wrong especially in routing. The output in dashboard.blade is 1. I don't know why.

Laravel ajax return 404

I'm trying to send data to back-end and i'm getting 404 error with this explanation in network tab:
"message": "",
"exception": "Symfony\\Component\\HttpKernel\\Exception\\NotFoundHttpException",
Route
Route::middleware('verified')->group(function () {
Route::post('/snaptoken/{id}', 'Admin\PayController#token')->name('securepaymentnow');
});
Controller
public function token(Request $request, $id)
{
//Find project
$project = Project::findOrFail($id);
//rest of data
}
Blade
//form and button
<form id="payment-form" method="POST" action="{{route('securepaymentnow', $project->id)}}">
#csrf
<input type="hidden" name="result_type" id="result-type" value="">
<input type="hidden" name="result_data" id="result-data" value="">
</form>
<button class="btn-sm bg-success pay-button" data-id="{{$project->id}}" type="submit"><i class="fas fa-fas fa-shield-alt"></i> Secure Payment</button>
//javascript
$('.pay-button').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
// $(this).attr("disabled", "disabled");
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("/securepaymentnow")}}/'+encodeURI(prdfoId),
type: "POST",
cache: false,
success: function(data) {
var resultType = document.getElementById('result-type');
var resultData = document.getElementById('result-data');
}
});
});
Any idea?
.........................................................................................................................
if you are using url() function, you should use the {{ url('/snaptoken') }}.
But if you want to use the "name" from the "securepaymentnow", use route() function with this example {{ route('securepaymentnow', $theId) }}.
Both should works.
Refer Laravel NamedRoute for details.

Form AJAX submit symfony doesn't work

I don't understand why my AJAX submit doesn't work.
I have two forms in my the controller:
$intervento = new Intervento();
$form = $this->createForm(InterventoType::class, $intervento);
$form->handleRequest($request);
$user = new User();
$form_user = $this->createForm(UserType::class, $user);
$form_user->handleRequest($request);
if ($form_user->isSubmitted() && $form_user->isvalid()) {
$response = new Response();
return $this->json(array('risultato' => ' ok'));
}
if ($form->isSubmitted() && $form->isvalid()) { }
return $this->render('interventi/collaudo.html.twig', array(
'form' => $form->createView(),
'form_utente' => $form_user->createView(),
));
In my twig file I start the form and it works:
{{form_start(form_utente,{'attr':{'id':'form-utente'}})}}
.....
<div class="row">
<div class="input-field col s4">
<input type="submit" class="waves-effect waves-light btn-large" value="Submit">
</div>
</div>
</div>
</div>
{{form_end(form_utente)}}
</div>
In my JavaScript file:
$('#form-utente').submit(function(e) {
e.preventDefault();
var form = $(this);
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert(data['risultato']);
// setTimeout(function() { window.location.href = "#" }, 500);
// setTimeout(function() { $("#form-stufa").click() }, 500);
},
error: function(){
}
});
});
I also have another AJAX call in this JavaScript, but I don't this gives the problem.
The submit button sometimes returns Error 500, sometimes an undefined alert.
I think it doesn't go to submit in the controller but I don't know why.
Can anyone help me?
Use the FOSJsRoutingBundle for js urls. You need expose your routing.

laravel login via ajax

Im trying to do the login in laravel via ajax so I want this function to return only json object in case of errors
the function returns json only when a input (email or password is empty) , but I insert wrong data in bought of theme the function returns a html page with errors include; but I want to return only these errors without html page (I assume that it it dose return response()->back()->withErrors('errors') )
my Js code :
$('#form-login').submit(function(event) {
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
var data = {
email : $('#login_email').val(),
password : $('#login_password').val(),
}
$.ajax({
url: '/login',
type: 'post',
data: data,
success:function(data, textStatus, jqXHR) {
if (jqXHR.getResponseHeader('Content-Type').includes('json')) {
window.location.reload();
}
},
error:function(data) {
// console.log(data['email'])
// console.log(data.email)
if(data.responseJSON.email){
$('#Email-help-block').html(data.responseJSON.email[0])
}else{
$('#Email-help-block').html('')
}
if(data.responseJSON.password){
$('#Password-help-block').html(data.responseJSON.password[0])
}else{
$('#Password-help-block').html('')
}
},
})
});
the function login :
public function login(Request $request)
{
$this->validateLogin($request); // this is where it returns errors
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponse($request);
}
My solution to this problem is:
<body>
<main class="container small">
<div class="middle">
<body>
<main class="container small">
<div class="middle">
<img
<br>
<div class="error valign-wrapper" style=" border: 2px solid red; border-radius: 7px;" hidden>
<h5 class="center-align"> Helaas zijn uw inloggegevens incorrect </h5>
</div>
<form method="POST" action="/api/v1/login" class="login">
{!! csrf_field() !!}
<input type="text" name="email" class="emailaddress" placeholder="Je e-mailadres..." style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP6zwAAAgcBApocMXEAAAAASUVORK5CYII="); cursor: auto;" autocomplete="off">
<input type="password" name="password" class="password" placeholder="Je wachtwoord..." style="background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP6zwAAAgcBApocMXEAAAAASUVORK5CYII="); cursor: auto;" autocomplete="off">
<div class="left">
Wachtwoord vergeten?
← Terug
</div>
<div class="right">
<input type="submit" class="button" value="Log in">
</div>
</form>
</div>
</main>
</body>
#include('footer')
#push('scripts')
<script>
$('form.login').submit(function(e) {
$form = $(this);
e.preventDefault();
$.post(window.location.origin + $form.attr('action'), $form.serialize())
.done(function(data) {
window.location.href = 'account';
})
.fail(function() {
$('.error').show();
});
});
</script>
#endpush
This is html with the error hidden (or you could show it with just ajax) on error. My javascript is pushed to a javascript stack at the bottom.

MethodNotAllowedHttpException in RouteCollection.php line 218 error occured in laravel

I am trying to build the controller that saves the image in my public folder using image intervention. I have used Cropit jquery plugin for image cropping and use ajax. The error " MethodNotAllowedHttpException in RouteCollection.php line 218" occurs.Below are my controller ,routes and view.
CropController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Image;
class CropController extends Controller
{
public function crop(Request $request){
$img = $request->image_data;
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$data = base64_decode($img);
Image::make($data)->save('images/images.jpg');
dd("image saved in images/images.jpg");
}
}
web.php
Route::get('/', function () {
return view('welcome');
});
Route::post('/image-crop',[
'uses'=>'CropController#crop',
'as'=>'image-crop',
]);
welcome.blade.php
<body>
<form method="post">
<input type="hidden" value="{{Session::token()}}" name="_token">
<div class="image-editor">
<input type="file" class="cropit-image-input">
<div class="cropit-preview"></div>
<div class="image-size-label">
Resize image
</div>
<input type="range" class="cropit-image-zoom-input">
<input type="hidden" name="imagedata" class="hidden-image-data" />
<button type="submit">Submit</button>
</div>
</form>
<script>
var url1="{{route('image-crop')}}";
$(function() {
$('.image-editor').cropit();
$('form').submit(function() {
//event.preventDefault();
// Move cropped image data to hidden input
var imageData = $('.image-editor').cropit('export');
$('.hidden-image-data').val(imageData);
// Print HTTP request params
var formValue = $(this).serialize();
$.ajax({
type:'post',
data:formValue,
url: '/image-crop',
success: function(data){
$('#result-data').text('New file in: images/'+data);
$('#crop').show();
}
})
.done(function(){
window.location.href=""+'/image-crop';
});
return true;
});
});
</script>
</body>
How to solve that error ?
Thank you
Hey Try to add this metatag on your layout
<meta name="csrf-token" content="{{ csrf_token() }}">
Also in your ajax request add this $.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Let me know if it works!.
https://laravel.com/docs/5.1/routing#csrf-x-csrf-token

Resources