Execute JavaScript on Django Page through URL without reload - javascript

i have a webpage that loads certain JavaScript packages.
www.mySite.com
If i enter JavaScript commands in the browser console, i am able to interact with them.
Lets take
alert('5')
as a simple example.
I would like the same JavaScript calls to be executed without the browser console but through a specific URL like:
www.mySite.com/?value=5
so that this leads to an execution of my JavaScript commands?
Without the Page beeing reloaded/refreshed but staying in the actual state.
My approach was to catch the extended URL in my Django View and execute the JavaScript command.
View:
class ShowPage(View):
def get(self, request, caseId):
value = request.GET.get('value', '')
if(value is not ''):
// execute JavaScript here...
return HttpResponse("<script>alert(" + value + ")</script>")
else:
...
return render(request, 'template.html', context)
But this leads to a loss of my page where i entered the URL.
Does anyone has an idea how to preserve the actual Browser content?
So that it is possible to call the loaded Javascript packages?
Another idea was to call JavaScript through Ajax. But how do i map a URL in Django to a Ajax request?

Your current code is problematic on many levels, particularly because it allows the user to execute arbitrary JS on your page. This is called a Cross-site Scripting (XSS) attack.
Another issue is that you seem to want to add a GET parameter without "changing the state" of the page. Here you must remember that a GET request is, by definition, a communication between the client and server. You can artificially change what the URL looks like using JS, but you cannot submit a GET request on the same page without reloading it.
This is why you certainly want to use AJAX, which allows you to fetch the contents from another page and return them to the current page in the background. Usually this is done by creating a view that returns a JsonResponse (in Django 1.7+) (see Creating a JSON response using Django and Python).
A simplified example would be to encode a view that simply displays some text. You could then retrieve this text using AJAX (I recommend the jQuery for this--it's simple and well-documented) and do whatever you want with it, including alert it.

Try to use a '#':
www.mySite.com#command
This doesn't reload the site.
Maybe this helps too:
url: https://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
url: Get current URL in web browser
'#': http://www.w3schools.com/html/html_links.asp
EDIT:
use 'eval()' to execute the input:
http://www.w3schools.com/jsref/jsref_eval.asp

Related

Refreshing page via JS snippet

While testing a way in Firefox to reload an HTML page without caching, I've included the following snippet in my code:
<script>
window.setTimeout(function () {
location.reload(false);
}, 5000);
</script>
This reloads the page after 5 seconds, however I get shown the prompt: "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier."
If there a way to do a silent refresh via Javascript, one that doesn't show any prompt? For instance, if I used the refresh Meta tag (HTML), my browser silently refreshes. I want to approximate that same experience, but via JS (and no cache). BTW mine is a Django web app, and I inject the JS code in my Django template.
This is standard behaviour to protect people from submitting form information more than once (eg, prevent double payments in an ecommerce system). Try telling the Javascript to direct to a 'new' page:
Try using this, setting the url to your own;
window.location = "my.url/index.html?nocache=" + (new Date()).getTime();
Answer borrowed from here where there is also an explanation given for why this works -> How can I force window.location to make an HTTP request instead of using the cache?
Have you tried location.reload (true) ? If set to true, it will always reload from server. Set to false it'll look at the cache first.
You are getting this prompt because you ask to reload a POST request. You should always get this prompt when reloading a POST request, as it is not a safe method
However, if you wish, you can explicitely resend a POST request (though you might have difficulties to find back the POST data previously sent). Or explicitely send a GET request to the same URL.

Django modify model instance from HTML

I want to know if it is possible to directly modify and save a model instance in the HTML Template and not via a view and extra URL.
My user has a Boolean Property, I want to display it as a toggle button on the website and the user should be able to toggle it on or off without leaving the website or reloading it.
class User(AbstractBaseUser, PermissionsMixin):
...
autoplay_enabled = models.BooleanField(default=True)
...
Is this possible without an extra view or form?
Basically I just need to set
request.user.autoplay_enabled = False (or True)
and then save() it
If I can't modify the object directly in the HTML template is it at least possible to just execute a function I have defined somewhere in my Python code, without having the need to create a new view?
What you're asking doesn't make any sense at all. HTML is just sent to the browser for display. You can't do anything "from HTML" without making some kind of request to the server, and the server won't do anything unless that request is received by some code - eg a view connected to a URL.
If you want something to happen without refreshing the page, you need to use Ajax. You can use a simple Ajax POST to a view that toggles the value and saves it - it only needs a dozen lines of code between front and back end.

When is a postback not a postback? (according to ASP.net)

Is there a difference between me using Javascript to redirect to URL + "?Querystring=value" versus using whatever mechanism ASP.NET uses?
If there is a difference, how can I make the rendered ASP.NET page be submitted to the same URL with a different query string by javascript?
If you want to do a post back just like a asp control like a asp:Button you can use the javascript functions included by the framework to do so:
__doPostBack('ControlIDOfEventYouWantToRaise','');
You can read more about the __doPostBack in this article:
Doing or Raising Postback using __doPostBack() function from Javascript in Asp.Net
Just doing a form.submit() will not be exactly the same as using __doPostBack.
To answer the first part of your question there is no difference doing a redirect if you are just doing a Response.Redirect as the will both do a GET. The difference is if you use a asp:Button control for instance, it will access your page first to handle the button (a post back) and then do a GET on the redirected page.
If you want to submit to the same URL (eg post your data) then you should use the __doPostBack method. If you don't require the data to be posted, then just do a redirect in javascript to the same URL with a modified query string (which will just do a basic GET) but your data will not be posted.
The only potential difference is that a querystring parameter is sent via GET, a form is (usually) sent by POST.
GET has a much smaller data limit as browsers have a max URL length (it varies)
You could use javascript to do a form.submit() which shoul emulate what ASP.Net does
I somewhat disagree with Basiclife's answer; if you have any code inside something like
if (IsPostBack) {
it's not going to be equivalent, ie the code is going to be executed if you're just setting the URL. Also, controls keep their state across postbacks but are freshly initialized if you're calling the URL again. This is due to ASP.NET trying to emulate a "normal" application, so the way to make sure a normal call and a postback have the same effect might result in "de-ASP.NET-ing" the entire page.
I'm not sure if what you want works. There probably is a way. But I heavily suspect there's a better way of doing this. If you get a postback for free, and can transmit data, why is it crucial that the data shows up in the URL, instead of being comfortably posted? I can see how you want a page to respond to a URL parameter, and how you might want to change the same parameter later on based on what's happening on that page, but since you always know you're posting back, you can eg override that URL parameter in that case, by something you're posting back. This doesn't sound so nice, but it might actually be less messy. Particularly since you seem to have a reason to not abandon the postback at all (otherwise you could just use a link, right?).

Javascript function execution on link click?

I have a link, that when a user clicks on it, it loads a different page as normal but also executes a JS function that autofills a specific text-box on that different page. Is it better practice to use Jquery or Javascript to do this? How can I do this using either one of them?
You can't do this from the source page.
It's a security feature. Imagine if you wrote a JS function that went to an online banking page and auto-filled a bank transfer using the user's current cookie. That's why you can't.
If you control the other page then the sequence you can use is:
Save data to the server;
Go to the new page with a JS redirect;
The new page is loaded from the server;
While loading th epage the data that was saved from the server is retrieved and used to populate the text box.
So it can be done from the server but only if you save it there. The only way of doing that is using Ajax.
An alternative approach is:
Instead of a JS redirect, submit the page back to the server;
The server saves whatever data it needs to;
The server sends back an HTTP redirect to the new page;
The new page uses the saved data to construct the new page with the populated text box.
At the end of the script add return false;. This will make the page run the script without redirecting the page.
Edit: (after saw your edition).
Is it better practice to use Jquery or Javascript to do this? How can I do this using either one of them?
jQuery is a javascript library, this it doesn't matter if you use plain javascript or use jquery as long as you happy with the result.
And about what you say that you successfully manipulated a page fro the redirecter page... I don't see how it possible.

To build a `Delete` -button efficiently with JavaScript / PHP

Which of the following code is better in building a delete -action for removing a question?
1 My code
<a href='index.php?delete_post=777>delete</a>
2 Stack Overflow's code
<a id="delete_post_777>">delete</a>
I do not understand completely how Stack Overflow's delete -button works, since it points to no URL.
The id apparently can only be used by CSS and JavaScript.
Stack Overflow apparently uses JavaScript for the action.
How can you put start the delete -action based on the content of CSS -file by JavaScript?
How can you start a SQL delete -command by JavaScript? I know how you can do that by PHP, but not by JavaScript.
Your method is not safe as a user agent could inadvertently crawl the link and delete the post without user intervention. Googlebot might do that, for instance, or the user's browser might pre-fetch pages to speed up response time.
From RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1
9.1.1 Safe Methods
Implementors should be aware that the
software represents the user in their
interactions over the Internet, and
should be careful to allow the user to
be aware of any actions they might
take which may have an unexpected
significance to themselves or others.
In particular, the convention has been
established that the GET and HEAD
methods SHOULD NOT have the
significance of taking an action other
than retrieval. These methods ought to
be considered "safe". This allows user
agents to represent other methods,
such as POST, PUT and DELETE, in a
special way, so that the user is made
aware of the fact that a possibly
unsafe action is being requested.
Naturally, it is not possible to
ensure that the server does not
generate side-effects as a result of
performing a GET request; in fact,
some dynamic resources consider that a
feature. The important distinction
here is that the user did not request
the side-effects, so therefore cannot
be held accountable for them.
The right way to do this is to either submit a form via POST using a button, or use JavaScript to do the deletion. The JavaScript could submit a hidden form, causing the entire page to be reloaded, or it could use Ajax to do the deletion without reloading the page. Either way, the important point is to avoid having bare links in your page that might inadvertantly be triggered by an unaware user agent.
Bind a click event on the anchor which start with "delete_post_" and use that to start an Ajax request.
$("a[id^='delete_post_']").click(function(e){
e.preventDefault(); // to prevent the browser from following the link when clicked
var id = parseInt($(this).attr("id").replace("delete_post_", ""));
// this executes delete.php?questionID=5342, when id contains 5342
$.post("delete.php", { questionID: id },
function(data){
alert("Output of the delete.php page: " + data);
});
});
//UPDATE
With the above $.post(), JavaScript code calls a page like delete.php?id=3425 in the background. If delete.php contains any output it will be available to you in the data variable.
This is using jQuery. Read all about it at http://docs.jquery.com/How_jQuery_Works.
The url you are looking for is in the js code. Personally I would have an id that identifies each <a> tag with a specific post, comment... or whatever, and then have a class="delete_something" on each one, this then posts to the correct place using javascript.
Like so:
Delete
<script type="text/javascript">
jQuery('a.delete_post').live('click', function(){
jQuery.post('delete.php', {id: jQuery(this).attr('id')}, function(data){
//do something with the data returned
})
});
</script>
You're quite correct that absent an href="..." attribute, the link would not work without JavaScript.
Generally, what that JavaScript does is use AJAX to contact the server: that's Asynchronous JavaScript and XML. It contacts a server, just as you would by visiting a page directly, but does so in the background, without changing what page the browser is showing.
That server-side page can then do whatever processing you require. In either case, it's PHP doing the work, not JavaScript.
The primary difference when talking about efficiency is that in a traditional model, where you POST a form to a PHP page, after finishing the request you must render an entire page as the "result," complete with the <head>, and with all the visible page content.
However, when you're doing a background request with AJAX, the visitor never sees the result. In fact, it's usually not even a human-readable result. In this model, you only need to transfer the new information that JavaScript can use to change the page.
This is why AJAX is usually seen as being "more efficient" than the traditional model: less data needs to travel back and forth, and the browser (typically) needs to do less work in order to show the data as part of the page. In your "delete" example, the only communication is "delete=777" and then perhaps "success=true" (to simplify only slightly) — a tiny amount of information to communicate for such a big effect!
It all depends on how your application is built, what happens at Stack Overflow is that the delete link click is caught by JavaScript and an Ajax request is being made to delete the post.
You can use a JavaScript library to easily catch clicks on all elements that match your selector rule(s).
Then you can use Ajax to send a request to the PHP script to do the SQL work.
On a side note, ideally you would not use GET for deleting entries, but rather POST, but that's another story.

Categories

Resources