PHP beginner - want to react to a click to redirect to another page

How can I code a simple PHP function, called from a htm page, to redirect from current web page to new webpage?

I am a complete novice with PHP.  The web hoster does support PHP.

eg.
in the htm
<OnClick=PHP_GoSomewhereElse()>

and in the PHP
PHP_GoSomewhereElse
{
  GoToWebPage("www.ainscow.ch/anotherpage.htm")
}
LVL 45
AndyAinscowFreelance programmer / ConsultantAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Paul MacDonaldDirector, Information SystemsCommented:
W3Schools has a great PHP tutorial - I recommend you browse through it.

That said, it's more typical to use an HTML <a> tag  (anchor tag) to move from one page to another:
<a href="http://www.ainscow.ch/anotherpage.htm">Ainscow's other page</a>
1
Dave BaldwinFixer of ProblemsCommented:
I agree.  There is no reason to go to the PHP page just to redirect.
0
Julian HansenCommented:
What is your thinking here?

A simple <a> tag will take you to a new page - so I am guessing there is more to this than simply going to another page.

Why did you want to go via PHP? As discussed above, PHP is a server side script - it can redirect a request sent to it (say you click a link) but if you are going to talk to the server asynchronously (through AJAX) then you have to control the redirect in the browser.

If you can explain the use case a bit more we can give you a more detailed explanation of how to go about it.
0
Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

AndyAinscowFreelance programmer / ConsultantAuthor Commented:
Thanks for the responses and as I said I am a beginner at PHP.

(If I asked how would I code in c# something to display Hello World in a window then a response such as open notepad.exe and type in Hello World isn't much use.  Agreed a simple <a> tag would achieve what I want rather more easily but it doesn't help me learn anything about PHP)

I asked a question like this because it would show me what I would require in a htm document to call a PHP function, what the PHP function would be coded like and what file I would need to store the PHP function in.


I'll have a look into the tutorial soon.
0
Chris StanyonWebDevCommented:
Hey Andy,

The fundamental thing to understand here is the difference between server-side and client-side. Technically, you don't call a server-side PHP function from within the client-side HTML. You make a request to a PHP script. May sound a little odd but it's a subtle difference.

<a href="somescript.php">Run some script</a>

Clicking on that link would send the user to that script and run it. That script could do whatever you wanted (connect to a database / generate some html / redirect to another page etc.)

You could also call that same script asynchronously (AJAX). This would effectively still call the PHP script, but it wouldn't send the user directly to it - it would effectively be run in the background. The browser could then just wait for a response from the script and act accordingly.

As an example on the question you asked, you could use something like the following:

//HTML
<a href="goSomewhere.php">Go Somewhere Else</a>

Open in new window

//goSomewhere.php
<?php
header('Location: http://www.ainscow.ch/anotherpage.htm');

Open in new window

Probably not really a great learning example as it would normally be done directly in HTML, but hopefully you get the gist.
0
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
Thanks.

>>You make a request to a PHP script.
Is that always synchronous unless one does something to make it asynchronous?

>><a href="goSomewhere.php">Go Somewhere Else</a>
Hmm.  I'd like to call a function within the php file, unless header is the function called automatically when no name is supplied.  I assume a php file can contain multiple functions.  Maybe a redirection isn't a good example of what the function would do.
Could the function for example take say two integers and return their sum which would be displayed client side.
0
Dave BaldwinFixer of ProblemsCommented:
An '<a href... link just does it, has nothing to do with synchronous.

A PHP page normally returns an HTML response when it is 'called'.  You can run any function you want.

The tutorial is Ok ( https://www.w3schools.com/php/default.asp ) but your best friend in PHP is the PHP web site full of info and examples.  http://php.net/
0
Chris StanyonWebDevCommented:
Is that always synchronous unless one does something to make it asynchronous?

Yes!

Calling a function inside a PHP script is a little tricky, and this is where the subletly comes in. As I said, you don't call a PHP function from HTML - you make a request to a script. Now that script will run top down as soon as it's called. You pass parameters to the that script through the normal HTTP request mechanisms, such as GET (URL querystring) or POST (HTML Form).

If you want to call a specific function, then you'll need to code accordingly. Take this as a very simple example:

<?php
switch ($_GET['method']):
    case 'add':
        echo add($_GET['num1'], $_GET['num2']);
        break;

    case 'subtract':
        echo subtract($_GET['num1'], $_GET['num2']);
        break;

endswitch;

function add($num1, $num2)
{
    return $num1 + $num2;
}

function subtract($num1, $num2)
{
    return $num1 - $num2;
}

Open in new window

This script will start running as soon as it's called. It will run through the switch to see what was passed in the querystring variable called method. That will dictate which function should be called. It then passes a couple of other querystring values into the relevant function. It echos out the return value of the relevant function call. Echoing out from PHP will be what shows up in the browser (or as an AJAX response). You could then call it in HTML like so:

<a href="myscript.php?method=add&num1=12&num2=7">Add</a>
<a href="myscript.php?method=subtract&num1=5&num2=3">Add</a>

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
Still struggling.
htm file:
<!doctype HTML public "-//W3C//DTD HTML 4.0 Frameset//EN">

<html>

<head>

<title>home</title>

</head>

<body>
This is some htm
<br><br>

<?php
myTest();
?>

</body>

</html>

Open in new window


and a php file
<?php

function myTest()
{
echo "<p>Hello world</p>";
}

?>

Open in new window


Both files are in the same folder on my webserver (which should support php)
When I view the page in my browser I don't see the result of the php function call.  Not do I see any error message
0
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
Give me a few minutes.  I was looking into the tutorial and this example from chris is rather different in the html side that I thought was required..
0
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
Now I'm getting somewhere I hope
<!doctype HTML public "-//W3C//DTD HTML 4.0 Frameset//EN">

<html>

<head>

<title>home</title>

</head>

<body>
This is some htm
<br><br>

<a href="testCode.php?method=myTest">Display different text</a>

<br><br>
<a href="testCode.php?method=add&num1=12&num2=7">Add</a>
<br><br>
<a href="testCode.php?method=subtract&num1=5&num2=3">Subtract</a>

</body>

</html>

Open in new window



and
<?php

switch ($_GET['method']):
    case 'myTest':
        echo myTest();
        break;

    case 'add':
        echo add($_GET['num1'], $_GET['num2']);
        break;

    case 'subtract':
        echo subtract($_GET['num1'], $_GET['num2']);
        break;

endswitch;

function add($num1, $num2)
{
    return $num1 + $num2;
}

function subtract($num1, $num2)
{
    return $num1 - $num2;
}


function myTest()
{
return "<p>Hello world</p>";
}

?>

Open in new window


and all three work.  Yippee

Just to be a real pain then I will close this question.
With my extra function called myTest can I get it to display the text on the current htm document rather than going to a new document.

such that
SNAG-0089.bmp
will change to
SNAG-0090.bmpwhen I click the display different text line
0
Chris StanyonWebDevCommented:
Cool. This is where an AJAX call would come in handy. Instead of directing the user to your script, you would make an Asynchronous call it and then handle the response. This is easiest done with the jQuery library. The AJAX call is handled with Javascript:

$(document).ready(function() {
    $('#clickMe').click(function(e) { // capture the click on the #clickMe element
        e.preventDefault(); // prevent the 'normal' click
        $.get( $(this).attr('href'), function( data ) { // make a get request to the href of the <a>
            $(this).html( data ); // data is whatever is echoed out from your script, so change the html to that.
        });    
    });
});

Open in new window

Give your <a> tag an ID so the jQuery knows what to respond to:
<a id="clickMe" href="testCode.php?method=myTest">Display different text</a>

Open in new window

Don't forget, you'll need the jQuery library loaded in the <head> of your html page:

<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
0
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
Now got a problem again.

<!doctype HTML public "-//W3C//DTD HTML 4.0 Frameset//EN">

<html>

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 

<title>home</title>

</head>

<body>

$(document).ready(function() {
    $('#clickMe').click(function(e) { // capture the click on the #clickMe element
        e.preventDefault(); // prevent the 'normal' click
        $.get( $(this).attr('href'), function( data ) { // make a get request to the href of the <a>
            $(this).html( data ); // data is whatever is echoed out from your script, so change the html to that.
        });    
    });
});

This is some htm
<br><br>

<a id="clickMe" href="testCode.php?method=myTest">Display different text</a>
<br><br>

</body>

</html>

Open in new window


I've put the document.ready section in numbers of different places but it always appears as text in the browser.  I've probably done something very basic wrong.
0
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
OK, now have this in the htm file:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> 

<script>
$(document).ready(function() {
    $('#clickMe').click(function(e) { // capture the click on the #clickMe element
        e.preventDefault(); // prevent the 'normal' click
        $.get( $(this).attr('href'), function( data ) { // make a get request to the href of the <a>
            $(this).html( data ); // data is whatever is echoed out from your script, so change the html to that.
        });    
    });
});
</script>

<title>home</title>

</head>

Open in new window


Now the document.ready does not appear but the text is not replaced when I click the 'link'
0
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
The link changes to red then back to blue when I click it.
0
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
Firefox browser.
0
Chris StanyonWebDevCommented:
OK. Need to slightly change the jQuery code. I was referring to $(this) inside the get function, and it was referencing the wrong element. We need to record the link as a variable and then change that. Because your script returns HTML, we need to replace the entire link with the new text rather than setting the html of it. The entire jQuery block should read:

<script type="text/javascript">
$(document).ready(function() {
    $('#clickMe').click(function(e) {
        e.preventDefault();
        var link = $(this);
        $.get(link.attr('href'), function(data) {
            link.replaceWith(data);
        });    
    });
});
</script>

Open in new window

0
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
Seems I can only accept one comment and no assists.  Thanks to everyone else.

Excellent, many thanks.
0
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
There was help from others so I did want to split.

ps.  This new UI for closing is terrible - I could not work out how to accept multiple comments as assists.  The previous interface was pretty clear to use I thought.
1
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
OK. I click on the comment best solution.  Move to another comment and I have only one button possible - 'best solution'.  If I click on that it removes my first selection.
I have clicked the link to switch between 'basic' and 'advanced' modes - still only possible to accept one comment.
0
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
I hope this does close it as I wish.


ps.  
Old UI - one click to select a comment as an assist.  New UI - two clicks to select a comment as an assist.  
Old UI - start closing immediately.  New UI - need to click before I can start closing.
Old UI - can select best and assist as I go along.  New UI - must select assist before I start closing otherwise I have to return to start.

In other words.  Probably at least twice the effort to close a question with the new UI when compared to the old UI.

@Julian. Any chance of you passing my closing comment onto the powers that be in EE ?   ( I would also have wanted to put part of my closing comment in bold font - which isn't an option to format a closing comment the way one can an ordinary comment.  sigh. )
0
Julian HansenCommented:
@Andy,

I have reported your posts with a request that it be bumped up the chain.
0
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
Thanks.  In general I am suspicious of the helpful or not. The asker wants assistance, psychologically saying not helpful might worry the asker because what if the expert takes offence and doesn't want to help any more.
0
AndyAinscowFreelance programmer / ConsultantAuthor Commented:
Might be better with a radio button selection and three options:
Was this helpful:   yes   undecided (default)   no
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.