Hi I was wondering why my Laravel 5 Ajax request doesnt work
<input type="hidden" class="_token" value="{{Session::token()}}" name="_token">
$.ajax({
url: "{{ route('groups.store') }}",
method: 'post',
data: {
name: 'name',
_token: $("input[name=_token]").val()
},
success: function(response) {
if (response.success == true) {
// remove error message
alert('success');
}
},
error: function(xhr) {
alert('error');
}
});
on the Route File I put:
Route::post('search/store', [
'uses' => 'SearchController#store',
'as' => 'groups.store'
]);
and on my controller I put:
public function store(Request $request)
{
return response()->json(['success' => true]);
}
then I keep getting error 404 while I simply wants to display the json result from my controller much help appreciated thx
btw heres the full routes.php
<?php
carbon()->setLocale('id');
Route::get('/', function () {
return view('welcome');
});
Route::post('search/SearchController','SearchController#postMapSearchResult');
Route::get('/getRequest', function(){
if(Request::ajax()){
return 'getRequest has loaded';
}
});
Route::group(['middleware' => ['web']], function () {
// Backend Area
Route::controller('login','Backend\LoginController');
Route::get('admin-cp' , function(){
return redirect('login');
});
if(request()->segment(1) == webarq()->backendUrl)
{
include __DIR__.'/backendRoutes.php';
}
//
// Frontend Area
Route::get('account/confirmation/{token}', 'Auth\AuthController#activateUser')->name('user.activate');
Route::controller('faq','FaqController');
Route::controller('blog','BlogController');
Route::controller('social','SocialController');
Route::controller('account','AccountController');
Route::controller('iklan','IklanController');
Route::controller('search','SearchController');
Route::controller('/','HomeController');
Route::post('search/store', [
'uses' => 'SearchController#store',
'as' => 'groups.store'
]);
});
Put the route outside of middleware group
Below is a code which work perfect for me.
var count = 100;
$('#ID').on("click", ".CLASS",function() {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: 'URL',
type: 'POST',
data: {_token: CSRF_TOKEN,id:count},
dataType: 'html',
success: function (data) {
alert('success');
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
});
Related
js:
$.ajax({
url: '/site/updateuserdata',
method: 'POST',
//async: true,
//cache:false,
data: {
'type': 'sort'
//val: val
//csrfParam: csrfToken
},
dataType: 'text',
error: function(jqXHR, textStatus, errorThrown) {
alert('error by ajax');
},
success: function(data, status, jqXHR) {
alert('success by ajax');
}
});
Controller:
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'rules' => [
[
'actions' => ['updateuserdata'],
'allow' => true,
// 'roles' => ['*'],
],
],
],
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'updateuserdata' => ['post'],
],
],
];
}
public function actionUpdateuserdata()
{
/*if (Yii::$app->request->isAjax) {
$message = 'Ваше сообщение успешно отправлено';
Yii::$app->response->format = Response::FORMAT_JSON;
$response = [
'success' => true,
'message' => $message
];
return $response;
}*/
$f = fopen('testajax.txt','a+');
fwrite($f, 'ajax: '.(isset($_POST['type'])?$_POST['type']:'error'));
fclose($f);
if(isset($_POST['type']))
return $_POST['type'];
else return 'error1';
// return Yii::$app->getResponse()->redirect(Yii::$app->request->referrer, 302, FALSE);
}
yii.js:
function initRedirectHandler() {
// handle AJAX redirection
$(document).ajaxComplete(function (event, xhr) {
var url = xhr && xhr.getResponseHeader('X-Redirect');
alert(url); //my code
if (url) {
window.location.assign(url);
}
});
}
I see first alert(ajax error) "error by ajax" and then alert(yii.js) "..../site/updateuserdata...", why ajax error? File testajax.txt not create.
I tried comment 'updateuserdata' => ['post'], and get error too.
Updated.
Also, tried:
public function beforeAction($action)
{
if ($action->id == 'updateuserdata') {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
}
and uncomment csrf parameters in ajax.
And 'error' return status 302(jqXHR.status).
dddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd
I find problem, it's stupid problem:
url: '/mag/updateuserdata/',
i have in 'urlManager':
'suffix' => '/',
i think this added for all, but not.....
Cause you commented
//csrfParam: csrfToken
from your ajax js file you have 400 http status code in your ajax.
So you can solve it in two way:
one: disable csrf validation by adding
$this->enableCsrfValidation = false;
in your actionUpdateuserdata method.
two: add csrf token and csrf param to your ajax.
print this code in your js, where you commented it.
Yii::$app->request->csrfParam . ':' . Yii::$app->request->csrfToken
then your request sent successfully and if you have other error you must check your code.
I created a custom post type called 'visitor'. and I have an input in the front end. when the user saves input, I want to grab that data and post it as 'title' in my 'visitor' post type.
in functions.php-
$secureInfo= array(
'site_url' => get_site_url(),
'nonce' => wp_create_nonce("wp_rest")
);
wp_localize_script( "main-js", "data", $secureInfo);
in main.js-
sendUserInfo(){
var grabbingInfo = {
"title" : this.alertBoxInput.val() //my targeted input
}
$.ajax({
beforeSend: (xhr) => {
xhr.setRequestHeader("X-WP-Nonce", data.nonce);
},
url: data.site_url + "/wp-json/wp/v2/visitor", //custom post type
data: grabbingInfo,
type: "POST",
success: (res) => {
console.log("success");
console.log(res);
},
error: (res) => {
console.log("sorry");
console.log(res);
}
});
}
however, this code works for logged in user and says unauthorized for public users. but I don't care if a user is logged in or not. any suggestion?
I am working in laravel 5. and using blade and ajax for upload image.
Every thing was working fine unless I inserted validation code in store function inside controller. Getting server error:
POST http://localhost:8000/imgC 500 (Internal Server Error)
I guess there is something wrong with url inside ajax or in routes, I am using Restfull Controller.
image.blade.php
{{Form::open(array('url' => 'imgC', 'method' => 'post','files'=>true, 'id'=>'upload_form'))}}
Title: {{Form::text('title')}}
Image: {{Form::file('image')}}
{{Form::submit('submit',['id' => 'btnAddProduct'])}}
{{Form::close()}}
ImageController.php:
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|max:255',
]);
if ($validator->fails()) {
return "error";
}
$destinationpath = public_path() . '/img/';
$image=$request->input('image');
$filename=$request->file('image')->getClientOriginalName();
$request->file('image')->move( $destinationpath,$filename );
$img= new Image;
$img->name= $request->input('title');
$img->picture_path=$filename;
$saveflag=$img->save();
if($saveflag){
return Response::json(['success' => $saveflag, 'file' => asset($destinationpath.$filename)]);
}
}
AJAX function:
$(document).ready(function() {
$('#upload_form').submit(function (event) {
event.preventDefault();
$.ajax({
url: '/imgC',
data: new FormData($(this)[0]),
type: "POST",
processData: false,
contentType: false
}).done(function (response) {
console.log(response);
$("#success").show();
setTimeout(function() { $("#success").hide(); }, 5000);
});
});
});
route.php:
Route::resource('imgC', 'ImageController');
What am I doing wrong here?
I looked into the server log files and figured it out.
There was error with validation after adding Use Validator; in Image controller, problem solved
How do I properly call a Laravel Route or Controller in my Ajax?
An error appears and says:
Route [product/create] not defined. (View:
C:\xampp\htdocs\laravel\resources\views\jsBlade\logoInput.blade.php)
(View:
C:\xampp\htdocs\laravel\resources\views\jsBlade\logoInput.blade.php)
My Routes look like this:
# Middleware group if user is successfully logged in
Route::group(['middleware' => 'auth'], function ()
{
Route::get('/home', ['as' => 'home', 'uses' => 'PageController#showHome']);
# Product group
Route::group(['prefix' => 'product'], function ()
{
Route::get('/', ['as' => 'indexProduct', 'uses' => 'ProductController#indexProduct']);
Route::get('new', ['as' => 'newProduct', 'uses' => 'ProductController#newProduct']);
Route::get('show/{productID}', ['as' => 'showProduct', 'uses' => 'ProductController#showProduct']);
Route::get('edit/{productID}', ['as' => 'editProduct', 'uses' => 'ProductController#editProduct']);
Route::post('create', ['as' => 'createProduct', 'uses' => 'ProductController#createProduct']);
Route::post('update', ['as' => 'updateProduct', 'uses' => 'ProductController#updateProduct']);
Route::delete('destroy', ['as' => 'destroyProduct', 'uses' => 'ProductController#destroyProduct']);
});
});
My Ajax:
$("#input-logo").fileinput({
uploadUrl: '{{route("product/create")}}',
type: 'POST',
allowedFileExtensions: ["jpg", "png", "gif", "jpeg"],
allowedFileTypes: ['image'],
headers: {
'X-CSRF-Token': $('#_token').val(),
}
}).on('filepreupload', function() {
$('#kv-success-box').html('');
}).on('fileuploaded', function(event, data) {
$('#kv-success-box').append(data.response.link);
$('#kv-success-modal').modal('show');
});
</script>
Controller
<?php
namespace App\Http\Controllers;
use Input;
use App\Product;
use App\Companies;
use App\Http\Controllers\Controller;
class ProductController extends Controller
{
public function createProduct()
{
$data = Input::all();
$product = new Product;
$product->fill($data);
if($product->save())
{
return redirect()->route('root')->with('message','Success');;
}
}
}
Firefox gives this error message:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of
the JSON data.
Change this part
uploadUrl: '{{route("product/create")}}',
to this
uploadUrl: '{{url("product/create")}}',
and add a csrf token to your header in ajax
headers: {
'X-CSRF-Token': '{{ csrf_token() }}',
},
Just Ajax to the URL of the route like this:
This is my route:
Route::post('users/send-file-temp',['uses'=>'UsersController#postSendFileTemp']);
and here is my ajax call:
$.ajax({
url: '/users/send-file-temp',
});
Ajax will send the request to /users/send-file-temp and Laravel will recognize the route and direct it to the corresponding controller.
Take not of your ajax method type and your Route method type
Example below
My Ajax code
$('#sendMsg').click(function(e){
e.preventDefault();
$.ajax({
url: '{{url("R_E/users/sendMSG")}}',
data: $("#form-signin").serialize(),
type: "POST",
headers: {
'X-CSRF-Token': '{{ csrf_token() }}',
},
success: function(data){
alert("okay");
},
error: function(){
alert("failure From php side!!! ");
}
});
});
My route Code
Route::post('/users/sendMSG', 'RE\MainController#sendMSG');
instead of {{route("product/create")}} ,
following one worked for me in Laravel 8 :
!{route("product/create")}!
I'm getting 422 Unprocessable Entity error even when I'm submitting my form via Ajax.
My javascript file
$.ajaxSetup({
headers: {
'X-XSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.keywords-plan-form').submit(function(event) {
event.preventDefault();
$.ajax({
url: '/laravel/public/keywordsplans',
type: 'POST',
data: $(this).serialize(),
success: function(data){
alert(data);
// success logic
},
error: function(data){
// Error...
var errors = $.parseJSON(data.responseText);
console.log(errors);
$.each(errors, function(index, value) {
});
}
});
});
as you can see I added X-XSRF-TOKEN****strong text to ajax header.
This is my '' tag
<meta name="csrf-token" content="{{ csrf_token() }}">
my Form Data in chrome debuger
_token:5j6DGhhTytbIRB1GrW9Wml9XrOxmKjgE9RiGa4Gf
date:
keyword[0]:Lorem ipsum
keyword[1]:Is dolor amet
keyword[2]:plumber tampa
Request Headers
X-XSRF-TOKEN:5j6DGhhTytbIRB1GrW9Wml9XrOxmKjgE9RiGa4Gf
.....
am I doing something wrong or forgetting something?
I don't think that csrf token is the issue here. If it were you would get TokenMissmatchException and not Unprocessable Entity.
Do you happen to have a request validator in your Controller like this?
$validator = Validator::make($request->all(), [
'username' => 'required|max:30|min:6|unique:users',
'email' => 'required|email|max:50|unique:users',
'password' => 'required|confirmed|min:6',
]);
If so maybe you can do something like this:
if ($validator->fails()) {
if($request->ajax())
{
return response()->json(array(
'success' => false,
'message' => 'There are incorect values in the form!',
'errors' => $validator->getMessageBag()->toArray()
), 422);
}
$this->throwValidationException(
$request, $validator
);
}
After that you can catch validation errors in your ajax error handler like this:
$('.keywords-plan-form').submit(function(event) {
event.preventDefault();
$.ajax({
url: '/laravel/public/keywordsplans',
type: 'POST',
data: $(this).serialize(),
success: function(data){
alert(data);
// success logic
},
error: function(jqXhr, json, errorThrown){// this are default for ajax errors
var errors = jqXhr.responseJSON;
var errorsHtml = '';
$.each(errors['errors'], function (index, value) {
errorsHtml += '<ul class="list-group"><li class="list-group-item alert alert-danger">' + value + '</li></ul>';
});
//I use SweetAlert2 for this
swal({
title: "Error " + jqXhr.status + ': ' + errorThrown,// this will output "Error 422: Unprocessable Entity"
html: errorsHtml,
width: 'auto',
confirmButtonText: 'Try again',
cancelButtonText: 'Cancel',
confirmButtonClass: 'btn',
cancelButtonClass: 'cancel-class',
showCancelButton: true,
closeOnConfirm: true,
closeOnCancel: true,
type: 'error'
}, function(isConfirm) {
if (isConfirm) {
$('#openModal').click();//this is when the form is in a modal
}
});
}
});
});
And see the messages in the
modal message
Maybe someone will come in handy.
422 Unprocessable Entity
is default error by validator laravel
vendor/laravel/framework/src/Illuminate/Validation/Validator.php
If fails validate params, then throught Exception ValidationException
vendor/laravel/framework/src/Illuminate/Validation/ValidationException.php
where default status = 422
And therethore all your ajax responses with non validate forms will be with status = 422
I have solved this issue :
public function register(\Illuminate\Http\Request $request) {
if ($this->validator($request->all())->fails()) {
$errors = $this->validator($request->all())->errors()->getMessages();
$clientErrors = array();
foreach ($errors as $key => $value) {
$clientErrors[$key] = $value[0];
}
$response = array(
'status' => 'error',
'response_code' => 201,
'errors' => $clientErrors
);
} else {
$this->validator($request->all())->validate();
$user = $this->create($request->all());
$response = array(
'status' => 'success',
'response_code' => 200
);
}
echo json_encode($response);
}
Whoever is still looking for the answer, if you are using Lumen make sure the Request object is a type of Illuminate\Http\Request and not the default one from Lumen.
```function create(Request $request){