How do I change URL without reloading page? - WITH A TWIST - javascript

I am looking to remove a certain amount of a page URL without reloading.
I have looked on StackOverflow for the answer and there are a few close answers but not what I'm looking for really.
I do not want to use the hash function and if possible, avoid using the HTML5 version because HTML5 isn't the ratified standard yet and for the website this will be used on, I wouldn't be at all surprised is some of the clients used IE6.
I would prefer if it wasn't an extremely complicated solution with 400 lines of code (at that cost I'd rather just reload the page to be honest).
I forgot to mention this, critical, part of the question
The user is directed from a different page with this string via PHP. So for example:
user submits a form with errors. Let's say the form is on /myform.php
The user gets headed to /index.php?string
carry on as normal
What I have:
This is an example URL that I wish to edit without reloading:
http://www.mywebsite.com/index.php?string
Wait! ?string has a use on /index.php
index.php will use $_GET['string']; and display a message to the user
I have used JQuery to remove the message after 4 seconds like this:
<div id="pagemsg"><?php echo $string; ?></div>
<script language="javascript">
setTimeout( "$('#pagemsg').fadeOut();", 4000);
</script>
This works all well and the message disappears after 4 seconds. However I'm left with this URL:
http://www.mywebsite.com/index.php?string
I don't want this string anymore because ?string has done its job!
I would like to remove the ?string without reloading the while page.
Is there any solution that can help me?
Also,
I don't mind if I have to use the HTML5 push function but is there a fall-back solution for the browsers that don;t support HTML5?
Why did I put WITH A TWIST in the title? Well, my requirements are different to the questions I have seen so far. Correct me if I'm wrong and I will change it.
Thanks for your help in advance!

The simple answer is no. That's why they added pushState.
However, it looks like you are trying to accomplish a fairly common scenario known as flash messaging. This is often done using the user's session to store a message to show on the next request (and then delete it).
Example:
function doImportStuff() {
// ...
$_SESSION['message'] = 'important stuff was done';
// ...
}
function showBoringPage() {
// ...
if (isset($_SESSION['message']) {
echo '<b>' . $_SESSION['message'] . '</b>';
unset($_SESSION['message']);
}
// ...
}

The only method I know of is this:
if (history && history.pushState){
history.pushState(null, null, '/new/url');
}
But this is HTML5 and won't work in your case..
For old browsers - and you: History.js

Related

Checking for Google OAuth disallowed_useragent to render something different

What I'm looking for:
I want to test for the 403 disallowed_useragent error (unless there is something else to test for) and when the error is present I can create a way for the user to continue.
Background/The Problem:
I have a Google Scripts signup sheets app with a Google OAuth button to login to the Admin functions.
Everything in the resulting webpage works the way I'd like, if it's accessed from a web browser.
However, this script was made for our church and placed both on a website and within an app builder (Subsplash), and when someone tries to login (from the script from within the app) it's returning a 403 disallowed_useragent error. I don't have much control over the app builder, or the resulting app: Subsplash (https://www.subsplash.com/).
I am reaching out to Subsplash to see if there is something they can do on their end, but in the meantime, or in the even that there isn't anything they can do, I'm looking for a solution that I can do on my end.
After researching the error, and potential fixes, it appears the problem is that Subspash is rendering my webpage in a WebView and, for security reasons, OAuth won't work in a WebView.
Researching the Problem:
I found references to using googlechrome://navigate?url=www.example.com but that didn't do anything from within the WebView on my Android phone.
This was the closest question to what I'm looking for: Google OAuth for websites in embedded browsers
In the answer:
I would like to avoid going down the road of detecting the user-agent web-side and force the user to open the link in Safari.
I don't know that sounds like a pretty decent solution to me. It may feel a like over kill a little but if it works go with it.
So I headed down the path of detecting the user-agent web-side and ran into this article: https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent which basically tells you to avoid it at all costs, and only if necessary, try to detect the missing feature instead.
This makes sense, because for some mobile/browser options, it'll work fine, but not all.
Also, maintaining all availiable browsers/mobile scenarios, does sound like a headache (and I'm programming this in my freetime, not as a job, so less maintenance would be best! Not to mention, at some point, it'll get turned over to someone without a background in programming!)
Not to mention, I don't have access to all different mobiles, etc. And may only find out that something doesn't work when someone with a different device tells me. (One I don't have to test with!)
Back to the solution:
I'm not sure what to look for, but the best case scenario would be to be able to test that clicking on a Google Login button will return the 403 error, and that I can somehow catch that and show something different.
If it is possible to search for a specific feature that is missing from a WebView (before even showing the Google Sign button) that would be acceptable also.
As a last resort, I'm not even sure what else to search for in my quest for an answer. So if you won't have a full answer, but can point me in a direction, that would be super helpful as well.
Some Code
Reminder!! This works for a website rendering!
page.html
<head>
...
<meta name="google-signin-client_id" content="....apps.googleusercontent.com">
...
</head>
<body>
...
<div id="google-signin-button" class="g-signin2" data-onsuccess="onSignIn"></div>
<div id="not-logged-in-message">
<br />Please login to access Admin Functions.
<!-- This anchor tag doesn't do anything -->
<br /><a href='googlechrome://navigate?url=script.google.com/...'>Open outside the app</a>
</div>
...
<?!= HtmlService.createHtmlOutputFromFile('javaScript').getContent(); ?>
<?!= HtmlService.createHtmlOutputFromFile('adminScript').getContent(); ?>
</body>
javaScript.html
...
<!-- Google Login https://developers.google.com/identity/sign-in/web/sign-in -->
<script src="https://apis.google.com/js/platform.js?onload=init" async defer></script>
...
adminScript.html
<script>
...
// https://developers.google.com/identity/sign-in/web/reference
function init ()
{
gapi.load ('auth2', function () {
/* Ready. Make a call to gapi.auth2.init or some other API */
$('#loading-message').val ("").empty ();
});
}
// Trouble Shooting: https://stackoverflow.com/questions/41448014/google-script-oauth2-error-redirect-uri-mismatch
// Make sure redirect faces production script
function onSignIn (googleUser)
{
console.log ("Calling onSignIn");
var google_profile = googleUser.getBasicProfile ();
console.log ('ID: ' + google_profile.getId ()); // Do not send to your backend! Use an ID token instead.
console.log ('Name: ' + google_profile.getName ());
console.log ('Image URL: ' + google_profile.getImageUrl ());
console.log ('Email: ' + google_profile.getEmail ()); // This is null if the 'email' scope is not present.
displayAdminInfoCall (google_profile);
fillAdminNavs (google_profile);
}
...
</script>

reload php page with javascript

I have drawn a chess board in a php page. Every piece is set as draggable, and every tile as droppable. Once a piece is dropped on a tile, I'd like to reload the php page so the board can be drawn anew along with new positions.
How can I do that: reloading the php page with javascript, without displaying a window asking for confirmation such as "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier. ->Cancel; Resend" ?
Or perhaps there are better solutions?
If you want to avoid having refresh reporting data (for any reason, including the user clicking the reload button) then use the POST-REDIRECT-GET pattern (http://en.wikipedia.org/wiki/Post/Redirect/Get). Read that, it will explain what to do.
Quick solution: you could try:
window.location.reload(true); //true sets request type to GET
Use GET, instead of POST and the dialog box you are getting will go away.
Good luck!
Make use of
window.location.reload();
will refresh automatically
<script>
var timer = null;
function auto_reload()
{
window.location = 'http://domain.com/page.php'; //your page location
}
</script>
<!-- Reload page every 10 seconds. -->
<body onload="timer = setTimeout('auto_reload()',10000);">
reference http://davidwalsh.name/automatically-refresh-page-javascript-meta-tags

Alternative of this script in jQuery?

I use the following script to get the content of the remaining.php.
The drawback is that sometimes it doesn't work or it is kinda slow to display the text. Is there any other way of doing this ?
Thank you
$(document).ready(function(){
$("#SubmitButton").click(function (){
$('#remaining').load('remaining.php');
});
});
You could directly include the contents of remaining.php into the initial markup but make it hidden by applying display:none; style to the #remaining element. Then when the button is clicked simply show it:
$(function() {
$('#SubmitButton').click(function () {
$('#remaining').show();
});
});
Of course if you need to pass some parameters to the script which will depend on some javascript variables that are known only at the moment the button is clicked you will need to use AJAX as you are currently doing.
If "sometimes it doesn't work or it is kinda slow", the problem is probably the server you are using, not your javascript code.
The javascript code you're showing us here doesn't really do anything that could be slow, it only binds an event on a submit button. However, what could be slow is waiting for the answer from your web server when sending a request for remaining.php
From there, there is a thousand of reasons why your web server could be slow. Maybe you could post the content of your remaining.php file so we can see what is going on in there.
This isn't really a fault of jQuery, but the speed of return from your server. Perhaps there's a better way to handle it instead of fetching a full page?
For example, if your content request was only retrieving a message, you could return JSON from your server and have jQuery handle the data:
$(document).ready(function(){
$("#SubmitButton").click(function (){
$.post('remaining.php',
null,
function(data) {
// do stuff with your JSON result
});
});
});
When you're using .load(), you're sending a request to the server to get your content, which is why it can seem slow. I'm not sure why it sometimes won't work , but I would venture to guess that you may be clicking $("#SubmitButton") before $(document).ready fires.
Depending on your implementation, you may be able to refactor your application so that the text you want to display is pre-loaded on the page.

Inserting script from jQuery / Javascript

I'm trying to insert reCaptcha code into my page from jQuery, but it doesn't work.
Here is my code:
$("#button").click(function() {
$("#loginBox").html($.getRecaptcha());
})
When I try the following, my code doesn't even run. I think it's trying to execute instead of rendering it.
$.getRecaptcha = function(){
return '<script type="text/javascript"' +
'src="http://api.recaptcha.net/challenge?' +
'k=6Ld3iAsAAAAAAGyX8QT244GagPEpCDSD-96o4gEi"></script>';
}
With the following, the code runs, but when I click to #button I get an empty, full white
browser window.
$.getRecaptcha = function(){
var captcha = $("<script>")
.attr("type", "text/javascript")
.attr("src", "http://api.recaptcha.net/challenge?k=6Ld3iAsAAAAAAGyX8QT244GagPEpCDSD-96o4gEi");
return captcha;
}
I don't want to insert reCaptcha code into my html from the beginning, because it downloads the reCaptcha content from the reCaptcha server even if my users don't want to use it. I could set the visibility of the container that holds the reCaptcha to invisible (display: none;), but it will dowload the content irrespectively of it.
I can insert the "noScript" code that reCaptcha gives us, but it doesn't work either, because it can spot that the browser allow javascript but I use noScript.
Any suggestions?
(I know I put my public reCaptcha key into the code, but it is just for testing purposes, and you could get it from my html or javascript code anyway)
UPDATE:
Krunal Mevada answered my question. But it doesn't work with reCaptcha. reCaptcha offers a reCaptcha AJAX API which is the answer to my specific question. However, with getScript() I can dinamically download the reCaptcha AJAX API javascipt file.
Use getScript method of jQuery.
May be this answer can be useful:
Stack Answer
First code part: insert a space at the end of the first line:
return '<script type="text/javascript" ' +

Using Bookmarks with jQuery Address

I am using jQuery's Address plugin (website) to enable the back/forward buttons on my website. I would REALLY like to also have the ability for people to bookmark pages and to copy the address from the address bar and share it with friends.
Address claims it can do this, so then what am I doing wrong.
My code is
function BackButton() {
$.address.change(function(event) {
// do something depending on the event.value property, e.g.
// $('#content').load(event.value + '.xml');
});
$('a').click(function() {
$.address.value($(this).attr('href').replace(/^#/, ''));
});
}
BackButton() is then called on every AJAX pageload to ensure it works with the pages loaded by ajax.
Thanks for your help
looks like you copied directly from the example at the plugin's website. your address.change function does nothing, there are only two commented lines in there.
So I used
if ( $.address.value() !== "\/" ) {
window.location = "http://www.domainname.com/" + $.address.value()
}
to redirect the user to the correct page.
So is this correct? Or are their problems with it?
What would be the benefits of using the $.address.init function of jQuery.Address?
Also this forces them to wait until the page (&javascript) is loaded to see any content. comments?

Categories

Resources