Excelent tutorials! FInnaly I learned how to use AJAX with laravel!!! Thanks for the hard work Max, I believe I can speak in the names of many, you're helping us alot to start our careers as web developers!
What should I return if I have more things being updated such as like title. I wonder if : return response()->json(['new_body' => $post->body],['new_title' => $post->title], 5000); would work as well just like: return response()->json(['new_body' => $post->body], 200); By the way I appreciate for all the tutorials!
Thanks a lot for this course! I have a question about handling those unwanted scenarios; a) failed validation - is there some more intuitive way of passing errors through JSON instead of accumulation of those 422 statuses? b) Redirecting in our PostController if user editing the post doesn't match author of the post doesn't have much sense because we are just returning HTML of a whole new page asynchronously, right? But then again, as you pointed out couple of videos before, this is not standard and expected but suspicious activity and UX probably shouldn't be priority...
+gh0c Hi, interesting questions you got here: a) You may overwrite the default error handling like this: $validator = Validator::make($request->all(), [ 'title' => 'required|unique:posts|max:255', 'body' => 'required', ]); if ($validator->fails()) { // Implement whatever you want to do with the errors here // e.g. return redirect('post/create') // ->withErrors($validator) // ->withInput(); } b) Yes, that is certainly not the solution you'd implement in a real app. A better way would of course be, to return some json() with an error message (status code 401 makes sense, too) and then handle this error in your client-side code. I did not pay much attention to this here, as I wanted to focus on Laravel and the server-side instead of the client-side JS part. But you are absolutely right regarding the issues, this approach has.
Thank you very much for your lessons! Before seeing your course, I could not look the other English-language lessons, as my English is not very good, but you have described is very simple, understandable, and even intonation, emotionally and with love for his work, that with you I raise my level of knowledge Laravel, and tightens your English. Thank you so much! But in this lesson, there is a problem ... Error 500 ... public function postEditPost(Request $request) { $this->validate($request,[ 'body' => 'required' ]); $post = Post::find($request['[postId']); $post->body = $request['body']; $post->update(); return response()->json(['message' => 'Post edit!'], 200); } Creating default object from empty value (error occurs on line ); What's the problem can not understand, in other design features $ post-> body operates in $ request [ 'body'] text is present. Maybe something to do with updating laravel? Thanks in advance for your reply!
+Никита Лощенин Hi, first of all: Many thanks for this awesome feedback and the kind words, I'm really happy to hear that you're enjoying my videos! Now regarding the problem: The issue should come from this expression: Post::find($request['[postId']); You're having too many squared brackets there. It should be: Post::find($request['postId'])
Excellent Tutorials. I loved it. Please and having difficulties routing through a project am working with laravel. The links keep breaking so i don't know exactly what am doing wrong but the code looks right. routing through web.php and the i build the view with UserController but it ain't working. I need some help and i can't fine an video that explains this in details. A tutorial that talks on routing through websites links or multiple pages. it will really help out
Hey, thanks for the nice tutorial.I am newbie here and following your tutorials. Everything seems working fine but don't know why the updating is not working unless I refresh the browser myself while closing the edit form.What can be the possible reasons for this problems.
I think it's looking strange, when you view the page source, and see, for every article, some value for a data-postid attribute. I think it would be much better, semantically, to add that attribute directly to the edit anchor. And it would be much easier to set the postId variable, which, would be just $(this).attr('data-postid') - and beside that, more readable and only the logged in users can see that attribute in the source of the page. Anyways, I liked your tutorial, even though I created the app in Symfony and not Laravel.
Great to hear that and many thanks for sharing your ideas/ improvements here. I do agree that this will be a better approach, I just wanted to kind of also show how you could select some data from your HTML code. But didn't really highlight that in the video so probably not the best idea ;)
Same as others, I'm getting an error 500, internal server error. i found out that my postId is returning null to the server when updating the post so it can't find the post id. i solved this problem by changing the dataset variable name into all lowercase because i suspect that it doesn't allow a single uppercase character variable name. example: postId = event.target.parentNode.parentNode.dataset['postId']; //with uppercase I on postId, it returns null postId = event.target.parentNode.parentNode.dataset['postid']; //with lowercase i, returns the correct id.
if you get a 500 error, check the value of your PostID variable (the one inside Ajax) before you send it to the Controller. You might have some surprise
Hello, i have a problem. I got a 405 ajax error and next a laravel error: MethodNotAllowedHttpException But when i refresh a dashboard a post is updated, what's could be wrong?
I got stuck with a console error message : "TypeError: $.ajax is not a function" This was because "using slim version of jQuery... doesn't support ajax calling" I found a resolution by linking the NON-SLIM version of jQuery: PS: I commented out the SLIM JQUERY.
sir, i have a problem.... at first i used Auth controller thats why if (Auth::user() != $post->user) { return redirect()->back(); } and {{ $post->user->first_name }} doesn't work... so what formet i need to use ..... ?????
sir, i used php artisan make:auth for login and register. now in dashboard.bade.php when i use this format posted by {{ $post->user->name }} it gives me a error that is ErrorException in 0dee855c8f724e6a63b71f2de5a7c0c08a0c170a.php line 57: Trying to get property of non-object (View: C:\xampp\htdocs\myproject esources\views\dashboard.blade.php) ... what should i do now..
Do both your models (user + post) have the connections set up correctly (like in the video)? You may also (in the controller) try dd($post->user) and see if this is null. If that's the case, then the fetching of the user fails - likely because there's something wrong with your relation.
+Mindspace i had issue when i clicked remember me button and logged in then if i refresh the page i had to login again, but i fixed it somehow i dont know what was the problem. also do you gonna make a tutorial how to give a permissin to a user that is a guest? i would like to see something like that! thanks
Please help me find out I have the same code in my controller $this->validate($request, [ 'body' => 'required' ]); $post = Post::where('id', $request['postId'])->first(); $post->body = $request['body']; $post->update(); return response()->json(['message' => 'post was edited'],200); I see the message 'post was edited' in my console, but the data isn't updated. I have checked, the $request['postId'] is correct.
Does the body get passed correctly to your action? The code looks fine but you may try fetching the post like this: $post = Post::find($request['postId']);
I have tried option with $post = Post::find($request['postId']); too. In addition, the $request['body'] is correct. As I understood, $post->update(); does not work, because all other data are correct.
I had the same problem, the catch is I was using text() instead of val() when retrieving #post-body field value. p.s. I was using pure jQuery for DOM traversal and all that. Here is my code: // Select third anchor link, (it has a class 'edit-post') and attach an event handler: $('.post').find('.interaction').on('click', 'a:nth-child(3)', function (event) { event.preventDefault(); // Prevent default action. // Select data-id attribute value on the , basically select post ID :) var postIDValue = $(this).parent().parent().data('id'); // Post body element: var $postBodyElement = $(this).parent().parent().children('p').first(); // For later use. // Select post body text: var postBodyValue = $(this).parent().parent().children('p').first().text(); // Insert data into modal: $('#post-body').text(postBodyValue); // Show the modal: $('#edit-modal').modal(); // When the #modal-save button is pressed, do the ajax: $('#modal-save').on('click', function () { $.ajax({ method: 'post', url: url, // this url is set outside javascript file, in the dashboard html file data: {body: $('#post-body').val(), postId: postIDValue, _token: token} // token is also set in dashboard file }).done(function (msg) { $postBodyElement.text(msg['new_value']); // Update the post field with a new updated value. $('#edit-modal').modal('hide'); // Hide/close modal. }); // end ajax }); // end click });
what seems to be wrong with my code. after i click save nothing's happened i dunno what's wrong i certainly doubled check all the codes and compare it to you all was perfectly match but still nothing happened when i click save. thanks..
Hm, did you check the code against the code in the Github repo? Because the code there will work - you might have typo in some place in your app.js file
You'll learn more by figuring out on your own instead of copying a code snippet, therefore I'll share the required steps instead: 1) Grab data from database (or whichever data source you have) in your controller 2) Pass it to the view as a variable 3) In the view, create the dropdown () and loop through your data to create the s of the dropdown
What could I be probably getting wrong? My app is returning error 500, internal server error. i have the token setup just as you have done it. I need help
+Sheriff Shittu Hi, that's hard to say, but it's certain that the error results from the server-side (=Laravel) code. You can see the actual error message by opening up the developer tools in the browser and then in the 'network' tab (at least in chrome) you can see the past requests. The request returning the 500 response should be marked red. Click on it and then preview the response - which should be the error message. Can you then post the error message here?
Yes, but this is 500 error code, therefore there must be some error in your server-side code. And you should be able to identify the error the server throws by analyzing the network request resulting in this error. So not the error message in the console or something like this but the actual HTTP response
GitHub Repo: github.com/DannyTaki/Social-Network.git I can't seem to get the Edit Post Ajax request to work. What's wrong with my code nothing is being displayed in console and both my id modal-save and in the app.js file it is #modal-save so no issue there. Anyone can help me?
God I'm stupid! I figured it out lol. In my dashboard modal code I had misspelled the id on the 'Save Changes' button. I spelled it 'model-save' it should be 'modal-save'
hey, great tutorial. I've learned so much from it. I have a little problem, when i want to change/edit the post it doesn't change even after refreshing the page and it doesn't output anything in the console box. Here is my code, so if you could help me get pass through this i would be very grateful. github.com/funky3a/laravel-socialmedia.git
Excelent tutorials! FInnaly I learned how to use AJAX with laravel!!! Thanks for the hard work Max, I believe I can speak in the names of many, you're helping us alot to start our careers as web developers!
+Bora Manasijevic
Hi Bora, that's awesome to hear! Many thanks for your great feedback! :)
borivoje is right
thank you so much, you saved my life with your videos, may god bless you
+Sara EL MALKI
I never expected to get a life-saver with coding - but even better ;) No, I'm happy to hear that you're enjoying my content.
I find your videos so helpful, thanks a lot for sharing your knowledge and keep uploading more videos like this one!.
+Gustavo Diaz
Great to hear that, thank you!
What should I return if I have more things being updated such as like title. I wonder if :
return response()->json(['new_body' => $post->body],['new_title' => $post->title], 5000);
would work as well just like:
return response()->json(['new_body' => $post->body], 200);
By the way I appreciate for all the tutorials!
Thanks a lot for this course!
I have a question about handling those unwanted scenarios;
a) failed validation - is there some more intuitive way of passing errors through JSON instead of accumulation of those 422 statuses?
b) Redirecting in our PostController if user editing the post doesn't match author of the post doesn't have much sense because we are just returning HTML of a whole new page asynchronously, right? But then again, as you pointed out couple of videos before, this is not standard and expected but suspicious activity and UX probably shouldn't be priority...
+gh0c
Hi, interesting questions you got here:
a) You may overwrite the default error handling like this:
$validator = Validator::make($request->all(), [
'title' => 'required|unique:posts|max:255',
'body' => 'required',
]);
if ($validator->fails()) {
// Implement whatever you want to do with the errors here
// e.g. return redirect('post/create')
// ->withErrors($validator)
// ->withInput();
}
b) Yes, that is certainly not the solution you'd implement in a real app. A better way would of course be, to return some json() with an error message (status code 401 makes sense, too) and then handle this error in your client-side code. I did not pay much attention to this here, as I wanted to focus on Laravel and the server-side instead of the client-side JS part. But you are absolutely right regarding the issues, this approach has.
Thank you very much for your lessons! Before seeing your course, I could not look the other English-language lessons, as my English is not very good, but you have described is very simple, understandable, and even intonation, emotionally and with love for his work, that with you I raise my level of knowledge Laravel, and tightens your English. Thank you so much!
But in this lesson, there is a problem ... Error 500 ...
public function postEditPost(Request $request)
{
$this->validate($request,[
'body' => 'required'
]);
$post = Post::find($request['[postId']);
$post->body = $request['body'];
$post->update();
return response()->json(['message' => 'Post edit!'], 200);
}
Creating default object from empty value (error occurs on line );
What's the problem can not understand, in other design features $ post-> body operates in $ request [ 'body'] text is present. Maybe something to do with updating laravel?
Thanks in advance for your reply!
+Никита Лощенин
Hi, first of all: Many thanks for this awesome feedback and the kind words, I'm really happy to hear that you're enjoying my videos!
Now regarding the problem:
The issue should come from this expression: Post::find($request['[postId']);
You're having too many squared brackets there. It should be: Post::find($request['postId'])
+Mindspace
Wow , I'm sorry for this stupid mistake , even ashamed like that, and the IDE is not suggested ! )
Many thanks!)
Haha, no worries, this tiny mistakes happen to everyone all the time - and then it takes hours to spot since you're looking for something "bigger" ;)
Yes , yes, that is how it happens ! )
Excellent Tutorials. I loved it. Please and having difficulties routing through a project am working with laravel. The links keep breaking so i don't know exactly what am doing wrong but the code looks right. routing through web.php and the i build the view with UserController but it ain't working. I need some help and i can't fine an video that explains this in details. A tutorial that talks on routing through websites links or multiple pages. it will really help out
Hey, thanks for the nice tutorial.I am newbie here and following your tutorials. Everything seems working fine but don't know why the updating is not working unless I refresh the browser myself while closing the edit form.What can be the possible reasons for this problems.
Hi!, how did you solve your error?
I wonder why "return redirect()->route('dashboard')" is not working for refreshing the dashboard after update operation...
I think it's looking strange, when you view the page source, and see, for every article, some value for a data-postid attribute. I think it would be much better, semantically, to add that attribute directly to the edit anchor. And it would be much easier to set the postId variable, which, would be just $(this).attr('data-postid') - and beside that, more readable and only the logged in users can see that attribute in the source of the page. Anyways, I liked your tutorial, even though I created the app in Symfony and not Laravel.
Great to hear that and many thanks for sharing your ideas/ improvements here. I do agree that this will be a better approach, I just wanted to kind of also show how you could select some data from your HTML code. But didn't really highlight that in the video so probably not the best idea ;)
Same as others, I'm getting an error 500, internal server error.
i found out that my postId is returning null to the server when updating the post so it can't find the post id.
i solved this problem by changing the dataset variable name into all lowercase because i suspect that it doesn't allow a single uppercase character variable name.
example: postId = event.target.parentNode.parentNode.dataset['postId']; //with uppercase I on postId, it returns null
postId = event.target.parentNode.parentNode.dataset['postid']; //with lowercase i, returns the correct id.
Thanks for sharing this!
I'm getting an error 500 i solved it same but still error
paste your error line here
now i can solved it already i write something wrong thank you very much
a typo perhaps?
if you get a 500 error, check the value of your PostID variable (the one inside Ajax) before you send it to the Controller. You might have some surprise
Hello, i have a problem. I got a 405 ajax error and next a laravel error: MethodNotAllowedHttpException
But when i refresh a dashboard a post is updated, what's could be wrong?
I got stuck with a console error message :
"TypeError: $.ajax is not a function"
This was because "using slim version of jQuery... doesn't support ajax calling"
I found a resolution by linking the NON-SLIM version of jQuery:
PS: I commented out the SLIM JQUERY.
For your development environment, are you using Laravel Homestead, ngrok, or something I didn't list?
Hi, in this video I used my own Vagrant/ VirtualBox setup but I switched to Homestead as a Vagrant box a couple of weeks ago. So now, I'm using that.
+Mindspace Nice! By the way I love your videos because you give a in-depth view on just about everything you type.
That's amazing to hear, many thanks!
and also i want to ask what editor you use?
+john lauro I use PHPStorm by Jetbrains :)
+Mindspace oh thank you.. :D
sir, i have a problem.... at first i used Auth controller thats why if (Auth::user() != $post->user) {
return redirect()->back();
} and {{ $post->user->first_name }} doesn't work... so what formet i need to use ..... ?????
What do you mean with "doesn't work"? Which error do you get?
sir, i used php artisan make:auth for login and register. now in dashboard.bade.php when i use this format posted by {{ $post->user->name }} it gives me a error that is ErrorException in 0dee855c8f724e6a63b71f2de5a7c0c08a0c170a.php line 57:
Trying to get property of non-object (View: C:\xampp\htdocs\myproject
esources\views\dashboard.blade.php) ... what should i do now..
Do both your models (user + post) have the connections set up correctly (like in the video)?
You may also (in the controller) try dd($post->user) and see if this is null. If that's the case, then the fetching of the user fails - likely because there's something wrong with your relation.
tnx a lot sir... i solve it...........
hey good tutorials, i would like to see how to make a Remember me. i just got some issues with it
+Demonz312
Hi, great to hear you're liking it! What kind of issues do you have with it?
+Mindspace i had issue when i clicked remember me button and logged in then if i refresh the page i had to login again, but i fixed it somehow i dont know what was the problem. also do you gonna make a tutorial how to give a permissin to a user that is a guest? i would like to see something like that! thanks
Probably not in this series, but might happen in the future, sure :)
Please help me find out
I have the same code in my controller
$this->validate($request, [
'body' => 'required'
]);
$post = Post::where('id', $request['postId'])->first();
$post->body = $request['body'];
$post->update();
return response()->json(['message' => 'post was edited'],200);
I see the message 'post was edited' in my console, but the data isn't updated. I have checked, the $request['postId'] is correct.
Does the body get passed correctly to your action? The code looks fine but you may try fetching the post like this: $post = Post::find($request['postId']);
I have tried option with $post = Post::find($request['postId']); too. In addition, the $request['body'] is correct. As I understood, $post->update(); does not work, because all other data are correct.
Hm, that's really strange. Does this way of updating work: laravel.com/docs/5.2/eloquent#basic-updates ?
I had the same problem, the catch is I was using text() instead of val() when retrieving #post-body field value.
p.s. I was using pure jQuery for DOM traversal and all that.
Here is my code:
// Select third anchor link, (it has a class 'edit-post') and attach an event handler:
$('.post').find('.interaction').on('click', 'a:nth-child(3)', function (event) {
event.preventDefault(); // Prevent default action.
// Select data-id attribute value on the , basically select post ID :)
var postIDValue = $(this).parent().parent().data('id');
// Post body element:
var $postBodyElement = $(this).parent().parent().children('p').first(); // For later use.
// Select post body text:
var postBodyValue = $(this).parent().parent().children('p').first().text();
// Insert data into modal:
$('#post-body').text(postBodyValue);
// Show the modal:
$('#edit-modal').modal();
// When the #modal-save button is pressed, do the ajax:
$('#modal-save').on('click', function () {
$.ajax({
method: 'post',
url: url, // this url is set outside javascript file, in the dashboard html file
data: {body: $('#post-body').val(), postId: postIDValue, _token: token} // token is also set in dashboard file
}).done(function (msg) {
$postBodyElement.text(msg['new_value']); // Update the post field with a new updated value.
$('#edit-modal').modal('hide'); // Hide/close modal.
}); // end ajax
}); // end click
});
what seems to be wrong with my code. after i click save nothing's happened i dunno what's wrong i certainly doubled check all the codes and compare it to you all was perfectly match but still nothing happened when i click save. thanks..
+john lauro
Do you see any errors in your JS console (dev tools)?
+Mindspace uncaught type error: f[b] is not a function.. that was the error ive seen
Hm, did you check the code against the code in the Github repo? Because the code there will work - you might have typo in some place in your app.js file
+Mindspace got it already sorry for bothering.. sir do u have a code on how to populate data on dropdown? thnx sorry sir im a beginner. :)
You'll learn more by figuring out on your own instead of copying a code snippet, therefore I'll share the required steps instead:
1) Grab data from database (or whichever data source you have) in your controller
2) Pass it to the view as a variable
3) In the view, create the dropdown () and loop through your data to create the s of the dropdown
What could I be probably getting wrong? My app is returning error 500, internal server error. i have the token setup just as you have done it. I need help
+Sheriff Shittu
Hi, that's hard to say, but it's certain that the error results from the server-side (=Laravel) code. You can see the actual error message by opening up the developer tools in the browser and then in the 'network' tab (at least in chrome) you can see the past requests. The request returning the 500 response should be marked red. Click on it and then preview the response - which should be the error message. Can you then post the error message here?
+Mindspace here is the error code: jquery-1.12.0.min.js:4 POST singles.dev/edit 500 (Internal Server Error)send @ jquery-1.12.0.min.js:4n.extend.ajax @ jquery-1.12.0.min.js:4(anonymous function) @ app.js:15n.event.dispatch @ jquery-1.12.0.min.js:3r.handle @ jquery-1.12.0.min.js:3
And my code:
$('#modal-save').on('click', function() {
$.ajax({
method: 'POST',
url: url,
data: { body: $('#post-body').val(), postId: postId , _token: token}
})
.done(function (msg) {
//console.log(JSON.stringify(msg));
$(postBodyElement).text(msg['new_body']);
$('#edit-modal').modal('hide');
});
});
Thanks
Yes, but this is 500 error code, therefore there must be some error in your server-side code. And you should be able to identify the error the server throws by analyzing the network request resulting in this error. So not the error message in the console or something like this but the actual HTTP response
+Mindspace Im having the same error message, and i am not able to solve it. Awaiting your response. Thanks
The same response as before applies to you: I'm no magician, I need error messages. And above I describe where you should be able to find one
GitHub Repo: github.com/DannyTaki/Social-Network.git
I can't seem to get the Edit Post Ajax request to work. What's wrong with my code nothing is being displayed in console and both my id modal-save and in the app.js file it is #modal-save so no issue there. Anyone can help me?
God I'm stupid! I figured it out lol. In my dashboard modal code I had misspelled the id on the 'Save Changes' button. I spelled it 'model-save' it should be 'modal-save'
also the ajax code :
$('#save-changes').click(function(){
$.ajax({
method: 'post',
url: url,
data:{body: $('#post-body').val(), post_id: post_id, _token: _token},
success: function(result){
console.log(result['message']);
}
});
});
Hi, Not Updated Data
Route::post('/edit',[
'uses' => 'PostController@postEditPost',
'as' => 'edit'
]);
public function postEditPost(Request $request)
{
$this->validate($request,[
'body' => 'required'
]);
$post = Post::find($request['postId']);
$post->body = $request['body'];
$post->update();
return response()->json(['message'=>'Post Edited'],200);
}
hey, great tutorial. I've learned so much from it. I have a little problem, when i want to change/edit the post it doesn't change even after refreshing the page and it doesn't output anything in the console box. Here is my code, so if you could help me get pass through this i would be very grateful. github.com/funky3a/laravel-socialmedia.git
+madfranclan
Your selector is wrong. You use $('#modal.save') but in your HTML code, you have: id="modal-save"
+Mindspace Thank you for the help.