Likes for multiple posts on page - laravel

I am trying to workout how to like a post with Vue and I understand the basics of it using axios to do some Ajax and Vue to do some changes to the DOM that reflect the current state.
But so far I have only tried single post. What happens if I have multiple posts like this on one page? How do I manage the Ajax calls? And most importantly how would I make the Vue handle each post independently in terms of DOM changes?
I'm new to this so if someone would drop some dummy code to clarify this problem, that would be super helpful, thanks.

When requesting your posts to your page, via a GET method I suppose, pass a unique identifier to each post, the id would work perfectly here.
Make you controller work so as to add entries to a pivot table that contains the id of the user and the id of the post. When writing your logic for the like function, make a vue method that has as an argument the id of the post, and pass that key in the data of an axios post request and do the processing in Laravel as you'll normally do.

Related

How should I update a component and non-component from an AJAX call?

Sorry if the question is confusing but I am just getting started with React. Basically, I am looking to start adding individual components to an existing website. Currently, when the page loads there are a couple of AJAX requests that update different parts of the page with jQuery.
For example, I make an AJAX request that is called every 30 seconds to get AccountInfo and when it returns a response, I update two separate parts of the page, let's call them AccountPanel and SideBar.
Question #1
If I were to create a component for the AccountPanel, should I make the AJAX request when the component mounts and continue to use jQuery to update the SideBar in there?
Question #2
Or is it better to create components for both and pass the AJAX response as props?
ReactDOM.render(<AccountPanel />, document.getElementById('accountPanel'));
ReactDOM.render(<SideBar />, document.getElementById('sideBar'));
Any help is appreciated :)
Actually, I think you need some state container. To share state(in your case AccountInfo) between all of your components.
Personally, I recommend using Redux. Because this container is completely predictable.
In result you code will looks like:
//create redux store somehow
ReactDOM.render(<AccountPanel store = {resuxStore}/>, document.getElementById('accountPanel'));
ReactDOM.render(<SideBar store = {resuxStore}/>, document.getElementById('sideBar'));

Dynamically add form to formset in Django and submit with AJAX

I have read a lot of answers relating to how to dynamically add forms to an model formset in Django and can successfully implement that. However, I would now like to submit the formset with AJAX. This is mostly working now but I have an issue that I can't find a solution to in any other answer:
If you dynamically add a form to the formset, you give it a new form id number that is one larger than the maximum the form currently has and you also increment the management TOTAL_FORMS count by one. The newly added form then saves successfully as a new object.
I am trying to submit by AJAX so the user can continue editing without having the page refresh. The formset saves fine but any dynamically added forms are now existing objects. To account for this I need to increment the INITIAL_FORMS count on the management form when the save is successful. Easy enough. However, I've also realised I need to give the newly created objects an ID since they now exist in the database.
How can I get my view to tell me the ID of the new objects in its response to the AJAX call? Or is there a better way of looking at this?
Django forms and formsets are intended for classic browser-based posting of data. Though they can definitely be made to work with Javascript, the more you want to part from the normal behavior, the more complex it gets.
Depending on your requirements, you might start thinking about dropping it and switch to Javascript + REST endpoint. Of course, if you need progressive enhancements and you are required to have it work without javascript, that's not an option.
In any case, you want to have a customized view for posting from JS, so that you can get the result back and parse it easily in your AJAX handler. Probably some JSON.
There are several approaches you could take.
Have your AJAX send data to a different URL. This is pertinent if you have an API or are planning to build one at some point. So your form, when submitted normally, will do its old-style processing but your AJAX will talk to the API endpoint instead.
For instance, your form send to https://example.com/myform, but your Javascript code talks to REST api at https://example.com/api/v1/mymodel/ (sending PUT, POST and DELETE requests as appropriate).
Or if you don't have an API and building one seems overkill, you may just alter your view so it formats its output differently depending on whether the data is being submitted in the regular way or using AJAX.
You'd go about it like this:
class MyFormView(.....):
def render_to_response(self, context, **kwargs):
if self.request.is_ajax():
return self.render_to_json(context, **kwargs)
return super().render_to_response(context, **kwargs)
def render_to_json(context, **kwargs):
data = {
# see below!
}
return HttpResponse(
content=json.dumps(data).encode('ascii'),
content_type='application/json',
)
This is just an outline. You need to ensure is_ajax will detect it properly (see django doc). And you need to properly build data from context: extract the things you want to send back to your JS code and put them in the dict.
You will find it's manageable if you just do this for one, maybe two views in your project, but very quickly you'll want to have a small API instead, especially given how easy it is to build one with packages such as Django REST framework.
In your view, where you save the object, AFTER the save, the object.id will contain the new id for the object, which you can return via json or however you want in your ajax response, and then yes you will need to fill that into the formset row so that it will be submitted the next time.
One thing you have to watch out for is that django expects all existing rows to be at the top of the formset, and any new rows to be at the bottom. Otherwise, the formset save will complain about missing id's. So if you're doing any kind of sorting in your javascript, you can't do that.. unless you do quite a bit of fixing of all the field names etc in the formset. The formset code uses the numbers in the management form to determine which rows to insert and which rows to update, it does not do it on the basis of whether or not an id is present. Unfortunately...

Is it normal that inputs (generated by html helpers) are influenced by POST data?

In a MVC app we implemented a mini forum. New posts in this forum are ajaxed. The AJAX POST action either returns a response form (partial view) or new post html and form html as a JSON.
New post and form are both rendered from views by this method. The model provided for the form has some null values, but the corresponding inputs store values taken from POST data (I verified the generated data to make sure it's not something that is done by the browser). The inputs are generated by html helpers (such as TextBoxFor).
So my question is, is this normal behavior in MVC and if it is, then how do I go about making those inputs have empty/null values (or even some specific value)? When debugging the values in the model are exactly as I set them (which is null, but same thing happens for any value really), but inputs for this very model still hold values taken from POST data.
I tested how does this work with good old PartialView instead of rendering html to string and returning it through JSON, but the results were exactly the same (so the method I use for rendering those views should be unrelated to the problem).
I came across this question: View data dictionary overriding model data in ASP.NET MVC
But from what I checked in my app, the POST data isn't actually stored in ViewData and the OP wasn't AJAXing data so redirects made more sense in his case.
I came across this post which explain this problem in detail and shows ways to deal with it.
To sum it up. Yes, this is normal behavior of htmlHelpers during POST action. To prevent it you can run ModelState.Clear(); in your post action (preferably just before you return\render the view). Optionally it is also possible to remove just one field using ModelState.Remove("PropName"); where PropName is the name of the model property which you don't want to be passed from POST data.

Codeigniter - change url at method call

I was wondering if the following can be done in codeigniter.
Let's assume I have a file, called Post.php, used to manage posts in an admin interface.
It has several methods, such as index (lists all posts), add, update, delete...
Now, I access the add method, so that the url becomes
/posts/add
And I add some data. I click "save" to add the new post. It calls the same method with an if statement like "if "this->input->post('addnew')"" is passed, call the model, add it to the database
Here follows the problem:
If everything worked fine, it goes to the index with the list of all posts, and displays a confirmation
BUT
No the url would still be posts/add, since I called the function like $this->index() after verifying data was added. I cannot redirect it to "posts/" since in that case no confirmation message would be shown!
So my question is: can i call a method from anther one in the same class, and have the url set to that method (/posts/index instead of /posts/add)?
It's kinda confusing, but i hope i gave you enough info to spot the problem
Cheers!
Use the redirect() in conjunction with CodeIgniter's Flash Data, or opt for AJAX.

Form from another model in a view

So I'm trying to extend the Blog tutorial adding some comments:
Post hasMany Comments
I want to display the add comment form in the same view as the 'post view'. Thing is I don't know the best way to get this approach. I thought about three ways:
Creating a function in Comments Controller to handle the data.
Creating a function in Post Controller to handle the data.
Deal with the data in the same function that deals with the post views.
The main problem with the two first 'solutions' is that the validation errors doesn't show up in the form unless I do some messy hacking of saving the invalidated field in a session variable and then parsing the variable on the beforeFilter callback, like this:
function beforeFilter () {
if ($this->Session->check('comment_error')) {
$this->Post->Comment->validationErrors = $this->Session->read('comment_error');
$this->Session->delete('comment_error');
}
}
What I basically do is adapt the invalidated fields to the actual view and allow it to show properly. This works really well, but it seems so ugly to me. What would be the best approach?
Another related question: should a controller reflect a view? I mean on that example, I thought about only having a Comment Model and dealing with all the data in the controller where's the form to add a comment (even though it's in the Post Controller).
Sounds like you're looking for the Mutlivalidatable behaviour: http://bakery.cakephp.org/articles/dardosordi/2008/07/29/multivalidatablebehavior-using-many-validation-rulesets-per-model
This allows you to define more than 1 validation ruleset per model. Use your controller to determine which one to apply upon posting something.
P.S. I have only ever used this on a Cake 1.3 project, not sure if it'll work on 2.0.
I see it this way:
Under every post there is an input box "Add comment" with a button to submit.
After submitting some text a form redirects to comments_controller where the comment is saved with this post_id, body, author, date etc.
After the comment is saved and all the logic is done it takes you back to the post.
Under each post there are all related comments displayed (having the same post_id sorted by date or whatever).

Resources