Why JavaScript function fires before .NET action? - javascript

I noticed that when a link on the page has JS onclick function and also a MVC action method, the JS function fires before the action.
Wondering is this always the case?
Why/how browsers deside to run JS and the the backend method?
Can I run backend method first, but still want to fire the JS function?
Regards

Wondering is this always the case?
Why/how browsers deside to run JS and the the backend method?
Client-side JavaScript runs on the client, inside a page. Server-side .NET code runs on the server and generates an HTML document (or other resource).
To run server side code, the browser has to make an HTTP request.
The easiest way to make an HTTP request is to leave the current page and load a new one from the server (by following a link or submitting a form).
Since client-side JavaScript runs in a page, it can't run after the browser has left the page it runs in.
Can I run backend method first, but still want to fire the JS function?
You can make an HTTP request from JavaScript (before doing other JS actions) instead of leaving the current page. This is usually done with the XMLHttpRequest object and is known as Ajax.

Why/how browsers deside to run JS and the the backend method?
server side code will need a request to return the response. HTTP works on Request and Response architecture. basically client make requests in order to get the response (i.e results or desired data)
wheenever you do postback or return true to the server, it will execute server side methods.
ClickHereToSee
here return value which is returned by the function, if you return the true value it will go to the server method, if you returned the false it will prevent the default action.
Can I run backend method first, but still want to fire the JS function?
You can. use Ajax. basically Ajax requests are XMLHTTPRequest. which used to update the paritial portions.

Can I run backend method first, but still want to fire the JS function?
First two answers are already well answered. For third one you can try Jquery Ajax-
function SomeFunction(){
$.ajax({
type: 'POST',
url: "#Url.Content("Controller/ActionResult")",
data : {
*yourparameter:value* //data
},
dataType: 'json',
success:function(result)
{
//javascript stuff
}
});
}
ClickHereToSee

Related

How does one limit rate of api calls despite page reload?

Suppose I am using a free API service with a limit of c calls per m minutes.
I am using a tiny bit of javascript linked by the main html of my very basic site which contains something like the following:
$(function () {
//stuff
function getSomething() {
return $.ajax({
type: 'GET',
url: targetURL,
data: dataObject,
});
}
getSomething().done(function (returnedStuff){
//process returnedStuff
});
//more stuff
});
I have two questions:
Will there be an api call each time the page is reloaded?
If the answer to above is YES, then how does one prevent/limit the user/some other event from overshooting the api limit by their repeated reloading of the page.
Thanks for the help.
tldr: Making some assumptions from your high level example:
Will there be an api call each time the page is reloaded? Yes
If the answer to above is YES, then how does one prevent/limit the
user/some other event from overshooting the api limit by their
repeated reloading of the page. Read below
Further explanation:
Depending on whether your example code hits your own server side code which then makes the API code...or whether you're calling the API directly from the client. If you call the function on reload (document ready or whatever), then it will execute on every reload. Else, obviously only when you call the method (like via button click).
Remember, client side code is visible to the client - thus if that's your architecture, then you're exposing your API to the client. I can then for example write my own javascript to loop and call your API repeatedly...
My assumption is that the data does not need to refresh on every reload. With that in mind, I suggest you do the following:
Suggested way to limit API calls:
Use an ajax call to your own server.
On the server side, persist the data via caching of your choice and build in your own logic to test whether data needs to be refreshed (first call, after timeout, etc).
This way you do not expose the API url and details to the client side, and you have control over the amount of calls made to the API.
For optimization purposes, you can also rather cache data client side...but keep the logic and API call server side.
Hope this helps!
ps. If you need an example, please just provide what platform you're coding in and I'll be more than willing to whip up a quick example for you!
pps. You can simply cache client side and makde the API call from there with some logic built in to test the cache - but obviously anyone can then still call your API.

How do you make a link perform an action without reloading a page?

The clearest example of this I could think of is the Reddit Upvote/downvote buttons how when you click the button, the value for upvotes is updated, the upvote button lights up, and the page DOES NOT reload, you just stay exactly where you are on the page.
I am trying to make a feature similar to this and I can totally figure out how to do it with reloading, but I want it to not reload so the user experience isn't disrupted.
Is it possible to do this with php? or would I need to use javascript or something?
The action I would need it to perform would be a basic update query in the database.
This would be done with an Ajax call to your php script. Ajax is designed for these asynchronous updates and/or reloads.
Another way you can do this is with HTML5 WebSockets. You could have the client send a trigger to the server when the user clicks the upvote, and then the server could update and push back the data. It would, however, be a bit overfill for this.
If what you want to do is to contact a server to either send it some state or to retrieve some state from the server (or both), then you would use AJAX with javascript in order to contact the server without reloading the page. You can then also use javascript to update the state of your page after the operation. That is generally what the Reddit page you refer to is doing.
Conceptually, you'd set up your page like this:
Put the link on the page.
With javascript install an event handler so you are notified of a click on the link.
When the link is clicked, your event handler will be called.
Prevent the default behavior of the link so the browser doesn't navigate to a new page.
Then, in the event handler, send your data to the server using AJAX. You will obviously need a URL on your server and server process that can accept and process the data for you and return a value if you need to.
If you need the response from the server, then set up a callback function for when the AJAX call completes (this will be some indeterminate time in the future).
Then, if you need to change the current page in any way (like show one more upvote), then you can modify the current page with javascript to show that new state.
Ajax is easier to use with a library (like jQuery) that contains some ajax support code, but you can certainly implement it in plain javascript too.
Here's one example of ajax with plain javscript. You can find many other examples with Google.
This MDN tutorial on AJAX seems pretty helpful too to show you how it works.
You could use JavaScript to do this. Here's a quick sample:
Vote Up
Simple solution in JavaScript:
var el = document.getElementById("upvoteBtn");
el.addEventListener("click", onVoteClick);
function onVoteClick(e) {
e.preventDefault();
// do something
}
Here's a fiddle.
NOTE: I see you'd be updating the database. In that case, you would have to use AJAX in the onVoteClick function (or use XMLHttpRequest) for this. JavaScript is a client-side programming language and will not be able to communicate to the server without the use of AJAX or XMLHttpRequest. Using the jQuery library, you should be able to write AJAX pretty easy.
It's called AJAX.
With AJAX you can send a request in the background.
The easiest way is to use the jquery libary for this.
You can also output some data as JSON back to the script if you want to take some other actions depending on the result from that query.
A good tutorial is this one.
It also explains how this requests (called: XMLHttpRequest) work.
You need to use Javascript's XMLHttpRequest
You can use AJAX...
It allows you to use JavaScript (client side) to call server side functions. Here's a good example.

Call JS function before redirect

The situation is as follows:
A user on the client side enters some data and presses a command button that initiates an ajax request. Depending on the input data the JSF Bean on the server side redirects to different pages. But in addition the HTML5 features localstorage respectively sessionstorage should be updated on client side, also depending on the results from the bean. For the storage some data entered from the user is necessary, so that the java script for the storage has to be within the original page.
Now, the problem seems to be that after the response the redirect is always done first, before executing the js function and so it is not possible to access the input data from the user on the client side of curse.
I tried things for calling the js function after pressing the command button like "oncomplete" on the client side using callback parameters (redirect takes place earlier) or RequestContext.execute from the server side (but this internally also uses the oncomplete event i think).
One possible solution I could imagine is to use window.onunload on client side and a hidden input formular to get the result of the bean. But isn't there a better solution?
You need to redirect by JS instead of by JSF. Return null from action method so that it returns to the same page and then execute the following script to perform a redirect in JS.
window.location = newURL;
If you use PrimeFaces with JSF then it's possible to make global override of PrimeFaces.ajax.ResponseProcessor.doRedirect in javascript to put any custom code before actual redirect happens:
PrimeFaces.ajax.ResponseProcessor.doRedirect = function(node) {
// <<<< your code is here >>>>
window.location = node.getAttribute('url');
}
Put this code in some js file and include it in all your pages.

Is there any way to call JavaScript function from a perl script?

I am trying to write a Perl script that will take a user parameter from command line and with his parameter, Perl script will call a JavaScript function in a HTML page. How can I go ahead to with this?
Not that I've seen. Perl is strictly server side, and JS functions you're talking about are on the client.
The closest you would get is have the Perl script write a block into the HTML page so that the page fires it on load to perform the action. But that's a little shaky at best to do.
It depends on whether the browser or server will be taking the first step.
If the server needs to run code first and then execute some JS, then #skyburner's solution would work. Essentially you would already have some functions defined on the page, but then you would dynamically add a block of JS to call whichever function you need to.
However, if the Perl is being run due to a user's action on the current page (such as clicking something or submitting a form), then AJAX would be the way to go. You would use JS to submit an HTTP request to the Perl script. The Perl would then return some value back to the JavaScript and execute some function based on this result. This would all happen "behind-the-scenes" without the user leaving the page.
If I understand correctly about what you want, since not all the browsers support socket, this is what you can do:
Have an ajax service call periodically sending requests to the server for update
Once the the parameters from the command line are taken, you can send the result along with an ajax response back to the page, and call the function in the ajax request callback function.
Also, another option, you can use reverse ajax to accomplish this. See Wikipedia about reverse ajax (comet), especially Ajax with long polling.

detecting JSON loaded by browser

I have an application in which most requests are submitted via AJAX, though some are submitted via "regular" HTTP requests. If a request is submitted and the user's session has timed out, the following JSON is returned:
{"authentication":"required"}
The JavaScript function which submits all AJAX requests handles this response by showing a popup message and redirecting the user back to the login page.
However, when a non-AJAX request receives this response the JSON is simply shown in the browser because the response is processed directly by the browser (i.e. the aforementioned JavaScript function is bypassed). Obviously this is not ideal and I would like the non-AJAX requests that receive this response to behave the same as the AJAX requests. In order to achieve this, I can think of 2 options:
Go through the application and convert all the requests to AJAX requests. This would work, but could also take a long time!
The JSON shown above is generated by a very simple JSP. I'm wondering if it might be possible to add a JavaScript event handler to this JSP which is run just before the content is displayed in the browser - I'm assuming this would never be called for AJAX requests? This handler could call the other JavaScript code that displays the popup and performs the redirection.
If anyone knows how exactly I can implement the handler I've outlined in (2), or has any other potential solutions, I'd be very grateful if they'd pass them on.
Cheers,
Don
3) Change your AJAX code to add a variable to the GET or POST: outputJson=1
You cannot add a handler to the JSP that way. Anything you add to it will make it a non-JSON producing page.
There are two options that I can see:
Add a parameter to the page by appending a URL parameter to the screen that modifies the output.
URL: http://domain/page.jsp?ajaxRequest=true
would output json only
URL: http://domain/page.jsp
would display a jsp page that could forward to another page.
OR
change the response to have the forwarding code in the JSP that will get executed by the web browser if it is hit directly. Then have your calling AJAX to strip the forwarding code out, and then process what is left.
4) Read up on the 'Accept' request HTTP header.
Then, on the server side tailor the output:
e.g.
if(Accept contains application/json...) { // client asking for json, likely to be XHR
return {"foo":"bar"}
} else { // other
return "Location: /login-please";
}
Start with a smarter error message, like this:
{"error":"authentication required"}
Wrap the JSON output in a callback:
errorHandler({"error":"authentication required"});
Have a handler waiting in your script:
function errorHandler(r) {
alert(r.error);
}
And don't forget to send it down as text/javascript and not application/x-json.

Categories