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

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'));

Related

How to fetch data before component mount in Svelte?

Unlike onMount there is no beforeMount lifecycle event in SvelteJS. So, how do we fetch data that the page depends on before mounting? onMount fetches produces glitches. One can say that I can wrap dependent DOM inside if conditions. But I don't think it is the right solution. Very like in Sapper there is a preload function that can load page dependent data before mounting. What is the alternative to this (Sapper's preload) behavior in SvelteJS?
You'd create another component that doesn't render the Component until the data is ready.
<script>
import Post from "./Post.svelte";
const url = 'https://jsonplaceholder.typicode.com/posts/1';
const promise = fetch(url).then(response => response.json());
</script>
{#await promise then data}
<Post title={data.title} />
{/await}
REPL
Depending on the scenario you can use a router that has data loading supports, like the sveltekit router.
You can put the fetch code right under <script> tag
A <script> block contains JavaScript that runs when a component instance is created.
There is also context="module" attribute with <script> tag. It
runs once when the module first evaluates, rather than for each component instance
See the official docs
Noob here, to your sub-question: isnt svelte front end only? Meaning no SSR support and thus no option for preloading data with first user request.
Since, you dont have any server that would preload your data and give the user prepacked front-end (svelte pages) with data. Thus, you need sapper to provide a functionality where server can fetch data with first user request, populate front end and send it to user.. This way, user receives svelte pages, populated with data, upon first response from your server.
Since you use only svelte, user needs to contact your server more often.. First, it fetches the front-end, then front-end fetches data from back-end. Furthermore, it aint SEO friendly as robots dont wait for the subsequent server responses. Thus, your pages wont be analyzed properly as robots analyze 'blank'page, no data mounted yet, and move to next, before response can be processed.
Please, correct me If I am wrong ;)
I believe above answer is right:
1. create empty variable in script tag
2. add below onMount call and fetch data from serverto above declared variable
3. check if var is empty and show loading button
4. if var isnt empty, then show user content
6. profit?
P.S: Sorry for any misconceptions or bad English :)

Likes for multiple posts on page

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.

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...

Client side to server side calls

I want to change the list of available values in a dropdown depending on the value selected in another dropdown and depending on values of certain fields in the model. I want to use JQuery to do this. The only hard part is checking the values in the model. I have been informed that I can do this using Ajax. Does anyone have any idea how I will approach doing this?
AJAX is indeed the technology your looking for. It is used to sent an asynchronous request from the client browser to the server.
jQuery has an ajax function that you can use to start such a request. In your controller you can have a regular method tagged with the [HttpPostAttribute] to respond to your AJAX request.
Most of the time you will return a JSON result from your Controller to your view. Think of JSON as something similar to XML but easier to work with from a browser. The browser will receive the JSON and can then parse the results to do something like showing a message or replacing some HTML in the browser.
Here you can find a nice example of how to use it all together.

Is it possible to send a form and a html request with same Event by Mootools?

$('submitbutton').addEvent( 'submit', function(e){
e.stop();
$('fuss').send();
req2.send();
});
trying to get this working but not sure if it is possible and had no success so far.
Mootools docs doesnt helped me either.
Will the multiple usage of .send() work?
Do i have to specify the data beeing send for the html request or does it take automatical the data beeing send by the form ?
It's in the documentation: http://mootools.net/docs/core/Request/Request#Element:send
This shorthand method will do a request using the post-processed data from all of the fields.
You can do as many requests in a specific event as you wish, as long as they're all asynchronous.
In your specific example it would seem you want to do two requests using two different methods, one with setting up a new Request class manually and the second doing it via the Element Method.
Based on your last comment, I wrote a little example in jsFiddle.
Basically I think you don't need two request for your goal. Just override onRequest method to update the html.

Resources