laravel Requested Ajax not working - php

in simple of my form i want to use ajax with $.post and get and post request with that, after using $.post and submit form my page is refresh and alert do not work validation of controller.
simply request ajax in controller does not working correctly
my form :
<script type="text/javascript">
$(document).ready(function(){
$('form').submit(function(){
name = $('#name').val();
family = $('#family').val();
email = $('#email').val();
currPassword = $('#currPassword').val();
password = $('#password').val();
password_confirmation = $('#password_confirmation').val();
$.post('{{ URL::route('admin.profile.update') }}' ,
{
name : name,
family : family,
email : email,
currPassword : currPassword,
password : password,
password_confirmation : password_confirmation
},
function(data){
if(data.errors)
alert(data.errors)
}
);
//return false;
});
})
</script>
{{ Form::model($profile, array('route' => array('admin.profile.update', $profile->id), 'method' => 'PUT')) }}
<div style='padding:10px;font-weight: bold;'>ویرایش مشخصات شخصی</div>
<table style='width:95%;border:none;font-size:11px;margin: 5px;text-align: left'>
<tr>
<td width="80px">{{ Form::label('name' , 'نام: ') }}</td>
<td>{{ Form::text('name',null , array('id'=>'name', 'class' => 'form-control' )) }}</td>
</tr>
<tr>
<td>{{ Form::label('family' , 'نام خانوادگی: ') }} </td>
<td>{{ Form::text('family', null, array('id'=>'family', 'class' => 'form-control')) }}</td>
</tr>
<tr>
<td>{{ Form::label('email' , 'ایمیل: ') }}</td>
<td>{{ Form::text('email', null, array('id'=>'email', 'class' => 'form-control ltr')) }}</td>
</tr>
<tr>
<td>{{ Form::label('currPassword' , 'رمز عبور فعلی: ') }}</td>
<td>{{ Form::password('currPassword', array('id'=>'currPassword', 'class' =>'form-control ltr')) }}</td>
</tr>
<tr>
<td>{{ Form::label('password' , 'رمز عبور: ') }}</td>
<td>{{ Form::password('password', array('id'=>'password', 'class' =>'form-control ltr')) }}</td>
</tr>
<tr>
<td>{{ Form::label('password_confirmation' , 'رمز عبور مجدد: ') }}</td>
<td>{{ Form::password('password_confirmation', array('id'=>'password_confirmation', 'class' =>'form-control ltr')) }}</td>
</tr>
<tr>
<td colspan="2">{{ Form::submit('ویرایش مشخصات', array('id'=>'submit','class'=>'btn btn-default' , 'style'=>'float:left')) }}</td>
<td></td>
</tr>
</table>
{{ Form::close() }}
my Controller :
public function update($id)
{
if ( Request::ajax() ){
$rules = array(
'name' => 'required|alpha',
'family' => 'required',
'email' => 'required|email',
'currPassword'=> 'required',
'password' => 'required|confirmed|min:4',
'password_confirmation'=>'required',
);
$validator = Validator::make(Input::all(), $rules);
if ($validator->fails()) {
/*
return Redirect::to('/admin/profile')
->withErrors($validator)
->withInput();
*/
return Response::json(array(
'errors'=>$validator
));
}
}
}
My Route:
Route::group(array('before' => 'auth'), function()
{
Route::resource ('admin/profile' , 'ProfileController', array('as'=>'profile' , 'before'=>'csrf'));
});

I believe the problem is the form is submitting because you are not using preventDefault() but I see that you were struggling with getting that to work correctly in a previous question. That is why your page is refreshing.
What you can do is instead of using Form::submit(), you can use Form::button() which will keep the form from submitting allowing you to do as you please with javascript. Then, instead of using $('form').submit() which should no longer work because it's not submitting, attach the handler to the click event of the button. $('#submit').on('click', function() { // Code goes here});
This unfortunately comes with the negative side-effect of your form not being able to function at all if the user does not have javascript enabled in the browser.
Also, depending on which browser you are using, you should be looking at the XHR requests as they happen using the developer tools, to see if there are any errors or statuses returned.

Related

Having problem with retriving json data in laravel

I'm working on a laravel project and i'm getting JSON error. I've try few options to solve the issue but did not come up with any solutions.
In this project I've to send multiple data into database onder one "ID". In that ID there are at list 10 data need to insert. So I used JSON format. It saves ok but getting error when I try to pull data.
Here is my code
Controller :
public function newExpenses(Request $request){
$Jexpenses = new Jexpenses;
$json = array(
'des' => $request->description,
'valu' => $request->expenses
);
$Jexpenses->voucher = $request->voucher_no;
$Jexpenses->date = $request->date;
$Jexpenses->description = json_encode($json);
$Jexpenses->expenses = $request->total;
$Jexpenses->remarks = $request->remark;
if($Jexpenses->save()){
$notification = array(
'message' => 'Expenses Saved',
'alert-type' => 'success'
);
}
return redirect()->back()->with($notification);
}
result :
{"des":["Jon","Sam","Pitter"],"valu":["20","30","15"]}
Return Controller:
public function expenses(){
$data = array(
'title' => 'Expenses',
'expenses' => Jexpenses::all()
);
return view('expenses.expenses')->with($data);
}
html :
#foreach ($expenses as $key => $getData)
{{ $array = #json( $getData->description ) }}
<tr>
<td>{{ ++$key }} </td>
<td>{{ $getData->voucher }} </td>
<td>{{ $getData->date }} </td>
#foreach ($array->description as $k => $v)
<td>{{ $array->des['$k'] }}</td>
<td>{{ $array->valu['$k'] }}</td>
#endforeach
<td>{{ $getData->expenses }}</td>
<td>{{ $getData->remarks }}</td>
</tr>
#endforeach
it should be work fine but getting error
error:
syntax error, unexpected '<' (View: C:\xampp\htdocs\acSoft\resources\views\expenses\expenses.blade.php
Need some help. Thanks.
1) Use json_decode($getData->description) instead #json. The #json is shortly form of json_encode
2) $array->description not exists property. Should be $array->des
3) You use variable in ' quotes. You should use " quote or nothing round variables.
4) It is bad idea using reserved words as variable names. I am about variable $array
#foreach ($expenses as $key => $getData)
{{ $descriptionData = json_decode( $getData->description ) }}
<tr>
<td>{{ $key + 1 }} </td>
<td>{{ $getData->voucher }} </td>
<td>{{ $getData->date }} </td>
#foreach ($descriptionData->des as $k => $v)
<td>{{ $descriptionData->des[$k] }}</td>
<td>{{ $descriptionData->valu[$k] }}</td>
#endforeach
<td>{{ $getData->expenses }}</td>
<td>{{ $getData->remarks }}</td>
</tr>
#endforeach

Data doesn't display

Need some help here, I'm using Laravel app, my problem is my data wont display on the table. I tried some ways to display my data but it doesn't work.
Here's my code.
<tbody>
#if (count($expenses) > 0)
#foreach ($expenses as $expense)
<tr data-entry-id="{{ $expense->id }}">
<td field-key='expense_category'>{{ $expense->expense_category->name or '' }}</td>
<td field-key='entry_date'>{{ $expense->entry_date }}</td>
<td field-key='amount'>{{ $expense->amount }}</td>
<td field-key='created_by'>{{ $expense->created_by->name or '' }}</td>
<td>
#can('view')
#lang('quickadmin.qa_view')
#endcan
#can('edit')
#lang('quickadmin.qa_edit')
#endcan
#can('delete')
{!! Form::open(array(
'style' => 'display: inline-block;',
'method' => 'DELETE',
'onsubmit' => "return confirm('".trans("quickadmin.qa_are_you_sure")."');",
'route' => ['expenses.destroy', $expense->id])) !!}
{!! Form::submit(trans('quickadmin.qa_delete'), array('class' => 'btn btn-xs btn-danger')) !!}
{!! Form::close() !!}
#endcan
</td>
</tr>
#endforeach
#else
<tr>
<td colspan="9">#lang('quickadmin.qa_no_entries_in_table')</td>
</tr>
#endif
</tbody>
here is my expenseController.
but i have never touched this code, i always work on the table form.
class ExpensesController extends Controller
{
/**
* Display a listing of Expense.
*
* #return \Illuminate\Http\Response
*/
public function index()
{
if (! Gate::allows('expense_access')) {
return abort(401);
}
if ($filterBy = Input::get('filter')) {
if ($filterBy == 'all') {
Session::put('Expense.filter', 'all');
} elseif ($filterBy == 'my') {
Session::put('Expense.filter', 'my');
}
}
$expenses = Expense::all();
return view('admin.expenses.index', compact('expenses'));
}
}
try to find are you getting data from DB or not ....
$expenses = Expense::all();
dd($expenses);
It will show your data collection.
As I Think you are not getting any data from here.

Laravel 5.4 change user role

I trying make changing role in my panel admin. But when i made it my form dont sending post request. Now only working showing user role. I cant fix it becouse when i click button to switch i dont get any error and role is not changing.
I use HttpRequester when i use url /admin/change its showing this error:
MethodNotAllowedHttpException in RouteCollection.php line 233
There is my code:
View:
#extends('layouts.app')
#section('content')
<h2>Panel Admina</h2>
<div class="panel-group">
<div class="panel panel-default">
<div class="panel-body">
<table class="table">
<thead>
<tr>
<th>Id</th>
<th>Imię</th>
<th>Nazwisko </th>
<th>E-mail </th>
<th>Nr.tele </th>
<th>Użytkownik </th>
<th>Moderator </th>
<th>Admin </th>
</tr>
</thead>
<tbody>
#foreach($users as $user)
<tr>
<form action="{{route('change')}}" method="post">
{{ csrf_field() }}
<td>{{ $user->id }}</td>
<td>{{ $user->name }}</td>
<td>{{ $user->lastname }}</td>
<td>{{ $user->email }}<input type="hidden" name="email" value="{{ $user->email }}"></td>
<td>{{ $user->phonenumber }}</td>
<td><input type="checkbox" {{ $user->hasRole('User') ? 'checked' : '' }} name="role_user"/></td>
<td><input type="checkbox" {{ $user->hasRole('Moderator') ? 'checked' : '' }} name="role_moderator"/></td>
<td><input type="checkbox" {{ $user->hasRole('Admin') ? 'checked' : '' }} name="role_admin"/></td>
<td><input type="submit" class="btn btn-default btn-sm" value="Przydziel rolę"></td>
</form>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
#endsection
Controller:
public function change(Request $request)
{
$user = User::where('email', $request['email'])->first();
$user->roles()->detach();
if ($request['role_user']) {
$user->roles()->attach(Role::where('name', 'User')->first());
}
if ($request['role_moderator']) {
$user->roles()->attach(Role::where('name', 'Moderator')->first());
}
if ($request['role_admin']) {
$user->roles()->attach(Role::where('name', 'Admin')->first());
}
return redirect()->back();
}
Routing:
Route::get('/admin', [
'uses' => 'AdminController#index',
'middleware' => 'roles',
'roles' => ['Admin']
]);
Route::post('/admin/change', [
'uses' => 'AdminController#change',
'as' => 'change',
'middleware' => 'roles',
'roles' => ['Admin']
]);
I really dont know how i can resolve my problem.
try to pass the user id to your route and your form action and instead of post make it put for example:
<form action="{{route('change', $user->id)}}" method="post">
and in your route:
Route::put('/admin/change/{id}', [
'uses' => 'AdminController#change',
'as' => 'change',
'middleware' => 'roles',
'roles' => ['Admin']
]);
and in your controller:
public function change(Request $request, $id)

Laravel: Check checkbox if true or false, then update database

Just started with laravel using phpStorm. Im trying to create a form that take inputs, and a checkbox, then adds it to a database.
All of the rows in the database get listed in the view index.html. The user should be allowed to activate or deactivate (with the checkbox) the the message that should be listed when browsing the index.html file. Because if a news article is active, and you want to deactivate it, you should be able to just uncheck the checkbox, and it will be deactivated.
So I am wondering how my function should look like.
Im also unsure how to run the function ActivatedOrDeactivated when the checkbox gets checked or unchecked.
Its my first post, so please tell if something is hard to understand in my description.
My route:
Route::get('admin',
[
'uses' => 'NyhetsController#index',
'as' => 'admin.index'
]
);
Route::get('admin/create',
[
'uses' => 'NyhetsController#create',
'as' => 'admin.create'
]
);
Route::post('admin',
[
'uses' => 'NyhetsController#store',
'as' => 'admin.store'
]
);
Route::get('admin/{id}',
[
'uses' => 'NyhetsController#show',
'as' => 'admin.show'
]
);
Route::get('admin/{id}/edit',
[
'uses' => 'NyhetsController#edit',
'as' => 'admin.edit'
]
);
Route::put('admin/{id}',
[
'uses' => 'NyhetsController#update',
'as' => 'admin.update'
]
);
Route::get('admin/{id}/delete',
[
'uses' => 'NyhetsController#delete',
'as' => 'admin.delete'
]
);
Route::delete('admin/{id}',
[
'uses' => 'NyhetsController#destroy',
'as' => 'admin.destroy'
]
);
My Controller that contains the function (just something i wrote in anger):
public function ActivatedOrDeactivated($id){
$news = News::findOrFail($id);
$input = Input::get('active');
if($input == true)
{
$news->active = 'false';
$news->update($input);
}
else{
$news->active = 'true';
$news->update($input);
}
}
My index file that contains the form:
<h1>Alle postene i databasen</h1>
<p>{{ link_to_route('admin.create', 'Legg til ny nyhet') }}</p>
#if($news->count())
<table class="table table-striped table-boarded">
<thead>
<tr>ID</tr>
<tr>Title</tr>
<tr>Author</tr>
<tr>Message</tr>
<tr>Active</tr>
<tr>Picture path</tr>
<tr>Activate/Deactivate</tr>
</thead>
<tbody>
#foreach($news as $n)
<tr>
<td>{{ $n->id }}</td>
<td>{{ $n->title }}</td>
<td>{{ $n->author }}</td>
<td>{{ $n->message }}</td>
<td>{{ $n->active }}</td>
<td>{{ $n->picture_path }}</td>
<td>{{ Form::checkbox('active') }}</td>
<td>{{ link_to_route('admin.destroy', 'Delete', array($n->id)) }}</td>
</tr>
#endforeach
</tbody>
</table>
When you want to update the news item when a user clicks the checkbox without ajax this would a way to do it:
router.php
Route::post('admin/{id}/active',
[
'uses' => 'NyhetsController#toggleActive',
'as' => 'admin.toggle_active'
]
);
HTML index.blade.php
#if($news->count())
<table class="table table-striped table-boarded">
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Author</th>
<th>Message</th>
<th>Picture path</th>
<th>Active</th>
</tr>
</thead>
<tbody>
#foreach($news as $n)
<tr>
<td>{{ $n->id }}</td>
<td>{{ $n->title }}</td>
<td>{{ $n->author }}</td>
<td>{{ $n->picture_path }}</td>
<td>{{ $n->message }}</td>
<td>
{{ Form::open(array('url' => 'admin/' . $n->id . '/active')) }}
{{ Form::submit('', [ 'class' => ($n->active ? 'glyphicon glyphicon-ok' : 'glyphicon glyphicon-remove') ]);
{{ Form::close() }}
<td>{{ link_to_route('admin.destroy', 'Delete', array($n->id)) }}</td>
</tr>
#endforeach
</tbody>
</table>
#endif
NyhetsController
public function toggleActive($id) {
$news = News::findOrFail($id);
if($news->active)
{
$news->active = 'false';
$news->update($input);
}
else{
$news->active = 'true';
$news->update($input);
}
}
return Redirect::to('admin');
Code is untested!
In your Form::
{{ Form::checkbox('active', 'true') }}
In your Controller
$news = News::findOrFail($id);
if (Input::get('active') === 'true') {
$news->active = 'true'; // UPDATE:must be true of course
$news->update($input);
} else {
$news->active = 'false'; // UPDATE:must be false of course
$news->update($input);
}
By the way: you could save yourself some typing if you simply route restfully using
Route::resource('admin', 'NyhetsController');

Laravel 3: with_input() not saving input

I have a Laravel form that gets passed through some validation. Obviously, if the validation fails, I'd like the user to be redirected to form and alerted of their mistake. Also, because the form is fairly large, I don't want the user to have to re-input any data. Here is the form (I've cut off a large part to reduce the size of this message)
:#layout('templates.main')
#section('content')
#if(Session::has('validation_errors'))
<ul class="form_errors">
#foreach($errors as $error)
{{$error}}
#endforeach
</ul>
#endif
{{ Form::open('account/create', 'POST') }}
<table>
<tr>
<td>{{ Form::label('dealer', 'Dealer') }}</td>
<td>{{ Form::select('dealer', array('1' => 'Dealer #1', '2' => 'Dealer #2')) }}</td>
<td>{{ Form::label('amount', 'Amount') }}</td>
<td>{{ Form::text('amount', Input::old('amount')) }}</td><!--Here is where I'm testing for old input-->
</tr>
<tr>
<td>{{ Form::label('date', 'Date') }}</td>
<td>{{ Form::date('date', NULL, array('class' => 'date_picker')) }}</td>
<td>{{ Form::label('installation', 'Installation #') }}</td>
<td>{{ Form::input('text', 'installation') }}</td>
</tr>
<tr>
<td colspan="4">{{ Form::textarea('notebox', NULL, array('id' => 'notebox')) }}</td>
</tr>
<tr>
<td colspan="4">{{ Form::submit('Submit') }} {{ Form::reset('Reset') }}</td>
</tr>
</table>
{{ Form::close() }}
#endsection
When the form is submitted, here is the controller that handles it:
public function post_create() {
//Validate it in the model
$validation = Account::validate(Input::all());
if($validation->fails()){
return Redirect::to('account/create')
->with_input()
->with('validation_errors', true)
->with('errors', $validation->errors->all('<li>:message</li>'));
}
else {
return "passed";//for debugging purposes
}
}
And lastly, here is the Account model:
class Account extends Eloquent {
public static function validate($input) {
//Validation rules
$rules = array(
'firstname' => 'required',
'lastname' => 'required',
//etc...
);
//Custom validation messages
$messages = array(
'firstname_required' => 'A first name is required.',
'lastname_required' => 'A last name is required.',
//etc...
);
//Pass it through the validator and spit it out
return Validator::make($input, $rules, $messages);
}
}
So when I go to test this by intentionally making the form invalid, I am redirected to the account/create form, however, no validation errors show, and the old input is not saved (I only attached Input::old() to the amount textbox).
It turns out that if the total number of characters from Input::old() exceeds ~1400 characters, things get a little buggy. I solved this by changing from 'driver' => 'cookie' to 'driver' => 'file' in my application/config/session.php and it began to work as expected.
https://github.com/laravel/laravel/issues/1475

Categories