Jquery/Ajax/HTML assistance needed - ajax

I am trying to build a very basic message center. My idea is to use Jquery to make an ajax call to a classic asp page that will build a Json array.
I then plan to use Jquery to grab that Json.
My main questions currently are:
Is it possible to empty out a multi select input list?
Would it be better to not use the input at all and build a nifty Jquery list?
Will using Ajax allow me to on the fly empty this list; replace with with different information and/or append items to this list all without a page refresh?
I need to be able to allow the client to select multiple people from this list. Is my outline above feasible?
Is it a good way to achieve what I am looking for?
I have very little experience with Json and Ajax, and was hoping someone could confirm if it was possible before I dive in.

Is it possible to empty out a multi select input list?
Yes
Would it be better to not use the input at all and build a nifty Jquery list?
You can have this work with any kind of element, including a standard input.
Will using Ajax allow me to on the fly empty this list; replace with with different information and/or append items to this list all without a page refresh?
Yes, in a function that handles the response of the Ajax call and uses call's result to populate the list. Since you're using Ajax, the call is asynchronous so the entire page will not be refreshed as a result of your call.

Related

Best way to output the content i load from ajax

I want to load objects with ajax and then for every object make with options.
What is better to do when i load content from server via ajax:
put everything in a string variable (including html tags) named output with += and put it on a loop for each object,then append it.
append an output for every object i load in a div
or a better solution
if there is a better solution is there anyone who can help me ?
Well that really depends on a technology stack that you are using.
But in essence it is exactly what is going on.
You have some array of products coming back from an ajax request.
You want to clear out the contents of the area where you are inserting those.
Then you wanna iterate over your collection of items and using some kind of template generate an html for each one. the simplest one in plain java script would be string concatenation.
then you concatenate them all and insert the result as innerHTML inside your container.
It may be ugly for a start but as you will learn more - you will improve.

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

Creating dynamic web forms on the client side

Is there an existing library that would do this?
I want to be able to have code on the client side where the user chooses something, it makes a call to the server, and the server sends back "for this option, you need a have a text field called foo and a select field called bar with the following options, this one is selected, etc", and then the client side builds the next part of the form from that information. Or if they choose a different option, a different set of fields and values is returned from the server and populated on the screen. Also it might cascade so after the first selection we need a select field with some options, and then depending what they select on that select field the next field might be another select field or it might be a text input field.
Has anybody done anything like that? Is my best choice to have the AJAX call return some html that I just stuff into a div, or can I do it field by field and value by value?
If it matters, the back end is going to be written in Perl/MASON, and the front end will be using Javascript/JQuery/JQuery-UI.
I would use jquery and submit AJAX calls to whatever backend system you choose. Have this backend system compute the necessary changes and return the info as JSON. Let JQuery parse it for you and append the necessary form elements. However, it seems like under alot of use cases these decisions could be made on the client side without even talking to the server just as we pre validate form input before allowing posting to the server. I don't, however, have your requirements in front of me so I am sure there is a reason you want to get the info back from the server.
P.S. please do not return pure html from the back end to the client....ever.

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.

What is the best way to do this in ASP.NET MVC3?

I want to have a form which has a simple 2 step process:
(If a person on has one school assigned to them then skip straight to step 2)
Step 1 - Select a school from a drop-down list
Step 2 - Enter the required data from a data-entry form. Certain fields are disabled based on which school was selected.
I have had a look at the various methods for creating 'wizards' and at using partial Views. What is the best way to handle this? I was wondering if using AJAX is worthwhile considering or just having a two step process in the form.
James :-)
You should absolutely do this via ajax so your options are either
use small partial views. your view logic determines what to disable/enable
(probably easier and more lightweight) use json to get a list of property names to disable.Then you can simply disable them via jQuery ideally by iterating through each item with the .each() call.
See: looping through JSON array in a jQuery list
for a use of the each call.
got jQuery getJson, see: http://api.jquery.com/jQuery.getJSON/
so:
1. getJson to get the results from a controller
2. enumerate using .each() and set the property
$("#" + yourFieldName).attr("disabled","disabled");

Resources