I'm processing something and when the function is successful I would like to redirect to another page and there show the alert "Function successful".
I'm using CodeIgniter, Javascript and Bootstrap
Any ideas will be appreciated
Once page X has redirected to page Y, page X is no longer open, so can no longer issue alerts. Your options include:
don't redirect. (Instead, you may be able to put page Y in an iframe; or, simply provide a link to it and let the user decide whether to click.)
don't alert.
alert before redirecting. (This is basically the same thing. The user can't actually interact with page Y until they've closed the alert, anyway, so it doesn't really matter whether the alert comes before or the redirect or after it.)
have page Y give the alert. For example, page X can redirect to http://example.com/path/to/Y/?alert=Function+successful, and you can design page Y to detect the query string and issue the alert.
When the functions is successful, redirect and use the body onload event of the new page. Using a querystring extraction based on another SO answer:
if (success)
{
window.location("anotherpage.html?myparm=alertMe");
}
...
anotherpage.html
<body onload="bodyLoad();">
...
</body>
<script type="text/javascript">
function bodyLoad()
{
parmValue = getParameterByName("myparm");
if(parmValue == 'alertMe')
{
alert('Function successful');
}
}
//http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>
Related
I have a QR Code that brings users to PAGE A that immediately forwards to PAGE B. I want Page B to check if users came from PAGE A otherwise forwards them to PAGE C (basically say you need visit PAGE A first). The end result is that Scanning the QR Code allows access to PAGE B through PAGE A but someone can't start on PAGE B without previously being on PAGE A (unless they type it in) It's not foolproof by any means, but it's a deterrent.
On Page B I am using:
if (history.back!="[page a url]") {
location.assign("[page c url]");
}
but this doesn't seem to work.
BTW I'm hacking my way through learning any of this by trying to learn what I need to do what I need to do - please assume I know very little
By your tags, I see that you are using WIX. I'm not sure if you have access to server side there so my answer is in javascript. This isn't full proof as you can't trust anything sent from the browser.
On page A, use localStorage to set a variable visitedA to 1 then redirect to page B.
<script>
localStorage.setItem("visitedA","1");
location.href = "pageB.html";
</script>
On page B check if visitedA equals 0, then redirect to C.
<script>
let visitedA = localStorage.getItem("visitedA") || "0";
if(visitedA == "0"){
location.href = "pageC.html";
}
</script>
Using Document.referrer is a good and most straightforward solution to this problem.
https://developer.mozilla.org/en-US/docs/Web/API/Document/referrer
example:
<script>
// did user come from page a?
if (document.referrer.includes('page-a') {
// yes page-a was in the referrer
} else {
// no, referrer was empty or did not include page a
}
</script>
On our blog we have a link where users can post our articles to their timeline. A popup opens up and the user posts to facebook, then the popup stays there and redirects to "www.oursite.com". How do we instead close the popup when the user either finishes posting or clicks on the cancel button? According to this so question it can't be done but Huffington post has figured it out but looking at their code we can't figure it out.
As an example, the facebook share button here will open up a popup and then close when you either post the article or cancel.
Here's what we have:
FB.init({appId: "90210", status: true, cookie: true});
function postToFeed() {
// calling the API ...
var obj = {
method: 'feed',
redirect_uri: 'http://www.oursite.com/',
link: 'http://www.oursite.com/',
picture: 'http://www.oursite.com/png.png',
name: 'Some title',
caption: '',
description: ''
};
function callback(response){
window.close(); // doesn't do anything
//document.getElementById('msg').innerHTML = "Post ID: " + response['post_id'];
}
FB.ui(obj, callback);
}
We've tried adding window.close(); in the callback (and also self.close();), tried leaving redirect_uri blank (and tried leaving redirect_uri out altogether, but it's required).
It seems that the accepted answer is no longer working due to the fact that facebook now strips anything after a hash and replaces it with post_id=xxxxx.
Solution #1 (if you trust FB not to change this in the near future):
if(window.location.search.indexOf('post_id')==1) window.close();
Solution #2 (if you want a little more insurance against change and don't mind a second file):
Create a new html file closewindow.html:
<html><body><script>window.close()</script></body></html>
and link to it in the redirect.
Redirect to http://oursite.com/#close_window. Then on your site's homepage, include something like this:
if (window.location.hash == '#close_window') window.close();.
After spending a whole day working on this problem, I have a very good solution that I'd like to share. Instead of using the SDK with FB.ui(), I have discovered that I can avoid it entirely by manually opening my own popup to https://www.facebook.com/dialog/feed. When doing it this way, redirect_uri works as expected. As long as you require the user to click a button to make the dialog pop up, no popup blocker will be triggered.
I don't believe there are any compromises with this code, and if anything, it is much easier to use than the actual SDK.
My Javascript code (which you can save as FacebookFeedDialog.js) looks like this:
/* by Steven Yang, Feb 2015, originally for www.mathscore.com. This code is free for anybody to use as long as you include this comment. */
function FacebookFeedDialog(appID, linkTarget, redirectTarget) {
this.mParams = {
app_id: appID,
link: linkTarget,
redirect_uri: redirectTarget,
display: "popup"
}
};
/* Common params include:
name - the title that appears in bold font
description - the text that appears below the title
picture - complete URL path to the image on the left of the dialog
caption - replaces the link text
*/
FacebookFeedDialog.prototype.addParam = function(key, value) {
this.mParams[key] = value;
};
FacebookFeedDialog.prototype.open = function() {
var url = 'https://www.facebook.com/dialog/feed?' + encodeCGIArgs(this.mParams);
popup(url, 'feedDialog', 700, 400);
};
/* Takes a param object like this:
{ arg1: "value1", arg2: "value2" }
and converts into CGI args like this:
arg1=value1&arg2=value2
The values and args will be properly URI encoded
*/
function encodeCGIArgs(paramObject) {
var result = '';
for (var key in paramObject) {
if (result)
result += '&';
result += encodeURIComponent(key) + '=' + encodeURIComponent(paramObject[key]);
}
return result;
}
function popup(mylink,windowname,width,height) {
if (!window.focus) return;
var href;
if (typeof(mylink) == 'string')
href=mylink;
else
href=mylink.href;
if (!windowname)
windowname='mywindow';
if (!width)
width=600;
if (!height)
height=350;
window.open(href, windowname, 'resizable=yes,width='+width+',height='+height+',scrollbars=yes');
}
Here's a sample HTML file that uses the Javascript code above:
<HTML>
<BODY>
<SCRIPT type="text/javascript" src="FacebookFeedDialog.js"></SCRIPT>
<SCRIPT>
var dialog = new FacebookFeedDialog(yourAppIDGoesHere,yourDestinationURLGoesHere,yourCloseWindowURLGoesHere);
dialog.addParam('name','This is my title');
dialog.addParam('description','This is the description');
dialog.addParam('picture',yourImageURLGoesHere);
dialog.addParam('caption','This is the caption');
</SCRIPT>
Open facebook dialog
</BODY>
</HTML>
Your closeWindow html file can look like this:
<SCRIPT>
window.close();
</SCRIPT>
As of 10/2017 removing redirect_uri seems to work.
It will default to https://www.facebook.com/dialog/return/close#_=_
whose source is just
<script type="text/javascript"> window.close() </script>
UPDATE:
Add this script to your redirect page:
if (document.referrer == "https://www.facebook.com/" && (window.location.href.indexOf('post_id=') != -1 || window.location.hash == '#_=_')) {
window.close();
}
Just remove the redirect_uri parameter from the url.
Like here.
This is not a direct answer to the original question, but it might help others arriving here.
There is a more robust way to do this that allows you take action on the originating page when the share has completed successfully:
In the originating page:
var shareWindow;
function openShareWindow() {
// See https://developers.facebook.com/docs/sharing/reference/share-dialog
shareWindow = window.open('https://www.facebook.com/dialog/share?app_id=...&display=popup&redirect_uri=...');
}
function shareCompleted() {
if (shareWindow) {
shareWindow.close();
shareWindow = null;
// The share was successful, so do something interesting here...
}
}
In the page you have set as your redirect_uri, which I usually map to something like http://myserver.com/share/close:
window.opener.shareCompleted();
Now you're assured the share window will close and you'll be able to take action on the originating page if needed.
Note: shareCompleted must be available in the root window namespace for this work. If you're wrapping all of your JavaScript as you should be, then be sure to:
window.shareCompleted = shareCompleted;
<script>if (window.location.hash.indexOf("#close_window") != -1) window.close();</script>
So i have a form, and onsubmit="return reg_check(this)" where reg_check() is a javascript function in the header which is supposed to check the form data, and since one of its tasks is to check if the username is in the database which requires php, i want to redirect to a php page that does this task.
Problem is: window.location.href is not working! Here's the function (reduced version) and of course the main.php is just a random page i got:
function reg_check(myForm) {
alert("before redirect..");
window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height;
alert("after redirect..");
}
The before redirect and after redirect alerts work, it just doesn't redirect? It remains in the same page.
Also, if I tried to redirect from the body by just typing :
<script type="text/javascript">
alert("before redirect..");
window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height;
alert("after redirect..");
</script>
it redirects.
Any ideas of how I could get this to work?
You need to return false; from your reg_check function and then in your onsubmit, change it to:
onsubmit="return reg_check(this);"
This will cancel the form submission. And if you want to let the form submit as normal, just return true from reg_check.
Edit (to be more clear you need to add return false; from your function):
function reg_check(myForm) {
alert("before redirect..");
window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height;
return false;
}
I've seen problems in IE where I've had to do the following:
window.location.assign(url);
Specifically within a jQuery AJAX success handler. Can't really speculate to why other than for me, it worked.
Actually I did
window.location.replace(url)
Which replaces the current page in the history. Nice trick that!
I had the same problem, but found the answer here Javascript: window.location.href doesn't redirect when calling function within a function .
My button was reloading the page by default so if you add an
event.PreventDefault();
To your function it should work.
[RESOLVED] I had a similar problem in redirecting to some other url from client script. Implemented window.open function instead and it worked. You may have for instance, a function say ChangeCity() for your html control event that gets called with onchange event.
function ChangeCity() {
switch ($("#currentCity").val()) {
case "NY":
var url = '#Url.Action("New York City", "Home", new { #area = "" },Request.Url.Scheme)';
window.location.href = url;
window.open(url,"_top");
return false;
/* cases for other cities */
}
You may like to explore details on window.location.href redirection -Alternative Solution
I am working on a VB.NET web application. When someone successfully changes their password I want to show a popup message that lets them know it was changed successfully. After they click OK I want to redirect them to the main page. Code looks like this:
ClientScript.RegisterStartupScript(Me.GetType(), "confirmScript", "ConfirmNewUser();", True)
Response.Redirect("MainPage.aspx")
Why does the redirect happen and the alert popup never displays?
Try this:
1) Remove Response.Redirect from the code behind.
2) Change the ConfirmNewUser function as given below:
function ConfirmNewUser(){
//Existing Code of ConfirmNewUser
//New Code.
var msg = "Password changed successfully. Press OK to go to Home page Cancel to stay on current page.";
if(confirm(msg)){
window.location.href = "MainPage.aspx";
}
}
You are calling the redirect server side, your script never get a chance to run. use window.location to do the redirect client side, something like this:
function ConfirmNewUser() {
if(confirm("Your password has been changed, click OK to continue")) {
window.location = "MainPage.aspx"; //go to home page
}
}
The reason is because all server-side processing will take place prior to client-side.
One solution would be to pass "MainPage.aspx" to your client script as follows:
ConfirmNewUser('MainPage.aspx');
Your client script would then have to take a URL parameter:
function ConfirmNewUser(url) { ... }
and follow up with a window.location:
...
if(confirm(...))
{
window.location = url;
}
and remove the following from your server code:
Response.Redirect("MainPage.aspx")
Response.Redirect sets the Location http header and a 302-Moved response, the browser will act upon this as soon as it sees it. As headers come before content, your script is never seen or parsed.
I need to use JavaScript (jQuery if applicable) to trigger my modal call if the result of my function is true and the referring URL is not of the domain.
The desire is that the user visits the main splash page and as long as they have not been redirected there by the site itself (via timeout on a session, invalid login credentials, etc) it displays the message so:
function showModalIf() {
if (checkFunction) {
if(////// REFERRING URL not from this site)
Trigger Modal Call
else
Don't Do anything else
}
}
Assuming you use jQuery UI Dialog to show the modal
function checkReferrerExternal() {
if (!document.referrer || document.referrer == '') return false;
var regex = /^https?:\/\/\/?([^?:\/\s]+).*/;
var referrermatch = regex.exec(document.referrer);
var locationmatch = regex.exec(document.location);
return referrermatch[1] != locationmatch[1];
}
function showModalIf() {
if (checkReferrerExternal()) {
//show jQuery UI Dialog modal or replace with whatever
$("div#dialog").dialog('open');
}
}
Check demo page http://jsbin.com/efico
If you are talking about forced redirection in the code, and not just a hyperlink click from elsewhere in the site, you could add a query string parameter on your redirection and check that way. Another option is to set a cookie and check for the cookie in javascript.
Here is a nice link on cookie handling in Javascript:
Javascript - Cookies
And here's one for parsing query string params/hashes in Javascript as well:
Parsing The Querystring with Javascript
Hope this points you in the right direction :)