How to prevent window.onload from repeating itself - javascript

I am trying to execute a js action that automatically sends informations to the URL for future use with php. To do so, I added a "onload" event on the window object and modified the URL in the listener. This is what it looks like so far:
window.addEventListener("load", function() {
window.location = "?test=test";
}, false);
When I load the page, the URL changes, but this is repeated over and over until the browser crashes. I was just wondering if there was a way to only execute it once.

If you don't want to use AJAX, and don't want to write JS functions to parse query strings, why not a simple:
<?php if(!isset($_GET['test'])): ?>
<script>
window.addEventListener("load", function() {
window.location = "?test=test";
}, false);
</script>
<?php else: ?>
<!--No JS written on the page, so no redirect -->
<?php endif;?>
But you really should look into AJAX, try using some JS framework like jQuery to help you in the process: http://api.jquery.com/jquery.ajax/

Check to see if you're already ON that page, before redirecting.

Add a simple flag on the URL like so: window.location = "?test=test&second=true";

As suggested in How can I get query string values in JavaScript?
Write a function to check get the URL params in JS GetQueryStringParams()
Then as suggested by others pass a send param in while reload
window.location = "?test=test&second=true";
Use the function in JS to check if you have a URL query string second and if its not there then reload the page

if you want to pass variables do this:
<?php
if(!isset($_GET['page'])){ //this line check if the variable field is available
$a = "Blank";
}else{
$a = $_GET['page'];
}
?>
that is it.

You could just erase the onLoad method once it's run, like so:
<script>
function doLoadStuff()
{
doSomeStuff();
//Clear onLoad contents
body.onLoad = function() {};
}
</script>
<body onLoad="doLoadStuff();">MyContent</body>

Related

variable value to php base_url function

Below is my jQuery Code:
<script>
$(document).on('click','.quickview', function(){
var **image** = $(this).attr('image');
var testimage = document.getElementById('quickimage');
testimage.src= "<?= base_url().'assets/product_images/'.image.".png"?>";
});
</script>
I want to use this image value to the src attr of img which is in a modal, what is the best way can please help? I will be very thankful to you.
You can't use JavaScript variables in PHP, since PHP runs on the server and finishes before the page is sent to the browser.
But you don't need to use the JS variable in PHP. You can do the concatenation in JavaScript.
testimage.src= <?= json_encode(base_url()) ?> + `assets/product_images/${image}.png`;

Javascript on webpage not changing text

I have the following script at the bottom of my php page, it runs on pageload, but I need it running every 10 seconds. It only runs on page load.
PHP is running.
I've tested this with a countdown from ten, and the script is actually looping, but for some reason not when i integrate this PHP.
Please help.
<script>
var CurrentBranch = "<?php echo file_get_contents('gitstatus.txt'); ?>";
var x = setInterval(function () {
CurrentBranch = "<?php echo file_get_contents('gitstatus.txt'); ?>";
document.getElementById("CurrentTestBranch").innerHTML = CurrentBranch;
CurrentBranch = "";
}, 10000);
</script>
Edit:
The code does display the file contents the first time around. But does not refresh when I make a change and save it.
Your PHP code is run only when the page loads. It generates string literals when it runs. These do not get updated when the interval function gets called repeatedly (because the PHP does not run again).
If you want to get new data from PHP you need to make new HTTP requests.
You could either reload the entire page, or use XMLHttpRequest (or fetch) to call a web service that gives you the data you want (Ajax is a useful search term).
PHP happens before HTML hits the server.
Look up setTimeout() javascript command. What you need to do is get javascript to call another php script, which checks and echoes your value.
Something like this (could be pseudocode, from memory):
setTimeout(function(){
var CurrentBranch = $.get('/url/that/sends/value');
// do something with your value, call a function, whatever
}, 10000);

Pass javascript variable to external php file

Yes, there are lots of questions to similar stuff but I can't figure it out, sorry.
I have a file with some javascript variables, depending on user input (but no form) and a normal HTML link to my php file.
<script>
function doStuff() {
var a = 'foo';
var b = 'bar';
window.location = 'newfile.php?a=' + a + '&b=' + b;
}
</script>
go to new php file
That works fine, I can access the data in newfile.php with $_GET.
newfile.php:
<?php
$a= $_GET['a'];
$b= $_GET['b'];
echo($a,$b); // works
?>
But I'd like to use POST. I guess I have to use ajax for that but how exactly?
jQuery is included btw so I could use $.ajax()
Any help is highly appreciated :)
EDIT:
Thanks for the quick response guys!
The JSON parsing doesn't work, I can't really figure out why - after clicking on the button the browser window disappears for a split second and I'm on the same page again which is unresponsive now :(
I went with the following code:
jQuery.post('newfile.php',{'a': a, 'b': b}); //curious: with or without ''?
setTimeout(function () {
window.location = 'newfile.php';
}, 5000); //this will redirct to somefile.php after 5 seconds
newfile.php:
$a= $_POST['a'];
$b= $_POST['b'];
echo('Testing: '.$a);
Right after clicking I can see the correct output in Firebug (Testing: foo) but of course after redirecting to the site the values are lost and I'm left with "Testing: "
What can I do?
You can use ajax to achieve this. Following is the code which works on a button click or anchor click.
HTML
<button type="button" id="button1">Click me </button>
Ajax
$('#button1').click(function() {
var a = $('#IDofYourFormelement').val();
var b = $('#IDofYourFormSecondElement').val();
$.post('/somefile.php', {'somevariable': a, 'variableB': b}, function(data) {
var parsed = JSON.parse(data);
if (parsed == 'success') {
setTimeout(function () {
window.location = '/somefile.php';
}, 3000);//this will redirct to somefile.php after 3 seconds
}
else
{
alert ('Invalid details');
}
});
});
and then in your somefile.php you can access it as
$a = $_POST['somevariable'];
$b = $_POST['variableB'];
//do some stuff and return json_encoded success/failure message
You can use the new with HTML5 FormData();
Code snippet from https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects see also https://developer.mozilla.org/en/docs/Web/API/FormData and http://caniuse.com/#feat=xhr2 for browser support
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
I guess you are trying to post the variables using javascript and display the page post executing your post variables. Found a similar question and an answer in here - JavaScript post request like a form submit.
EDIT
The window.location will call another instance of you page and then will assign or replace the current doc, hence your previous post parameters are lost. If you want the page with your post parameters passed you need to do a form submit to your php page with method=POST also with the post parameters. That's what is written in the above stackoverflow link I shared.

Having issues pulling a GET value from a URL, Not sure what I'm doing wrong

I'm working on a link disclaimer page for internal use and on of the issues I'm having is getting the outgoing URL into the link on the page. The code below is what I'm using to grab the GET value I need and put it in the link's href attribut after decoding. The other half of the code uses the built-in Javascript encodeURIComponent() function, so unless I can use the PHP decode function, or if there's a dead simple way to grab the GET value I need using Javascript, I'm going to use PHP to place it in the Javascript on the server side. I know it works and it only takes a few lines of PHP code to grab and validate what I need.
That said, the code is below and I'll also provide a link to the page so you can see what's going on.
jQuery(".btn-continue").attr("href") = "\"" + decodeURIComponent(
<?php
if(isset($_GET["outlink"])){
echo $_GET["outlink"];
}else{
echo "/";
}
?>
);
This is the page that has the code in action: http://radboxstudio.com/you-are-now-leaving-radboxstudio-com.html?outlink=http://google.com/
Clicking the first link to Google on this page should take you to the page above: http://radboxstudio.com/
There's a bit of Javascript that is supposed to encode the link's href and pass it on using get. I've included the relevant code below in case I screwed up there. currentDomain is defined in an earlier bit of code and I know that works as it is supposed to.
$('a').each(function() {
var $a = jQuery(this);
if ($a.get(0).hostname && getDomain($a.get(0).hostname) != currentDomain) {
$a.click(function(event) {
if (!confirmed) {
event.preventDefault();
event.stopPropagation();
var url = encodeURIComponent($a.get(0));
window.location = "http://radboxstudio.com/index.php?option=com_content&view=article&id=10&outlink=" + url;
}
});
}
});
To set the value of href by using the attr() function of jquery you should use it like this:
$("selector").attr("href", "value_you_want");
Checkout jquery api: http://api.jquery.com/attr/
Turns out the PHP was doing the work for me. The code below works.
<?php if(isset($_GET["outlink"])){
$outlink = $_GET["outlink"];
}else{
$outlink = "/";
}
?>
Linky
Sorry for the trouble. :D

use variable with window.location.href

I was wondering how I would be able to execute a command such as this in javascript. I just want to store the url as a string in a variable and redirect them to it when the time comes -
var linkz = "http://www.google.com/";
window.location.href= linkz;
Why doesn't this work?
Thanks,
If you're using links this way (as mentioned in a comment):
Google
Then the problem is that you're not passing a string to your checkCk() function.
Try this:
Google
The code you used for window.location.href should work.
At this point, I don't see why you'd use javascript if all you're doing is replacing the default behavior of the link.
I've just tried on my local machine, and it works:
<script>
window.onload = function(){
var google = "http://google.com";
window.location.href = google;
}
</script>
Redirecting to google...
Copy this to new file, call it for example redirect.html and open it in your browser.
Update:
<script>
var redirect = function(new_place) {
window.location.href = new_place;
}
</script>
<a href='javascript:redirect("http://google.com")'>Go to google</a>

Categories