setTimeout and window.location (location.href) not working - javascript

I want to redirect user to index.php in 5 seconds, but it redirects me right away. I don't want to use jQuery in this simple code.
<script>
setTimeout(function(){location.href="index.php", 5000} );
</script>

This is the right way...
setTimeout(function(){location.href="index.php"} , 5000);
You can check the docs here:
https://developer.mozilla.org/en/docs/DOM/window.setTimeout
Syntax :
var timeoutID = window.setTimeout(func, [delay, param1, param2, ...]);
var timeoutID = window.setTimeout(code, [delay]);
Example :
WriteDatePlease();
setTimeout(function(){WriteDatePlease();} , 5000);
function WriteDatePlease(){
var currentDate = new Date()
var dateAndTime = "Last Sync: " + currentDate.getDate() + "/"
+ (currentDate.getMonth()+1) + "/"
+ currentDate.getFullYear() + " # "
+ currentDate.getHours() + ":"
+ currentDate.getMinutes() + ":"
+ currentDate.getSeconds();
$('.result').append("<p>" + dateAndTime + "</p>");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="result"></div>

This also works:
setTimeout ("window.location='index.php'", 5000);

I know this thread has already been solved and its somewhat 2 years later that i have come accross this, I personally just used the example from Joan's answer and modified it to work exactly how i need it to as the location.href will not redirect the TOP or Parent page when called within an iframe.
So for anyone looking for a way to redirect after 5 seconds but within an iframe and to redirect the TOP / Parent page aswell here is how i have achieved that based on Joan's answer to the Original Question.
<script type="text/javascript">
setTimeout(function(){window.top.location="index.php"} , 5000);
</script>
And if you wanted to call this by using PHP as i personally did do here is how you would use the echo command to redirect the user after 5 seconds.
echo '<script type="text/javascript">setTimeout(function(){window.top.location="index.php"} , 5000);</script>';
Hope this helps anyone else searching for the same solution.
Thanks

Related

Cannot get jQuery/JS redirect button to work

I am newish to jQuery. I am trying to unset a cookie and then go to the next page.
There are quite a few answers on this subject here and elsewhere. I thought this would be very straightforward but about two hours later I know I must be doing something dumb.
Simple button:
<button class="btn btn-success" id="showInfo">Show intro</button>
Tweaked borrowed function that works nicely:
function setCookie(cookieName, cookieValue, daysToKeep)
{
var d = new Date();
d.setTime(d.getTime() + (daysToKeep*24*60*60*1000));
var expires = "expires="+ d.toUTCString();
document.cookie = cookieName + "=" + cookieValue + ";" + expires + ";path=/";
}
"Simple" function call on button click:
<script>
$("#showInfo").on("click", function()
{
setCookie("button1","",-1 );
$(location).attr('href',"2.php");
// window.location.assign("2.php");
// window.location.replace("2.php");
})
</script>
I have tried windows replace, assign and href. I have tried jQuery $(location).
I know I am doing something stupid because even when I comment out the setCookie function call nothing happens with any of these.
if your button is inside a form, it's better to use preventDefault to avoid those problems. Modify your function with the following:
<script>
$("#showInfo").on("click", function(e)
{
e.preventDefault();
setCookie("button1","",-1 );
window.location="2.php";
})
</script>

Why is my for loop not working in my JSON function?

Hey Guys im new at coding and working right now on a Twitch Viewer. (FreeCodeCamp)
Im able to get information from the JSON file and show it through my html code.
But my problem is that i cant get the names from my "gamer" array.
Why is the for loop not working in the json function?
Thank you very much for your help!
var gamer = ["OgamingSC2","ESL_SC2"];
for(i=0;i<(2);i++){
$.getJSON('https://api.twitch.tv/kraken/streams/'+gamer[i]+'/?callback=?', function(json) {
$('.list').append("<b>Name: " + gamer[i] + "</b><br>");
var logo = json.stream.channel.logo;
$('.list').append("Game: " + json.stream.channel.game + "<br>");
$('.list').append("Status: " + json.stream.channel.status + "<br>");
$('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>");
console.log(json);
});}
img {
width: 5em;
border-radius: 10px;
}
<head><script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> </head>
<body>
<b>Twitch.tv JSON API</b> </br>
<div class="list"></div>
</body>
What happens here is the $.getJson is an asynchronous call, which means that it will execute only after all of the sync operations are executed. So, the for loop runs twice, and two getJSON callback functions are added to the function stack.
Now as Javascript has lexical or functional scope, the variable i lives on in the global scope as 2 (as the final i++ also has executed).
Next, the callback functions are executed one by one off of the function stack. But alas, your variable i is now 2! Now the callback functions would only see gamer[2] which doesn't exist and this throws an undefined
If you add a console.log(i) to your $.getJSON, you'll see that it outputs only 2 two times.
Why don't you try this:
var gamer = ["OgamingSC2","ESL_SC2"];
gamer.map(function(gamer) {
loopIt(gamer);
});
function loopIt(gamer) {
$.getJSON('https://api.twitch.tv/kraken/streams/'+gamer+'/?callback=?', function(json) {
$('.list').append("<b>Name: " + gamer + "</b><br>");
var logo = json.stream.channel.logo;
$('.list').append("Game: " + json.stream.channel.game + "<br>");
$('.list').append("Status: " + json.stream.channel.status + "<br>");
$('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<head><script src="http://code.jquery.com/jquery-1.11.2.min.js"></script> </head>
<body>
<b>Twitch.tv JSON API</b> </br>
<div class="list"></div>
</body>
i think it json gives nothing because you put callback=?
when you pass ? in call back variable it take value with ? and gives nothing.
so just put callback= .dont give any values and try again. and just alert json variable in function. you will know value is coming or not. i dont found nothing wrong with loop and json link.
For this types of server call in for loop , you can use custom loop.
Like this, https://jsfiddle.net/s8eLhxpx/
var gamer = ["OgamingSC2","ESL_SC2"];
var initCounter = 0;
callServerData()
function callServerData(){
$.getJSON('https://api.twitch.tv/kraken/streams/'+gamer[ initCounter ]+'/?callback=?', function(json) {
$('.list').append("<b>Name: " + gamer[ initCounter ] + "</b><br>");
var logo = json.stream.channel.logo;
$('.list').append("Game: " + json.stream.channel.game + "<br>");
$('.list').append("Status: " + json.stream.channel.status + "<br>");
$('.list').append("Logo: " + "<img src=" + logo + ">" + "<br><br><br>");
console.log(json);
initCounter++
if(initCounter < gamer.length){
callServerData();
}
});
}

Autofill input text on Sharepoint 2007 using Jquery

im sure this is a simple question but can't understand why this isn't working. I simply want to set the current time automatically to an input field. I am using Jquery at the moment to accomplish the task. I know jquery works because if I do alert (time); it shows me the time as expected.
Just to add, I set the jquery script in a text then referenced into a Content Editor Webpart under the list.
Below is the HTML of my input generated by Sharepoint. I decided to target the title as its the only consisting attribute in there.
<input type="text" class="ms-long" title="Current time" id="ctl00_m_g_dd7a368d_cc10_4464_a245_c7fc87ae6650_ff2_1_ctl00_ctl00_TextField" maxlength="255" name="ctl00$m$g_dd7a368d_cc10_4464_a245_c7fc87ae6650$ff2_1$ctl00$ctl00$TextField">
Below is the Jquery script I am trying to run. A the moment this script does nothing to my input text box.
<script src="//code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
var time = (dNow.getMonth()+1) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();
$("input[Title='Current time']").val(time);
});
</script>
Any help would appreciated on this.
I tested your code and it works fine if you define the dNow first: tested on Chrome and Opera
jQuery(document).ready(function($) {
var dNow = new Date();
var time = (dNow.getMonth()+1) + '/' + dNow.getDate() + '/' + dNow.getFullYear() + ' ' + dNow.getHours() + ':' + dNow.getMinutes();
alert(time);
$("input[title='Current time']").val(time);
});
If that's not working for you, you have some other problem in your JavaScript, debug and check for other errors

Jribbble - How do I load 6 shots at a time

I'm a bit new to Javascript, but I've managed to get things to load to the page which is a start.
I'm trying to load 6 "shots" to a page with this script, but it currently loads them all:
<script type="text/javascript">
$(document).ready(function getDribbbleShots() {
$.jribbble.getShotsByPlayerId('abenjamin765', function (playerShots) {
var html = [];
$.each(playerShots.shots, function (i, shot) {
var str = (''+shot.description+'');
html.push('<div class="col-md-4"><div class="thumbnail"><a href="' +shot.image_url+ '" target="_blank">');
html.push('<img class="shot-image" src="' + shot.image_url + '" ');
html.push('alt="' + shot.title + '"></a>');
//html.push('<div class="caption"><h4>'+ shot.title +'</h4>');
//html.push('<div class="ellipsis">'+shot.description+'</div>');
html.push('<p class="imgTitle">' + shot.title + '</p></div></div></div>');
});
$('.dribbble-feed').html(html.join(''));
//$( ".ellipsis p" ).addClass( "ellipsis" );
}, {page: 1, per_page: 9});
});
</script>
I also I want to introduce a "load more" button that will load 3 shots at a time.
Any help would be greatly appreciated :)
Cheers
If you use playerShots.shots.slice(0, 2), the loop will go through just the first three "shots."
Documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
As far as loading more, you'll want to save the result from the API response to a variable accessible by your code that shows more "shots."

How would I remove from spaces from a search form using jQuery?

I've replaced the submit URL from the search form with this jQuery snippet:
<script type="text/javascript">
$(document).ready(function() {
$('.search-form').submit(function() {
window.location.href = "/search-" + $('.search-form input:text').val() + "-" + "keyword"+ "-"+ "keyword2/" + $('.search-form input:text').val() + ".html";
return false;
});
});
</script>
This works fine and turns the URL into a nice SEO cleaned URL. But how can I replace the spaces?
When someone types in "search me" the URL looks like /search-search me-keyword-keyword2/search me.html with spaces. With + or - it would look much better. I know of str_replace from PHP, but how would I go about this in jQuery?
There's a native JavaScript function called encodeURIComponent that's intended to do exactly what you need.
window.location.href =
"/search-" +
encodeURIComponent($('.search-form input:text').val()) +
"-" + "keyword" + "-" + "keyword2/" +
encodeURIComponent($('.search-form input:text').val()) +
".html";
Method 1: Using Replace
<script type="text/javascript">
$(document).ready(function() {
$('.search-form').submit(function() {
var value = $('.search-form input:text').val();
value = value.replace(' ', ''); // replace
window.location.href = "/search-" + value + "-" + "keyword"+ "-"+ "keyword2/" + value + ".html";
return false;
});
});
</script>
Method 2: Encoding URL
<script type="text/javascript">
$(document).ready(function() {
$('.search-form').submit(function() {
// encode url
var value = encodeURIComponent($('.search-form input:text').val());
window.location.href = "/search-" + value + "-" + "keyword"+ "-"+ "keyword2/" + value + ".html";
return false;
});
});
</script>
Note that replace method would work even in JQuery because Jquery is simply library of javascript :)
http://www.w3schools.com/jsref/jsref_replace.asp
replace() method is native javascript. That'll get you what you want.
You could remove spaces with using mod_rewrite. It’s quite useful way. You can also remove spaces from URLs by replacing spaces by %20, but that only helps with spaces and won't escape other characters. What you really need to do is use a URL-escaping function.

Categories