YOURLS Redirect with Javascript - javascript

Currently I am using YOURLS PHP URL shorterning script.
In their functions.php, seems like they support both redirection which is with PHP header location and javascript.
Functions.php
I want to redirect with javascript, which will show me the message before redirect. I found this coding inside functions.php
// Redirect to another page using Javascript. Set optional (bool)$dontwait to false to force manual redirection (make sure a message has been read by user)
function yourls_redirect_javascript( $location, $dontwait = true ) {
if( $dontwait ) {
echo <<<REDIR
<script type="text/javascript">
window.location="$location";
</script>
<small>(if you are not redirected after 10 seconds, please click here)</small>
REDIR;
} else {
echo <<<MANUAL
<p>Please click here</p>
MANUAL;
}
}
But I don't know how to do it. Is that coding currently commented or ? What should i change to redirect with javascript ?
Please help me out. Thanks.

The function is all ready to go. A javascript redirect will occur on the client side, so this script outputs the appropriate javascript. Call it like so:
<?php # http://www.myurl.com/was/here.php
yourls_redirect_javascript('http://www.myurl.com/go/here.php');
?>
When this page loads javascript will be used to redirect the user. If the javascript fails, there will be a link for them to click to follow the redirect.
I suspect that the "here document" syntax is throwing you off a bit. Read the PHP Docs to learn more about echo <<<
http://php.net/manual/en/function.echo.php

Related

Update HTML content with data from external PHP post request

I have two pages. mobile.html and video.php. mobile.html sends an ajax post request with a single variable. video.php should read that variable and pass it to a JS function in the same page that would change a video control. I tried to use this logic:
mobile.html sends an ajax post request
video.php has PHP code inside a div to read the request and get the variable
reload video.php and allow the JS code in the same page to get the variable from inside the div
pass the variable to the intended JS function in video.php.
execute the function on the video.
here is my code and for simplicity I replaced the video with <p> tag. mobile.html code works fine. my problem is in video.php
mobile.html
$.post("video.php", {gesture: action}, function(response){
$("#result").html('response: '+response);
});
video.php
<html>
<head>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
//a div to hold the value of post variable
<div id="dom-target" style="display: none">
<?php
if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
if( isset($_POST["gesture"]))
{//put the variable value inside the div to fitch it later
$gesture = $_POST["gesture"];
echo $gesture;
}
else {
echo "none";
}
}
else {
echo json_encode("PHP no post");
}
?>
</div>
//p content should be updated with the value of $gesture
<p id="update">
should be updated with post variable using JS
</p>
<script>
//get post variable from the div
var div = document.getElementById("dom-target");
var myData = div.textContent;
$("#update").html(myData);
console.log("myData: "+myData);
</script>
</body>
</html>
I have been up over my head for a week trying to work around this problem but I cannot seem to get the result that I want because when I reload the page I find my variable in the ajax callback function :/
the output I am getting currently is "PHP no post" in video.php and myData: "PHP no post" in the console of video.php which is ok because obviously the first time I run the page it is not through a post request. however when I click the button that triggers the post request in mobile.html I get the output of this line console.log("myData: "+myData); with the correct data but in mobile.html console! not in video.php console. meaning that the code is run in the callback function of the ajax post request in mobile.html.
I failed to find a way to update the <p id="update"> in the currently opened video.php page. Now I am not even sure I can do it with PHP since it runs only on a server and JS runs only on the web browser.
My question is: can I do the steps explained above using PHP ?
IF YES can you help me figure out a way to dynamically and instantly update the video.php page using a post call sent from mobile.html ? or any other way that would work with PHP?
IF NOT can you suggest what other languages/platforms I can use to do what I want to do ?
UPDATE:
to have an idea of what I want to achieve, I did two pages using localstorage. open mobil.html in one window and then openvideo.html
in another window side by side. play the video then use the controls on mobile.html and see how it changes the playback in video.html.
I want to be able to do the same thing but remotely using PHP because I have to use a real mobile instead of mobile.html
You are sending your gesture value to the video.php file, but you are not using it to get a new paragraph element with the updated value in it. PHP should do its work on the server and JavaScript strictly on the frontend.
Keep your POST request the same.
$.post("video.php", {gesture: action}, function(response) {
$("#result").html('response: ' + response);
});
But modify the response that server returns. The gesture value is in the $_POST array. From there you can use it to render a new paragraph and echo or return this to the frontend.
<?php
// Set default value.
$gesture = 'none';
if ( isset( $_POST[ "gesture" ] ) ) {
// Overwrite if there is a gesture value.
$gesture = $_POST[ "gesture" ];
}
// Echo a new paragraph with the gesture in it.
echo '<p id="update">' . $gesture . '</p>';
exit;
?>
first just please organize the code a little bit so you can see the code well
you need to put the post request inside a function with a trigger action because with that it would be never called
you need to make sure that you are getting the correct data in 'action' variable (console.log it before the post)
(if $.post is not working for some reason download jquery and use it locally because it might not be in the slim CDN)
Hint:
$( document ).ready(function() {
console.log(gesture); //check this in the console after refreshing the page
$.post("video.php", {gesture: action}, function(response){
$("#result").html('response: '+response);
});
});
I am answering my own question for those who have been rumbling about not understanding how to update a part of a web page in real time without having to reload it. Long story short, To achieve the scenario I mentioned in my question I have to use WebSockets as #EmielZuurbier pointed out in the comments of the first answer, so thanks to him.
There are tons of ways to do that.For beginners, you have to be patient and make sure you understand how it works properly before you jump in coding. Also, know that some codes that are available on the internet work only on the backend and that there are specific ways to make websockets work on a browser. In my case I used Node.js in the server side and isomorphic-ws in the client side in a web browser
here are some helpful references that helped me during the past week:
Here is the official site for Node.js for installation and documentation.
This is a good video to get you started if you are new to WebSockets. it explains Websockets and display real implementation of it.
Here you can find documentatino of WebSocket().
This video demonstrate how to implement a websocket in your local
machine (aka laptop): How to Create a WebSocket Server & Client.
Be aware that the video above will work only on backend which you can run using Terminal on mac or Command line in Windows. To work it on a
browser I used isomorphic-ws which is a wrapper that allows
websockets to work on web browsers.
I wish this could help anyone who was stuck like me on how to implement a real time communication between two ends.

Redirect to another page on page load but only after a check is made

I am building a feature whereby a user can only view a job that they're given if they've agreed to the HIPAA guidelines. If they have already agreed, the job page will load as normal onclick, but if not, they should be redirected to the guidelines page.
I have tried a page redirect, but that gives me a 404 error. I have my program (PHP) checking a field in the database; if it's 1 then they have agreed and the job page should load as normal. If it is 0 then they should be redirected to the HIPAA page. I am calling a function on checking the database field:
<script type="text/javascript">
function hipaa() {
var referringUrl = window.location.href;
window.location.href = 'user/hipaa';
}
</script>
And
if ($result[0]->hipaa == 0) {
$url = $_SERVER['PHP_SELF']; // current page so user can return
hipaa(); // EDIT: removed this line
//Added these lines:
$urlNew = '/user/guidelines';
echo '<META HTTP-EQUIV-REFRESH CONTENT = "1; ' . $urlNew . '">';
}
The function gets called but the window.location.href gives me a 404 error. Any help would be much appreciated. I am a relative beginner in JavaScript.
EDIT: I updated my code to try and do it through PHP and I don't get an error now, but it doesn't redirect, it just stays on the same page.
Your META tag should look like this....
<?php
$urlNew = 'https://stackoverflow.com/questions/53988586/redirect-to-another-page-on-page-load-but-only-after-a-check-is-made';
echo '<meta http-equiv="refresh" content="1;URL=\'' . $urlNew . '\'" />';
?>
But if you look at the W3C standard, even way back to (3.2) pre-97, it states that redirects should always "when possible" be issued server-side or by giving the visitor a link that is directly clickable.
I ended up using JavaScript and after playing around for a bit, got it to work. My code is:
echo '<script type="text/javascript">window.location.href = "../guidelines";</script>';
Thank you to all who took the time to respond.

On redirect notification - PHP/JS

How can I make a Modal Box/Notification Box appear when I do header redirect or some other method of redirection to a page? Basically as a Success kind of thing. Like I click on send it opens a page and then brings them back to the same page where the send button is and will show a Success box? Any ideas?
If you need to trigger some code on a PHP page through an AJAX call you can do it without directly opening that URL. You just pass that PHP URL to a call, the PHP page code is executed and the response is returned back to the page where the request originated. It would look something like this:
<span id="someButton">Button</span>
<div id="someDivOnYourPage"></div>
<script>
$('#someButton').click(function(e) {
$.ajax('page.php', {
success: function(data) {
alert(data); //This alerts 'Hello from PHP!'
$('#someDivOnYourPage').html(data);//this will set 'Hello from PHP!' inside the #someDivOnYourPage div
},
error: function() {
alert('An error occurred');
}
});
});
</script>
page.php
<?php
echo "Hello from PHP!";
?>
A more detailed explanation with downloadable examples can be found here: jQuery Ajax POST example with PHP.
If it's just a login or something similar, you can store the message in a session on whatever page you're processing and then once the page has been redirected, put that session variable into a regular variable and unset your session. Then you'll just print out whatever as HTML or Javascript.
On the page you submit to
//Do your processing
$_SESSION['someReturnMessage'] = 'Success!';
header('Location:./originalpage.php');
On originalpage.php
//Top of file
if(isset($_SESSION['someReturnMessage'])){
$message = $_SESSION['someReturnMessage'];
unset($_SESSION['someReturnMessage'];
}
...further down the page where you want the message to show...
if(isset($message){
echo $message;
}
You could also use AJAX, which may be a better fit for doing simple tasks.
Using sessions can be a bad idea though, so make sure you don't use them when there are better solutions: Error messages stored in SESSION

Open Webpage Section/Tab on Form Submit / page reload

I am using a bootstrap theme and am trying to get my page's form to stay on/open the specific registration form's confirm message. Unfortunately with several Registration Forms on the page, each is "hidden" inside it's own hidden div/tab. I am not too good with JS and have spent about 4 hours so far trying to get this to function properly:
http://middlechambersociety.com/dev/mcs2014/
On any Registration Form completion I want the user to be brought back to and shown that Registration Form's Confirmation Message AND the "Pay with Card" button when it is part of the reg process (the button currently shows when it should). However, the problem is that when my form reloads the best i can do is bring users to the Registration Section and show the Golfer's Reg Form and/or Confirm message only (because it is the default open div/tab). I have tried php and limited JS/jQuery with no success. I have tried adding Class .active to the li i want to display but no luck. I currently have the following trying to fire on each form when submitted to TRY to get the appropriate registration tab to display:
<?php
if ($reg_type == 'Diners' && !empty($confirm_msg)) {
?>
<script type="text/javascript">
alert('Working1');
$(document).ready(function() {
alert('Working');
var tab = $('#reg_diner').parent();
alert(tab);
tab.addClass('active').siblings().removeClass('active');
});
</script>
<?php
echo '<div class="confirm-message">' . $confirm_msg . '</div>';
echo $stripe_pay_form;
}
?>
please help.
For anyone who may be confused as to what i am looking to accomplish: feel free to complete one of the forms (Dining for instance) and see that the confirm message is hidden until you PHYSICALLY navigate back to the Dining registration tab.
Maybe try an ajax call and on success add active class to new content?
My bad - misunderstood. Heres where I can see your error:
In console.log You've got an $ reference error at your script calling point. Cause you load jQuery in footer. So it cant use scripts before it load fully. (Document Ready doesn't work because he doesn't know this command yet) Put jQuery into head, or your tag after calling jQuery
I understand not wanted to navigate user to a different page but sometimes it is just much easier.
One way though would be to put a $_GET string in the form post then use that to control the display message. Add it to the form action url maybe:
enter code hereaction="index.php?form=golfer1"
Then update your code :
<?php
if ($_GET['form'] == 'golfer1') {
echo '<div class="confirm-message">' . $confirm_msg . '</div>';
echo $stripe_pay_form;
}
?>

Page Redirection

To help better explain my Question, here is what i have:
I am using a Precoded service, on it i have access to the Template HTML Files Only.
The URL to the Login page is : DynamicPage.aspx?Site=Mysite&WebCode=LoginRequired
The Main site URL would look like : DynamicPage.aspx?Site=Mysite&WebCode= or DynamicPage.aspx?Site=Mysite
What i need is a JavaScript I could put into the main header template file that would view "WebCode" And depending on whats entered redirect to a certain page.
I got from "Sitifensys" a code
Sitifensys
if (window.location.href!="foo.bar/login.php") window.location.href="login.php";
The problem with this code is even when i go to the main page it still redirects me to login.php which i do not want it to. I need this code to Read the "WebCode" If it is "LoginRequired" Redirect to "Login.php" else if redirect to "Test.php"
Hope this explanation is a bit better.
Try
window.location.href = "http://www.something.com/"
Don't do this that way. If you do anything in JavaScript it may be easily blocked by user. Better add and if() in your PHP code and then redirect to login, if user don't have specific session key:
if(!(isset($_SESSION['logged_in']) && true == $_SESSION['logged_in']))
{
header('Location: login.php');
die();
}
Just as answered earlier, you should add a window.location.href="somepage" somewhere.
Some where in your script :
if (window.location.href!="foo.bar/login.php") window.location.href="login.php";
This doesn't need to be in a listener for the page load event.
EDIT :
Regarding your new descriptionn I would use (but would not recommend;)) something like :
if (location.pathname.indexOf("WebCode=LoginRequired")>0) {
window.location.href="login.php";
}
Hope this will help.
if (location.pathname.indexOf(login.php) >= 0) {
//don't redirect
} else {
/...
}
You can add this script at the beginning of the body tag:
<body>
<script>
if((/WebCode\=LoginRequired/).test(window.location.href)){
window.location.href = window.location.href.
replace(/(\?|\&)WebCode\=LoginRequired/, '');
}
</script>
...
</body>

Categories

Resources