Is there a better way to update user view instead of refreshing? - javascript

In the database I have something like Line, Word and Character. That is, a Word must belong to a specific Line, the same goes for Character (or you can think of a multi-level menu, each menu item can be another menu). I'm writing a management page to interact with the database. Each time the user insert/delete a record, the page must be refreshed to show the changes. However, this approach is too annoying for my users (although the refresh is automatic). Is it possible to show the changes without refreshing the whole page? If it is, how? Thank you.
UPDATE: The data is shown as multi-level list (the picture below is an example) and can be collapsed/expanded. When I refresh the page, they are all collapsed (which annoys my users).

You can do it using AJAX(Asynchronous JavaScript And XML). You can update a web page without reloading it using ajax. You can use jQuery ajax() which is so simple to integrate. http://api.jquery.com/jquery.ajax/
Here is an example-
$.ajax({
method: "get",
url: "/action.php",
data: {item_id: item_id, vote: vote},
dataType: "html"
})
.done(function(msg){
// Update view of the web page, it could be deleting or updating a div
})
.fail(function(msg){
alert(msg);
});
/*
method - get/post
url - which will handle your request
data - data you want to send to server
dataType - response type, html/json/text etc
*/
If it works without any problem then the done method will trigger otherwise fail method will trigger.

If you are saying something like a live suggestions display while you type on the search bar. The ajax. If you just want to show the newly updated record on the be view page, a redirect would do

Related

JavaScript: how to pass additional information to source page?

I have a website and when a user follows an internal link I would like to pass some extra information to a new page, so JavaScript on the destination page could do some useful highlighting.
There is an option to pass that information via the link parameters (GET), but it will generate lots of virtually duplicate pages and break pretty URLs concept. Another way is to make a webapp using AJAX, but it will also bound content to a single URL.
How can I transparently pass some information to the new page during navigation w/o messing with site's URL structure?
You could store the data in local storage or session storage, and retrieve it again on the destination page.
So you have a few options.
Form Submission
First option post a form with the data. Add a hidden form, on the anchor click capture the click event, set the hidden fields with the values you want to send to the next page, and submit the form. On the next page, read the post parameters in the backend and update the page.
Local Storage
On click of the anchor, set localStorage to the values you want to appear on the next page. When the next page loads, read the localStorage values and update the page. Note: The server will not have access to the values
Ajax with pushState
Use Ajax to submit the form. When the Ajax call returns, use window.history.pushState to update the url with whatever url you want to be displayed to the user.
One of the options not mentioned is to create a dirty URL:
/destination/param1/value1/...
then strip additional parameters at server-side and redirect:
/destination
keeping additional values stored at server-side (e.g. via sessions). I still prefer using sessionStorage in a real application, but it worth mentioning anyway.
What do you mean it will "bind content to a single url"? AJAX request is the first thing that comes to my mind as the solution to this problem. You dont have to use the url of the page to make the ajax request, you can build the url inside your javascript based on whatever conditions exist in your application.
Besides AJAX and passing parameters in the URL, the only other thing I can think of is to use Cookies. That of course runs into problems if the user has cookies disabled. I think an Ajax call to your server is the most robust way of handling the problem.

How to save/cache the dom so that the page loads as-is when you hit the back button?

i add models to my js app model collection using ajax calls. when i click a model and go to the next page, i want all the models i had loaded to still be there when i hit the back button. what is the best way to do this so that it works on all browsers? this is for mobile web. i can't find a straight answer, how do i use bfcache, or js history, or is there another, better way?
You can store them in the local Storage and ajax for them only if the do not exist on the local Storage
So instead of using the regular $.ajax , use this for the ajax that you want cached:
function storageBasedAjax(url,cb){
if (localStorage.getItem("myAxaxCache_"+url)){
cb(localStorage.getItem("myAxaxCache_"+url));
return;
}
$.ajax({url: url, success: function(result){
localStorage.setItem("myAxaxCache_"+url,result);
cb(result);
}});
}
Just remember you do not want to over load, so if you have a url with a parameter changing each call,do not use this or you will overload the local storage

Django/Python: Use file uploaded by the user for two different view methods at different times

I have a form in my template. The user uploads a file and when this is submitted i call a view method via an Ajax call because i do not want the page to reload, this works fine.
$("#formi").submit(function(event){
event.preventDefault();
var data = new FormData($('form').get(0));
$.ajax({
type:"POST",
url:"{% url 'do_some' %}",
data: data,
processData: false,
contentType: false,
csrfmiddlewaretoken: '{{ csrf_token }}',
success: function(data){
...},
The problem comes when i want to call another view passing the same data (file uploaded) but i do not want the user to upload again the file. I will try to elaborate on this:
Say you have a form, the user uploads a file, submits it and two new buttons appear on the screen. With this two new buttons now you can move around the page (right or left). Press right button and from "Home" page you move to "About" page, but the page do not reload, it is all in the same HTML.
Calling one big function to fill the "About" page, the "Contact" page, etc on the first submit of the form takes a lot of time. I want to use the data to fill the first page quick, then the right button is clicked and fill the next page quick, etc. What i want to do is to "save" that data somewhere and use it when the, for example, "right" button is clicked.
WARNING
I DO NOT USE DATABASES FOR THIS WEBPAGE. THE DATA THE USER PROVIDES IS SENSIBLE SO IT CANNOT BE STORED. It will dissapear when the user exits the page
SO, question: Is there a way that i can use the same data i get from the form in another button? Maybe use that button as a second form and pass the file from the first form to this one and "submit it" when is clicked? Save this file in my python code and use it only when that button is clicked?
Is there a way to delay the ejecution of a view method so the code do not run all together?
Maybe this is an easy question and i am thinking too much
Thanks in advance.
If you wan't to process that uploaded file later, you must save it somewhere, either in database, on hard drive or in cache. You can't rely on some global django varialbe because there is no guarantee that it will survive between requests (workers, threads on entire WSGI serwer can be reloaded between requests, depending on your WSGI server settings).
If you want to ensure that nobody will retrieve that file from your server, you can encrypt it. On file uploading, encrypt it using some random string and save that encrypted file on your server, send back in response encryption key (you can save it in users cookies for example) so any requests that will use that file again must contain proper key.

Remove POST data when using custom javascript back button

I've coded some custom navigation buttons into the project I'm working on, via javascript - they essentially copy the browser button functionality (brief wasn't initially clear on why separate buttons were required, but they asked for them):
function goBack() { window.history.back(); }
function goForward() { window.history.forward(); }
However, as the functionality is the same as the browser back button, the website asks if I want to resubmit POST data if I go back to a page with said POST data, which is undesirable. Ideally, to fit with the current site setup (all POSTs submit to the originating page, which checks for POST data and performs the relevant submissions to the database), I want to clear the POST data so there is no request to resubmit.
I'm not familiar with the Post/Redirect/Get (PRG) that people might recommend, and it doesn't seem to cover the concept of continually pressing "back"; if you submit a form, you post to a page which handles the post action, then redirects to a GET page - but the redirect is still in the history, meaning if you go back, surely you would hit the redirect page and just be sent "forward"? Plus, PRG seems mostly centred on page refreshing, which is not what I'm looking for at the moment.
The concept of PRG also seems to be due to the browser back button not allowing for additional code to control POST data, so coders have to make the best of what they can access.
With my relative freedom of having a custom back button which could allow for manipulation of POST/session/cookie data, I'd consider there should be some method of calling a global session variable or cookie on back button press, which then gets picked up on the previous page load to unset the POST data and the global session variable/cookie, but my attempts to implement something like this have not succeeded - they've been simple single-line setcookie('back', true) or set($_SESSION['back']=true) PHP snippets within goBack(), with PHP earlier in the page:
<?php if (isset([either set cookie or set session variable]) {
unset([either set cookie or set session variable]); // also tried changing 'true' to 'false' here
unset($_POST);
}?>
Is this kind of behaviour possible and I'm just looking at this from the wrong angle, or is the only way to do a successful back action while suppressing POST to re-engineer the site to use PRG, which will be comparatively significant legwork? Is there some other point in a page load/POST submit that would allow for clearing the POST data, to allow for the back button functionality I'm looking for?
EDIT
I, as an example, navigate to site.com/stuff/edit/[an ID], to edit an item of stuff. The first time I visit, there is no POST data, so the PHP check of isset($_POST) returns false and the page is simply rendered with a form which is populated by a GET.
I amend in the form and press submit. The submit sends the POST data to the target page; this is STILL site.com/stuff/edit/[an ID]! However, because there is now POST data, the PHP picks this up, validates it on the page (you'll see why later) and performs backend model and controller functions to update the item to the database serving the site.
Depending on whether the update was successful, the page then renders the form again, with the information which is retrieved from a GET, which pulls the information from the server (amended or otherwise) and either a success or fail message.
If I want to add a new item, I navigate to site.com/stuff/new; this navigates to the same page as site.com/stuff/edit, but PHP code determines the masking URL and renders different aspects of the code to look like a different page with a different POST action - it also notes there is no ID passed in.
I add an item, and the POST redirects back to the same page; this time, though, there is no Id from the server, meaning the code behind picks up the fact it is a new entry, and performs an insert. It then either displays a success message with a link to view/edit the new item, or a failure message with a prepopulated form to reduce retyping the new item into the form.
I hope this has helped show how this page works; its not necessarily how I would have written the site, but I've inherited the work from an ongoing situation and work with others who code in this way, so I need to be consistent or make unobtrusive changes rather than radical redesigns of in-use code.
I think this should do the job:
function goBack() {
var referrer = document.referrer;
if(referrer != '') {
window.location = referrer;
} else {
window.history.back();
}
}

How to get javascript pagination data via jquery?

I need a web sites some data which I want to parse via jquery. I am able to do everything except the pagination which contain javascript anchor link.
(source: grinshare.com)
2
I want to load the second page (certain selector, say "p #listo") in a paragraph in the 1st page via ajax. Can I do this via ajax? if it is possible, please can you share the code..
Thanks in advance..
Note:
I want to get the 2nd page via ajax...I tried a lot things....
$.ajax({
url: __doPostBack('grdResults$ctl29$ctl01',''),
success: function(data){
//Some function I will perform
}
});
But it reload the page...if I use quotation for url it give error... I tried get, load, post but unable to do it...
You need to have a URL that outputs data and handles pagination on the server side. For example, it could be /mydata/page/3/, and it would grab page 3 of the data and return it in some format (JSON, XML, YAML, whatever).
Then, you can have jQuery send an ajax request on click of each of the items in the pagination controller instead of running __doPostBack().
Switching to ASP.NET MVC would help you.

Categories