JSON array values, appending to URL and refreshing - javascript

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?

Related

How to sent data to server, remove parameter from url and reload window with new url Javascript, jQuery and PHP

I am currently stuck with a problem I can't seem to find a decent solution for.
Problem:
I have written some code that will send 2 parameters to an action within a PHP script through a url. I need these parameters sent to the action no matter what. However, after the parameters are sent, I need to remove one of said parameters from the URL and then reload the page with said new URL.
I hope I could give you a clear description of my problem. Following is the code I have written so far.
jQuery(document).ready(function() {
// Define array with the dashboard id and title as key => value pairs.
var dashboardArray = <?php echo json_encode(CHtml::listData($dashboards, 'iddashboard', 'title')); ?>;
// Loop through the elements in the dashboardArray and then create option elements to be added to the above create select element.
for (var idDashboard in dashboardArray) {
$('#idDashboards').append($(document.createElement('option')).prop({
value: idDashboard,
text: dashboardArray[idDashboard].charAt(0).toUpperCase() + dashboardArray[idDashboard].slice(1)
}));
};
// Get arg01 from the server.
var arg01 = <?php echo json_encode($arg01); ?>;
// Prepare URL variable and spike it with arg01 to be sent back to the server.
var url = 'Path/To/action/Index/index&arg01='+arg01;
// Button change and function tied to it. Instead of an ajax request, we reload the page completely.
$("#idDashboards").change(function() {
// Define dashboardIndex. The -1 stands for the option tag that has already been created.
var dashboardIndex = $(this).prop('selectedIndex')-1;
// Sent parameters to actionIndex in Controller and remove dashboardIndex after the request was successful.
if (url.includes(arg01)) {
window.location.href = url+"&dashboardIndex="+dashboardIndex;
console.log("Yes i was here");
}
// window.location.href = url; <---- Here is where the problem begins.
});
});

Remove query string from URL after some period of time in 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.

I have a query with upload real time data to load in div without refresh in jquery

I am making a chat function, in which I have put the chat records with while loop but I want to get new records with out refresh the div at the real time.
But If no record is updated new so div doesn't refresh because of scroll force me to bottom.
Use this (I guess u have php installed, you use a PHP page):
var ajaxurl = "updatepage.php(CORRECT URL HERE)";
var data = {};
data["CurBox"] = document.getElementById(IDOFCHATBOX).innerHTML
$.post(ajaxurl, data
, function (response) {
func(response);
});
and make sure you run checks on that the current chatbox is not already the same as when it would be updated! :)
use the post method inside the refreshscript to get the current chatbox contents

js refresh page while passing variable in yii

I am trying to refresh the page while pass an array from an onclick button.
Since I am using yii, posting isn't an option, and setting a session variable wasn't working. Any ideas would help. Thank you
<a style="width:100%;" onclick="my_picks_reset()" id="my_picks_reset">Reset</a>
<script>
$(function() {
/*set var picks = array of TBA and reset th my_picks div*/
$("#my_picks_reset").click(function() {
var my_picks = ['TBA','TBA','TBA','TBA','TBA','TBA','TBA','TBA'];
var url = document.URL;
$(location).attr('href',url,'my_picks',my_picks);
})
})
</script>
It seems from your comments that you're expecting POST request. Changing location of the page will give you GET request. So you have two options here:
1) Continue using location and read the the values from $_GET variable.
If you decide to use this option your need loop through my_picks array and construct the query string that would look like that:
?my_picks[]=arrayValue1&my_picks[]=arrayValue2... and do location.assign(currentLocation + composedQueryString)
2) The second better solution is to use $.ajax() to send values with post method.

Checking if a URL contains a value with javascript

I am working on a feature for my site that allows the user to use the back button and not have to load more database results.
I start by loading 16 results, and then there is a load more button which loads the next 16. In the ajax success i change the href of this button so the url changes to e.g. domain.com/#1 to #2.
I wrote this last night:
// First get the page URL and split it via # signs
var parts = location.href.split('#');
// now we run a check on the URL and see how many 'parts' there are
if(parts.length > 1)
{
var params = parts[0].split('?');
var mark = '?';
if(params.length > 1)
{
mark = '&';
}
location.href = parts[0] + mark + 'page=' + parts[1];
}
Which gets the URL, and redirects the user the same page but converts the fragment number to a page number. From this i then use a PHP $_GET and set the limit claus last value from that.
This works fine. But its primitive. Let for instance say i push back and the URL becomes:
www.domain.com/?page=1
If i then click to load some more data, the page url becomes:
www.domain.com/?page=1#2
If the user then visits another page and comes back then they get directed to:
www.domain.com/?page=1&page=1
Whats the best way around this? I was thinking of running a check on the URL at the same time as looking for a fragment and if the URL has a page variable i then add that variable to the fragment variable and the page URL becomes ?page=THE SUM NUMBER
Any help on modifying the snippet i posted above to check the URL for a page value and then add the two together before the redirection?
Thanks!
You need to use location.search to get the query string on a URL:
var queryParameters = location.search.split('&');
Then you can loop through the queryParameters and check if page is set:
var pageNumber = 0;
for(var i = 0; i < queryParameters.length; i++)
{
var keyvaluePair = queryParameters[i].split('=');
if(keyvaluePair[0] == 'page')
{
pageNumber = keyvaluePair[1];
break;
}
}
Please see the documentation on the MDN:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location
You might also find this example useful for returning one value:
https://developer.mozilla.org/en-US/docs/Web/API/Window.location#Example_.236.3A_Get_the_value_of_a_single_window.location.search_key.3A
If you want to get the information after the #, you need to use location.hash. The MDN documentation I linked also has information on location.hash.

Categories