Hello everybody iam new to laravel and i hope you will help me to solve this problem. I want to update a particular column conditions, 1 to 0 and 0 to 1 when user click the link with Ajax.
I have column named status which can have value 1 or 0,according to user click the link value gets updated.
I have two route
Route::get('/logo/updateY/{id}', [ 'uses'=> 'Backend\Logo\LogoController#updateYesStatus', 'permission'=> 'update' ]);
Route::get('/logo/updateN/{id}', [ 'uses'=> 'Backend\Logo\LogoController#updateNoStatus', 'permission'=> 'update' ]);
controller
public function updateYesStatus($id)
{
$logoStatus = Logo::findOrFail($id);
$logoStatus->update(['status'=>'1']);
return redirect::to('administrator/logo/view');
}
public function updateNoStatus($id)
{
$logoStatus = Logo::findOrFail($id);
$logoStatus->update(['status'=>'0']);
return redirect::to('administrator/logo/view');
}
view:
#if($logo->status== 1)
<td >Displayed</td>
#else
<td >Hidden</td>
#endif</td>
<script type="text/javascript">
$(document).on('click','.userStatus',function(){
var id = $(this).attr('id');
$.ajax({
data:{ id=id, _token: '{!! crfs_toekn() !!}'},
url: '',
type: 'POST',
dataType: 'json'
success:function()
{
}
});
});
</script>
1) Use the same method (GET or POST) in the ajax and at routes
2) You should fix the ajax data
{id: id, _token: '{!! csrf_token() !!}'}
3) You should pass the url to ajax
Related
I try to make POST-request to method of admin controller using AJAX (from admin part). My JS code:
<script>
$(".remove-request-btn").on('click', function () {
let request_id = $(this).data('request-id');
let confirm_result = confirm('Are you sure you want to delete this request?');
if (confirm_result) {
$.ajax({
url: 'index.php?route=extension/x_feedback/settings/removeRequest&token={{ token }}',
method: 'post',
dataType: 'json',
data: {request_id: 11},
success: function(data) {
if (data.status === 'ok') {
location.reload();
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
My method:
public function removeRequest()
{
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode(
[
'status' => 'ok'
]
));
}
I expect json in the response but get following:
I tried to add admin into the url like '/admin/index.php?route=extension/x_feedback/button/feedbackRequest&token={{ token }}'
But it doesn't help. Can you help me please what I'm doing wrong? Thank you!
1-please add bellow code into controller method
$data['token'] = $this->session->data['user_token'];
2- use javascript into .twig file - not external js file.
In OC3 is used user_token instead token
so you must use this url:
url: 'index.php?route=extension/x_feedback/settings/removeRequest&user_token={{ user_token }}',
And do not forget declare user_token in the corresponding controller file:
$data['user_token'] = $this->session->data['user_token'];
I've set up two buttons which when clicked are just sending their values to my controller, then I am trying to send back AJAX HTML to show the users profile on the main page. I can't get the input id to make it to the controller no matter what I try.
Here's the HTML:
<ul class="signup-li">
#foreach($participants as $participant)
<button type="submit" name="id" value="{{$participant->id}}">
{{$participant->phone}}
</button>
#endforeach
</ul>
Here is my JS:
$(document).ready(function(){
$("button").click(function() {
var id = $(this).val();
console.log(id);
$.ajax({
type:'POST',
url:'/get-profile/',
headers: {'X-CSRF-TOKEN': '{{ csrf_token() }}' },
data: { "id" : id },
success: function(data){
console.log('hi');
},
error: function(xhr,textStatus,thrownError) {
alert(xhr + "\n" + textStatus + "\n" + thrownError);
}
});
});
});
Here is my controller function:
public function getProfile(Request $request)
{
$id = $request->input('id');
Log::info($id);
$participant = Participant::where('id','=',$id)->first();
$returnHTML = view('ajax.user-profile')->with('participant', $participant)->renderSections()['content'];
return response()->json(array('success' => true, 'html'=>$returnHTML));
}
What am I doing wrong? I try to log the request and nothing comes through. I have CSRF disabled for this route. The issue is that the participant is not found because the ID is not getting to the controller. Why isnt it making it?
You may add dataType: 'json', to your $.ajax({...}) call
I am trying to get a list of countries with their cities using Select2 with Jquery.
At the time of creating a post with their respective country and city, I don't have a problem, but at the time of editing the post I miss the following error:
http: //imperial.test/dashboard/posts/40/edit/getStates/6 (Not Found)
D:\laragon\www\Imperial\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php # 179
Routes:
Route::group([
'prefix' => 'dashboard',
'namespace' => 'Admin',
'middleware' => 'auth'],
function(){
Route::get('/', 'AdminController#index')->name('dashboard');
Route::resource('posts', 'PostsController', [
'names' => [
'index' => 'dashboard.posts.index',
'create' => 'dashboard.posts.create',
'store' => 'dashboard.posts.store',
'edit' => 'dashboard.posts.edit',
'update' => 'dashboard.posts.update',
'destroy' => 'dashboard.posts.destroy',
],
]);
Route::get('posts/create/getStates/{id}', 'PostsController#getStates');
Route::get('posts/create/getCities/{id}', 'PostsController#getCities');
Route::get('posts/edit/getStates/{id}', 'PostsController#getStates');
Route::get('posts/edit/getCities/{id}', 'PostsController#getCities');
Route::get('images/posts/{id}/avatar/{image}', [
'uses' => 'PostsController#postProfileAvatar',
]);
});
My Script
$(document).ready(function(){
$('select[name="country_id"]').on('change',function(){
var country_id = $(this).val();
if(country_id)
{
$.ajax({
url: '/edit/getStates/'+country_id,
type: 'GET',
dataType: 'json',
success: function(data){
console.log(data);
$('select[name="state_id"]').empty();
$.each(data, function(key, value){
$('select[name="state_id"]')
.append('<option value="'+key+'">' + value + '</option>');
});
}
});
} else {
$('select[name="state_id"]').empty();
}
});
$('select[name="state_id"]').on('change',function(){
var state_id = $(this).val();
if(state_id)
{
$.ajax({
url: '/edit/getCities/'+state_id,
type: 'GET',
dataType: 'json',
success: function(data){
console.log(data);
$('select[name="city_id"]').empty();
$.each(data, function(key, value){
$('select[name="city_id"]').append('<option value="'+key+'">' + value + '</option>');
})
}
});
}else {
$('select[name="city_id"]').empty();
}
});
});
N' in the blade if the script path is registered:
<script src="{{ asset('js/worldedit.js') }}" defer></script>
Any suggestions on how to solve this error, I tried it in a separate project without using Route :: group and prefixes and I did it with GET routes and it worked, so I deduce that the problem is in the ajax route
Your route is under a group with prefix dashboard, so shouldn't it be
url: '/dashboard/posts/edit/getStates/'+ country_id
Instead of just
url: '/edit/getStates/'+country_id
When you are viewing a post your current address is
http: //imperial.test/dashboard/posts/40
and your javascript has this url (relative address)
url: '/edit/getStates/'+country_id,
So ajax call actually get this url:
http: //imperial.test/dashboard/posts/40/edit/getStates/6
While you are defining route (in laravel web.php) for
http: //imperial.test/dashboard/posts/edit/getStates/{id}
So you get not found error.
Define your routes as
Route::get('posts/{postid}/edit/getStates/{id}', 'PostsController#getStates');
Route::get('posts/{postid}/edit/getCities/{id}', 'PostsController#getCities');
You must use the route helper to get the route by name. In this case, you can do the following:
In the html "select" element:
For example, suppose you have a route called "cities.list" that retrieves all cities in this state:
<select name="state_id" data-route="{{ route('cities.list', ['id' => ':id']) }}" >
So, in the js script just use that route as follows:
....
var select_state = $('select[name="state_id"]'); // or $(this)
var route = select_state.data('route')
route = route.replace(':id', select_state.val())
$.ajax({
url: route,
type: 'GET',
dataType: 'json',
....
Did you get the idea?
I'm trying to delete record using ajax, in laravel 5.4, I know this is one of the common questions and there are already lots of online solutions and tutorials available about this topic. I tried some of them but most of giving me the same error NetworkError: 405 Method Not Allowed. I tried to do this task by different angle but I'm stuck and could not found where I'm wrong, that's why I added this question for guideline.
I'm trying the following script for deleting the record.
IN Route:
Route::delete('article/delete/{article}', 'ArticleController#delete_article')->name("delete_article");
In Controller:
public function delete_article($id)
{
article::where('id', $id)->delete($id);
return response()->json([
'success' => 'Record deleted successfully!'
]);
}
IN View:
<li name="csrf-token" content="{{ csrf_token() }}">
<a class="deleteRecord" href="/admin/article/delete/{{$article->id}}">
<i class="icon-bin"></i>delete
</a>
</li>
Ajax Code is:
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: /admin/article/delete/{{article}},
type: 'DELETE',
data: {
"id": id,
"_token": token,
},
success: function (){
console.log("it Works");
}
});
});
As you can See it seems everything is right but I don't know why it doesn't work correctly?
please help me, guys.
This is work for me:
In Route
Route::post('/article/delete', 'ArticleController#delete_article');//Ajax Routes
IN Controller
public function delete_article(Request $request)
{
$id=$request['id'];
article::where('id', $id)->delete();
return response()->json(['articleDelete' => 'success']);
}
in View:
<td>
<a class="deleteRecord" data_id="{{$article->id}}">
<i class="icon-bin" style="color: black"></i></a>
</td>
In AJAX:
$(".deleteRecord").each(function () {
$(this).on("click", function () {
var $tr = $(this).closest('tr');
var id = $(this).attr("data_id");
swal({
title: "Are you sure to Delete!",
text: "***",
icon: "warning",
buttons: [
'cansle!',
'yes'
],
dangerMode: true,
}).then(function(isConfirm) {
if (isConfirm) {
$.ajax({
url: '/admin/article/delete',
type: 'post',
dataType: 'json',
data: {_token: "{{csrf_token()}}" , id:id},
success: function () {
swal({
title: "article deleted succesfuly",
icon: "success",
type: 'success',
})
$tr.find('td').fadeOut(1000,function(){
$tr.remove();
});
}
})
}
})
});
});
The problem (as far as I can see) lies here:
<a class="deleteRecord" href="/admin/article/delete/{{$article->id}}">
In your view, you make a variable named id and the value is based on data-id attrribute.
var id = $(this).data("id");
But in your a tag you don't have data-id attribute. So you have to add it (something like this):
<a class="deleteRecord" href="/admin/article/delete/{{$article->id}}" data-id="{{$article->id}}">
Also in your ajax call, teh url is incorrect (based on what you have defined in routes:
Ajax call:
url: "article/"+id
Route:
article/delete/{article}
So either change the route:
article/{article}
or change the ajax call:
url: "article/delete/"+id
And one more thing. You have to prevent default a tag action. change the event like this:
$(".deleteRecord").click(function(event){
event.preventDeault();
You are doing wrong in many places. Try this
Route
Route::delete('article/delete/{article}', 'ArticleController#delete_article')->name("delete_article");
Controller
public function delete_article($article)
{
article::where('id', $article)->delete();
return response()->json([
'success' => 'Record deleted successfully!'
]);
}
View
<button class="deleteRecord" data-id="{{$article->id}}"><i class="icon-bin"></i>delete</button>
AJAX
$(".deleteRecord").click(function(){
var id = $(this).data("id");
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "article/delete/"+id,
type: 'POST',
dataType: 'json',
data: {
_method: 'DELETE',
submit: true,
_token: token,
},
success: function (){
console.log("it Works");
}
});
});
I'm trying to send 2 variables to FavorisController: {{ Auth::user()->id }} and the id that I have in the URL
This is what I've tried so far
Route:
Route::get('annonce_test/{id}','FavorisController#create' );
My ajax script
$(document).ready(function() {
$('.favoris').click(function(){
var id_user = "{{ Auth::user()->id }}" ;
$.ajax({
url: 'annonce_test/{id}',
type: 'GET',
data: {id: 1, id_user: $id_user},
success: function(data){
alert(Ajouter au Favoris avec succes);
},
error: function(){},
});""
});
});
FavorisController
public function create(Requests $request)
{
$id_annonce = $_GET['id'];
$id_user = $_GET['id_user'];
$query = DB::table('annonce_residentiel_user')
->insertGetId(
array('annonce_residentiel_id' => $id_annonce , 'user_id' => $id_user)
);
}
I got the error trying to get property of non-object {{ Auth::user()->id }}
But is this the correct way to do it? I mean if I have another script for deleting I should chage the url in my ajax script.
Move Auth::user() part from JS script to PHP:
->insertGetId(['annonce_residentiel_id' => $id_annonce , 'user_id' => auth()->user()->id]);
Also, make sure user is authenticated with something like:
if (auth()->check()) {
// Do stuff.
}
Based on your route definition $id is the argument for the create method and to get more data from the ajax call you should use Input::get. Also the route will be activated only when the url in the ajax call has the format of ex: annonce_test/25. check the update to the ajax call.
Route:
Route::get('annonce_test/{id}','FavorisController#create' );
Ajax call:
$(document).ready(function() {
$('.favoris').click(function(){
var id_user = "{{ Auth::user()->id }}" ;
$.ajax({
url: 'annonce_test/'+id_user,
type: 'GET',
data: {id: 1},
success: function(data){
alert(Ajouter au Favoris avec success);
},
error: function(){},
});
});
});
FavorisController:
public function create($id)
{
$id_annonce = Input::get['id'];
$query = DB::table('annonce_residentiel_user')->insertGetId(
array('annonce_residentiel_id' => $id_annonce , 'user_id' => $id));
}