I am showing a jQuery overlay when users first visit a particular page
They have a radio button in the overlay that they can click to say they do not wish to see the notification again
I want to set a cookie that the user doesnt want to see the overlay again
Is it possible to set the cookie without refreshing the page?
I was going to make a ajax call back to the server and then set the cookie in the response headers but I guess they wont get set in an Ajax request/response?
Is it safe / OK to set the cookie purely from javascript? Or is that a bad idea?
any other options?
There is no reason that an AJAX call cannot set a cookie. It is basically just an HTTP request.
AJAX Requests Get And Set Cookies Like Any Other HTTP Request
You may use jQuery Cookie Plugin.
Some example:
function setCookieFilters() {
var $filtersContent = $(".dynamic-filters");
if ($filtersContent.length > 0) {
if ($filtersContent.css("display") == "none") {
$.cookie("isUsingFilters", "true", { expires: 7 });
}
else {
$.cookie("isUsingFilters", "false", { expires: 7 });
}
}
}
you could also just get/set the cookie in plain old javascript:
Create and Store a Cookie
Use this: this shall reload the page.
setcookie($data,$item_data, time()+ (3600));
echo "<script>location.href='index.php'</script>;
Related
I follow below code :
function My_Function() {
var x;
if (confirm("Exit?") == true) {
x = "Ok";
window.location.href = '#Url.Action("Login", "Account")';
Session.Abandon();
} else {
x = "Cancel";
}
}
I want to prevent is that , after logging out , then I click the back navigation button , I don't want to go back to the previous page.
Browsers can cache content locally. So no matter what you are doing on your server, after logging out, if the user clicks on the Back button, the browser can decide to get the last page from the local cache and display it.
In order to prevent this behavior you could serve all controller actions that require authentication with cache disabled. This can be achieved by decorating them with a custom [NoCache] filter. This filter will ensure that the proper response headers are set when serving actions that require authentication to prevent the browser from caching them.
This being said, please note that the Session.Abandon(); call should be done on your server - inside your Logout controller action that is supposed to clear the authentication cookies and session state.
Session.Clear and Session.RemoveAll are identical; the latter just calls the former. They immediately remove all items stored in the session, but the session itself survives. Session_OnEnd does not fire.
Session.Abandon doesn't actually clear the values immediately, it just marks the session to be abandoned at the end of the current request. You can continue to read the values for the rest of the request. If you write to the session later in the request, the new value will be quietly discarded at the end of the request with no warning. Session_OnEnd fires at the end of the request, not when Abandon is called.
My website structure is as follows:
public_html/
- index.php
- students.php
The user loads the site (index.php) which contains a button. When this button is clicked AJAX is used to load "students.php" and it is displayed to the user (As if they just went to a different page seamlessly). When doing so the following JavaScript is run:
var state = {'Page' : 'Students'};
history.pushState(state, null, "students");
This adds a state to the browsers history and causes the browsers URL to display "example.com/students" instead of "example.com". However if a user was to refresh at this point, nothing would load (404 Not Found) due to the folder "students" not actually existing.
My question is, how can I get the users browser to actually display "index.php" and automatically take them to the students page. In other words, the user refreshes "example.com/students" and what actually happens is the user is taken to the index.php file and the AJAX automatically takes them to the students page (As though they actually refreshed the page)
Note: I am aware I can pass null to the url parameter in "pushState()" however this URL behaviour is desired as it would allow users to quickly jump to a page (If I can get it working)
The full code to show the students page via AJAX is as follows:
/**
* Display students screen.
*/
function displayStudents(createState) {
if(typeof(createState)==='undefined') {
createState = true;
}
$("#container").css("width", $( window ).width());
$("#container").css("position", "fixed");
$("#container").animate({marginLeft: "-100%"}, ANIMATION_SPEED);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
$("#container").css("margin-left", "100%");
$("#container").html(xmlhttp.responseText);
$("#container").animate({marginLeft: "0"}, ANIMATION_SPEED, null, function reset() {
$("#container").css("width", "100%");
$("#container").css("position", "relative");
});
if(createState) {
var state = {'Page' : 'Students'};
history.pushState(state, null, "students");
}
}
};
xmlhttp.open("GET", "students.php", true);
setTimeout(function() { xmlhttp.send(); }, ANIMATION_SPEED);
}
Most of the code here is for animation.
In other words, the user refreshes "example.com/students" and what actually happens is the user is taken to the index.php file and the AJAX automatically takes them to the students page (As though they actually refreshed the page)
The point of pushState is that when you use JavaScript to transform the state of the page, you provide a URL which the server can use to deliver some HTML that will provide the page in that state.
If you are always going to serve up the homepage and then transform it with JavaScript, then just use hashbangs. pushState is entirely the wrong tool for the job.
If you were to use pushState, then a pseudocode implementation of a possible approach would be along the lines of:
GET data needed for the page
IF `Accept` header prefers `application/json`
Output `Content-Type: application/json` header
Output data in JSON format
ELSE
Output `Content-Type: text/html` header
Pass data through the template for the page
Output template as HTML
And you would use students.php in the URL instead of students (or you would make students resolve to the PHP code you wanted to run instead).
Since you are using raw XMLHttpRequest, you will need to use setRequestHeader to set the Accept header. You are using jQuery though, so you could just use $.ajax and pass it dataType: "json".
I am new to Dojo Framework.I created one button using dojo constructor and dojo.connect onclick event function i written url and load functions.This url navigating servlet and get the response back.
but i don't want response back i want to send request only.
how to do this..anyone help me.
thanks in advance.
are you looking to navigate to another page? if so, you can use window.location.href or other approaches to achieve that. See the foll url for other approaches:
JavaScript: Navigate to a new URL without replacing the current page in the history (not window.location)
if you do not want to navigate but just send some data to the server (and dont care about the response), you can just write an empty function for the callback
var deferred = dojo.xhrGet( {
url : "xxx",
load: function(data) {
//ignore
}
});
});
However, it is recommended to always check the response to ensure there were no errors on the server side.
You could also use dojo.xhrPost to submit your form
Is it possible to create a (yes/no) javascript messagebox from code-behind, and also retrieve the return values?
I would like to set the content of a session object based on the client Yes/No.
The idea is to use this approach for redirecting iphone clients from my default web page.
"Do you want to go the iphone version of this site?"
--YES Redirect to "iphone" default page, and set a session object to avoid asking this question again if default page is requested again
within the lifespan of the session object.
--NO Set a session object to avoid asking this question again if default page is requested again within the lifespan of the session
object.
Just display the message and set an appropiate cookie. Then make your server-side react to the cookie and render the selected version of the site.
http://www.htmlite.com/JS006.php - Javascript Confirm popup
http://www.w3schools.com/js/js_cookies.asp - Javascript cookies
In Code behind on FormLoad or wherever it best suits your needs, you would just have to set your button's OnClientClick as follows:
button.OnClientClick = "IphoneVersion()";
In Markup create a function in javascript as follows:
function IphoneVersion() {
if (confirm('Do you want to go the iphone version of this site?')) {
//set hidden value here }
else { //don't set hidden value }
}
You can set your Hidden control value to yes/no text and refer to it behind code or you can redirect in the function itself.
That will do it!
Or you could stash the value in a hidden field and read it on the server side.
** EDIT **
OP Comment:
I would like to set the content of a session object based on the client Yes/No.
Either way you look at it, if he wants to set this value in session, he has to go back to the server.
Try something like this:
confirmSomething = function(){
__doPostBack("<%=Button1.ClientID%>", confirm("Are you sure?"));
}
<asp:Button ID="Button1" runat="server" OnClientClick="confirmSomething();" />
Code-behind:
protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
bool conf = bool.Parse(eventArgument);
}
After a user creates an account on my website, I want to redirect the user to the home page and display a twitter style message bar on top. This is how I have it:
success: function (response) {
if (response.Success) {
location.href = response.ReturnUrl;
}
ShowMessageBar(response.Message);
},
The message bar does appear but it gets displayed only for a second as it gets canceled by the redirect. What can I do to display the message right after the redirect has completed? Is there a complete event for the location.href? Thanks.
You need to pass it through a cookie, the quesrystring, or localStorage.
Something like this using localStorage or cookies (localStorage is available in IE8+ and most other browsers):
on the current page:
if('localStorage' in window)
localStorage.setItem('message', response.Message);
else // use cookie
On the new page:
$(function(){
if('localStorage' in window && !!localStorage['message']) {
ShowMessageBar(localStorage['message']);
localStorage.removeItem('message');
}
else // use cookie
});
If you are uncomfortable with these techniques there are jquery plugins that wrap this functionality. I would recommend jstorage.
This will need the Cookie plugin for jQuery:
http://plugins.jquery.com/project/Cookie
Put this somewhere in the header of your homepage:
jQuery(function($){
if($.cookie("message")) {
ShowMessageBar($.cookie("message"));
$.cookie("message", "any_value", { expires: -1 });
});
And in your success function:
success: function (response) {
if (response.Success) {
$.cookie("message", response.Message);
location.href = response.ReturnUrl;
}
},
Once the url of a page changes all execution stops and is transferred to the new page. Pass a parameter to the new page that triggers the event you want instead.
Sounds to me like you would need to call ShowMessageBar() from the redirected URL.
You could send a parameter and check for its existence on document ready. Probably the easiest way of achieving the desired effect.
If you REALLY wanted to show the message, you could always throw it in an alert before you redirect them, which would halt execution until they clicked 'ok'.