Remove query string from URL after some period of time in javascript - javascript

Hi all I am trying to remove the query string from my url after some period of time in php I have 2 pages one is login-issue.php in that page after user submit the from it will redirect to login.php page with query string like below
if ($mail->Send()) {
Header( 'Location: login.php?message=success' );
}
In login.php the message will appear with that query string
if(isset($_GET['message']))
{
$successMessage= "Your Request has been sent to Admin.you will get mail with in 24hrs";
}
I want to remove that query with that success message after some interval of time (1 min).
Can anyone help me how can I do that.
Thanks in advance.

PHP by itself can't deal with client-side manipulations, so we need to use JavaScript to do the task.
setTimeout(function() {
history.pushState('', '',
location.href.split('?')[0]);
}, 60000); // 1 min = 1000 ms * 60 = 60000
Explanation:
We said to JavaScript that I want to execute history.pushState('', '',
location.href.split('?')[0]); after 1 minute using setTimeout method, this method belongs to the window object (if you're using a browser) and as window is the object that holds everything so writing window.setTimeout(...) is optional JavaScript knows we're referencing window even we didn't write it. So we split the current URL by ? character we get an array as a return and we replace the current URL by the first column in that table.
With that the query string will be removed from the URL without refreshing the page.
EDIT:
to show the message in a p tag that we will be deleted after 1 min alongside with changing the URL, change this:
if(isset($_GET['message'])) {
$successMessage= "Your Request has been sent to Admin.you will get mail with in 24hrs";
}
into this:
if(isset($_GET['message'])) {
$successMessage= '<p id="message">Your Request has been sent to Admin.you will get mail with in 24hrs</p>';
}
and then change the above JavaScript that I gave it to you with this:
setTimeout(function() {
history.pushState('', '',
location.href.split('?')[0]);
var msg = document.getElementById('message');
msg.parentNode.removeChild(p);
}, 60000); // 1 min = 1000 ms * 60 = 60000
And now you MUST to put that script in script tag just before </body>
So another EDIT to meet your needs:
just put this script in a script tag without changing anything else in your PHP code:
setTimeout(function() {
window.location.href = window.location.href.split('?')[0];
}, 60000);
with that, the page will automatically be refreshed after 1 minute, thus no GET['message'] will be included and therefore no message will be displayed in the page.
Hope I pushed you further.
Am here if you want any further explanations.

I think, you are need that:
setTimeout(() => location.search = "", 2000);
2000 - is a delay in milliseconds.
You should place that code in script tag at the bottom of your page.

Related

JSON array values, appending to URL and refreshing

I'm trying to do a form of URL cycling but instead of given URLS, I want to append values from a JSON object to the url and cycle those.
I have the main idea working but it's not quite right. Right now the link to the page in question carries a value for 'display' so an example would be
showdisplay.php?display=3
This runs a query to get all page info for any pages assigned to display 3, and this works.
What I want, once that query returns my result which is then JSON encoded, is to loop throught the JSON object, append the pageID of the first element in the URL, and after the duration of the element (in seconds) refresh the page and do the same thing again. Continue looping this and going back to the first element at the end of the object.
SO given this JSON object:
[{"pageID":"104",
"display_id":"3",
"duration":"56",
"page_id":"104",
},
{"pageID":"116",
"display_id":"3",
"duration":"54",
"page_id":"116",
}]
Here's what I expect when clicking the link ```Link to Page:
On immediate pageload, the URL would be showdisplay.php?display=3&pageID=104
After 56 seconds ('duration' in JSON), refresh page and set URL to showdisplay.php?display=3&pageID=116
After 54 seconds, refresh again back to pageID 104
Basically, when following that link, the url should never just say showdisplay.php?display=3 but should always have a pageID assinged to it from the JSON
My script:
<script type="text/javascript">
let obj = <?php echo $showDisplays; ?>;
let params = new URL(document.location).searchParams;
params.set("pageID", obj[0].pageID);
params.set("display", obj[0].display_id);
let url = window.location.href.split('?')[0];
let nextURL = url + "?" + params.toString();
window.setTimeout(function () {
window.location.href = nextURL;
}, obj.duration * 1000);
obj.forEach(function(o){console.log(o)})
</script>
I've been stuck on this for days and have no idea what I'm doing wrong or how to loop this properly. I feel like it shouldn't be too dificult but I'm not a JS coder by nature and I'm totally stuck. Can anyone help me rectify this and loop properly?

setTimeOut on a redirect function to redirect twice

Update -- Im working on a simple function which after click redirects you to an external page with the product you choosed in a form. the thing is that I need to do first a redirect to a "thank you for your purchase" page and then redirect to the external... this is my code and how I tried to do it.
function addToListAndRedirect(item_id){
var email = jQuery("[name='your-email']").val();
var amount = jQuery("[name='vinbrevet-contact-amount']").val();
var subscription = {
ListIds: [
"beeb2f48-5265-443e-960f-4f995d8c2942"
],
ConfirmationIssue: { IssueId: "cd081857-4f30-4da1-ab5c-a7883f62d99c" },
Contact: {
Email: email
}
}
window.location.href = "http://vinbrevet.se/success?items="+ item_id + ":" + amount;
jQuery.post("http://ui.admlo.se/Api/Subscriptions/c03a4119-f6a8-4d86-b34f-f16177ec7912", subscription).always(function() {
function redirectToExternal(item_id, amount) {
window.location.replace("https://www.systembolaget.se/dryckeslista?items="+item_id+":" + amount);
}
});
}
and on /success
function redirectToExternal(item_id, amount) {
window.location.replace("https://www.systembolaget.se/dryckeslista?items="+item_id+":" + amount);
}
setTimeout("redirectToExternal()", 5000);
now the redirection works great but I can't get the item_id and amount? should I duplicate the whole function also in /success?
So is like this: you post your purchase go to "/success" page and after 5 seconds it will redirect to the external page with the item_id. Where Im doing it wrong?
Your success page should take the product id in the url, and the second redirect script should be on the success page.
window.location.href = "http://dryckesbrevet.se/success";
The code below that won't run as you are now on a different page!
Try something like:
window.location.href = "http://dryckesbrevet.se/success?id="+product_id;
Then put your setTimeout() on the success page, grab the id and redirect!
You can't redirect two times. As soon as you set location.href your browser will be moving to it and any further actions will not take effect.
You need to pass second redirect url to first page, and from first page make redirect after 5 seconds.
location.href='http://dryckesbrevet.se/success&redirect='+encodeURIComponent("http://ui.admlo.se/Api/Subscriptions/c03a4119-f6a8-4d86-b34f-f16177ec7912")
success page shows message
success page executes setTimeout("redirectToExternal()", 5000); to redirect to external page provided in &redirect=???.

Updating total number on website with jQuery / Javascript?

This below is displaying Total racers on my website but its not updating live. I need to referesh the page to grab the new number from the database, so what's the simple way of updating it live with jquery/javascript without refreshing the page? Thanks a lot for taking the time to check my question and possibly answer.
<div id="stats">
<div id="racers">
<span><?=number_format($racers, 0, ' ', ' ')?></span>
RACERS
</div>
</div>
Jquery Ajax:
$.post('page.php', {
postVariable : value
}, function(data) {
//do something with data retrieved from php script
});
You set 'page.php' to a script that gets the data you want and echoes it.
You then retrieve what was echoed in the callback function(data);
So data will be the variable containing the value you need. You put this script in a
javascript function and call it when you need to make a request for information on the back-end.
If you have questions let me know. If you need more information on the ajax request you can find it here as well: api.jquery.com/jquery.post/
What you need to do this is the following:
1. Have an action in a controller that outputs the total number of racers
For example:
class Data extends CI_Controller {
public function GetTotalRacers() {
// This is dummy data. You need to replace this code with the correct
// number of racers retrieved from the database
echo 14;
}
}
Take note of where this action is. I'm assuming codeigniter will make the path something like /Data/GetTotalRacers in this case (that depends on how your route rules are configured).
2. Use JavaScript to ask the server for the data and display the result on the page
I recommend you have a method that runs every X number of seconds to refresh the total number of racers. To achieve this, you can use setInterval. Within the setInterval's function have an ajax call to your action. Finally, display the value that's returned from the server:
setInterval(function() {
$.ajax({
// Replace the url value with the correct url to access your action
url: '/Data/GetTotalRacers',
cache: false
})
.done(function( totalRacers ) {
$("#racers span").text(totalRacers);
});
}, 60000); // ex. Update every 60000ms
Note: I've never used codeigniter, but hopefully this description will help set you on the right path.

Periodically autosave form

How to implement a periodical save of a form in the background? Same kinda thing that gmail does.
setInterval(function(){
var form = $('#my-form-id');
var method = form.attr('method').toLowerCase(); // "get" or "post"
var action = form.attr('action'); // url to submit to
$[method](action, form.serialize(), function(data){
// Do something with the server response data
// Or at least let the user know it saved
});
},10000); // do it every 10 seconds
If you don't want to use the method of the form, but always want to use 'post', then use:
$.post(action, form.serialize(), ... );
And, if you want to supply your own action for the autosave that is different from the action for the actual save:
$.post("/autosave/comments", form.serialize(), ... );
You would need a timed loop on the client side that would save the form every x seconds/minutes. A crude way of doing this would be to have a setTimeout javascript function that collects the form's field values and updates the model via an update (PUT in Rails' case) AJAX request.
Example
Here's a crude way of doing it (i.e. there might be a better way):
// repeat every 10 seconds
var repeatTime = 10 * 1000;
function updateModel(){
// get field values (using jQuery, etc.)
// make ajax request using these field values
//(make sure put parameters match model attribute names)
console.log('updated');
setTimeout(updateModel, repeatTime); // start call over again
}
setTimeout(updateModel, repeatTime);
I included the console.log so that you can test this out in Firebug right now and see that the updateModel executes every 10 seconds. I would recommend using jQuery to generate the PUT AJAX requests.
Why not do this purely on the client, using a local database (or whatever)? That should reduce complexity, server load and bandwidth usage.
Permanent or per-session storage -- whatever's appropriate -- and you can save after every keystroke: no need for setTimeout().
Sisyphus.js: Gmail-like client-side drafts and bit more. Plugin developed to save html forms data to LocalStorage to restore them after browser crashes, tabs closings and other disasters.
http://sisyphus-js.herokuapp.com
Smashing Magazine article: http://coding.smashingmagazine.com/2011/12/05/sisyphus-js-client-side-drafts-and-more/
Version that works without jquery:
function urlencodeFormData(fd) {
var s = '';
function encode(s) { return encodeURIComponent(s).replace(/%20/g,'+'); }
for (var pair of fd.entries()) {
if(typeof pair[1]=='string') {
s += (s?'&':'') + encode(pair[0])+'='+encode(pair[1]);
}
}
return s;
}
setInterval(function() {
var form = document.getElementById('my-form-id');
var request = new XMLHttpRequest();
request.open(form.method, form.action);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded')
request.send(urlencodeFormData(new FormData(form)));
}, 10000);
If you need to do something with the server response see this post: https://blog.garstasio.com/you-dont-need-jquery/ajax/#posting

jQuery animation only if ajax information is not the same

I have a timer every 20 seconds using setInterval, it uses jQuery's ajax function load() to set the toparticles div with the information from another URL on site. Once that load is successful, it performs a jQuery highlight effect on the first article in the toparticles div. All articles on both places are held in their own seperate table, so I use #toparticles table:first.
I only want to perform the loading into the toparticles div, AND the animation if the first article is not the same.
So the concept is as follows:
Every 20 seconds:
Check this url, if the first table isn't equal to the first table of the page you're on, reload the entire div with that url's information, then perform highlight animation.
My current code:
setInterval(function() {
$("#toparticles").load("http://myarticles/feed/of/top/articles", function()
{
$("#toparticles table:first").effect("highlight", {color:"#f2f37f"}, 1000);});
}, 20000);
Thanks if you can provide any help.
A naive approach (best would be to have some sort of id) is
setInterval(function() {
var first_html = $("#toparticles table:first").text();
$("#toparticles").load("http://myarticles/feed/of/top/articles", function()
{
if ( first_html == $("#toparticles table:first").text() )
{
$("#toparticles table:first").effect("highlight", {color:"#f2f37f"}, 1000);
}
});
}, 20000);
It stores the text of the first table in a variable before the ajax call, and then compares it to the new first table. (i only check for text, you could change that to .html() to check for the whole html structure if you want that level of detail)
You could probably change your request to use jQuery.ajax(). It has an "ifModified" option. From the docs:
ifModifiedBoolean
Default: false
Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data.
jQuery.ajax() documentation
Also, I haven't checked myself but it seems as though they have an example that uses the .load() function's call back:
$("#success").load("/not-here.php", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});

Categories