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));
}
Related
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 have a Laravel application that works perfectly locally, but every AJAX call returns 404 when hosted. I'm unsure if this is from a sever config error, a missing php.ini setting, or something else? I've included an example of a failing call.
AJAX/JQ:
var url = "/final-review";
$("#review_note_text").change(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$('#review_note_loader').show();
var formData = {
note_text: $('#review_note_text').val(),
};
var type = "POST";
var reviewNoteUrl = url + '/review-note';
$.ajax({
type: type,
url: reviewNoteUrl,
data: formData,
dataType: 'json',
success: function (data) {
$('#failure-message-review').hide();
$('#success-message-review p').html("Saved successfully" + '×');
$('#success-message-review').show();
$('#review_note_loader').removeClass("halted-loader").hide();
},
error: function (data) {
$('#review_note_loader').addClass("halted-loader");
$('#failure-message-review p').html("Something went wrong, your record was not updated. <strong>Error Code: " + data.status + "</strong>" + '×');
$('#failure-message-review').show();
}
});
});
My Corresponding Route:
Route::post('final-review/review-note', 'FinalReviewController#update_review_note');
Controller Function
public function update_review_note(Request $request){
$validatedData = $request->validate([
'note_text' => 'nullable|string',
]);
$note = \App\ReviewNote::create([
'note_text' => $request->get('note_text'),
'author' => Auth::user()->name,
'created_at' => now()
]);
return Response::json($note);
}
SOLVED:
I had to change the "url" var in my blade template to be:
var url = "{{ url('/final-review') }}";
In my AJAX I was defining "url" as "/final-review", which led to a route of "foobar.com/final-review/params" what I really needed was "foobar.com/app-name/final-review/params".
Testing locally, I did not have "app-name" in my URL.
I have got a form with a delete button which I see on the console that it's sending a delete request.
jquery.js:4 DELETE http://laravel.com/painel/player/53 500 (Internal Server Error)
and my route is:
Route::resource('painel/player','PlayerController');
| DELETE | painel/player/{player} | painel.player.destroy | App\Http\Controllers\PlayerController#destroy |
and my method destroy is as below:
public function destroy($id)
{
$player = Player::where('id_player', '=', $id)->first();
$player->delete();
$player = array(
'users' => Player::all(),
'refresh' => true
);
return View::make('painel.player.show', $player);
}
EDIT:
I forgot to mention the ajax:
$( document ).on('click', '.solsoConfirm', function(){
$("#solsoDeletForm").prop('action', $(this).attr('data-href'));
});
$( document ).on('click', '.solsoDelete', function(e){
e.preventDefault();
var solsoSelector = $(this);
var solsoFormAction = $('#solsoDeletForm').attr('action');
$.ajax({
url: solsoFormAction,
type: 'delete',
cache: false,
dataType: 'html',
success:function(data) {
$('#solsoDeleteModal').modal('hide');
$('#ajaxTable').html(data);
$('#countClients').text( $('.solsoTable').attr('data-all') );
$.growl.notice({ title: solsoSelector.attr('data-message-title'), message: solsoSelector.attr('data-message-success') });
$('.solsoTable').dataTable();
}
});
return false;
});
While your $.ajax({ ... type: 'delete' ... }) should work, you need to set up your response to accept the 'delete' method.
The alternative and standard way to do PUT, PATCH, and DELETE in Laravel is via method spoofing:
<form action="painel/player/{{ $id }}" method="POST">
{{ method_field('DELETE') }}
{{ csrf_field() }}
</form>
Your JS might look something like:
var csrf = $('input[name="_token"]').val();
$.ajax({
url: solsoFormAction,
type: 'post',
data: {_method: 'delete', _token: csrf},
...
});
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
I want to load my post via AJAX when I click on a post link, how I can send my post ID via AJAX?
I've got a link in my Blade file:
{{ link_to_route($post->type, $post->comments->count() . ' ' . t('comments'), array('id' => $post->id, 'slug' => $post->slug), array('class' => 'link--to--post')) }}
I've got the following route definition:
Route::get('news/{id}-{slug?}', ['as' => 'news', 'uses' => 'NewsController#show']);
And controller action:
public function show($id, $slug = null)
{
$post = $this->news->getById($id, 'news');
if ($slug != $post->slug){
return Redirect::route('news', ['id' => $post->id, 'slug' => $post->slug]);
}
Event::fire('posts.views', $post);
return View::make('post/post', compact('post'));
}
And then I'm trying this:
var postTitle = $(".link--to--post");
postTitle.click(function () {
$.ajax({
url: '/news/{id}-{slug}',
type: 'GET',
data: $(this),
success: function (data) {
console.log(data)
}
});
return false;
});
But this doesn't work for me, what am I doing wrong?
Your javascript should pass the parameters like this:
$.ajax({
url: '/news/' + id + '-' + slug,
success: function (data) {
console.log(data)
}
});
You had url: '/news/{id}-{slug}', which would perform a GET request to /news/{id}-{slug}, which isn't a valid route -- you want a URL like /news/1-foo.