Echoing JavaScript value in PHP

I read that if you add a hidden input to a form, like this…

    <input type="hidden" id="url" />
    <input type="submit" value="Submit Quiz" />    
  </form>

then add one of the following scripts (for JavaScript or jQuery)…

<script>
document.getElementById("url").value = document.URL;

$(document).ready(function() {
    $("input#url").attr("value", $(location).attr('href'));
});
</script>

then when you click the Submit button and it takes you to the results page, it will capture the URL of the first page. But I don’t understand how to convert the result to PHP.

For example, if want to insert the PHP echo statement “echo $PreviousPageURL” on the next page, how do translate document.URL to $PreviousPageURL?

[quote]EDIT
This post has been reformatted by enclosing the code block in 3 backticks
```
on their own lines.[/quote]

You will need to give the url input a name attribute too, so that the value then gets submitted with the rest of the form.

Like this?

<input type="hidden" name="PreviousURL" id="url" />

How do the manipulate that so I can echo $PreviousURL on the next page?

Depending on the method you give the form, you use either the global $_POST or $_GET variables. So:

With <form method="POST">, you would use echo $_POST['PreviousURL'];
With <form method="GET">, you would use echo $_GET['PreviousURL'];

On the next page, it will be available as either a POST or GET variable, depending on the method that you use to submit the form.

For example, using filter_input and a filter to ensure that only url values arrive:

$url = filter_input(INPUT_POST, "PreviousURL", FILTER_SANITIZE_URL);

What you do with $url from there is up to you.

2 Likes

I’m led to understand that $_POST and $_GET have too many security issues these days, which is why filter_input is preferred.

What are your thoughts on this?

To be honest I’m so used to relying on WordPress that I often overlook security! filter_input is definitely the way to go.

OK, got it.

@ Oz - Are you saying that WordPress isn’t secure? :wink:

I was getting ready to upgrade to WordPress or Drupal, but I got cold feet. I think it would take me another lifetime to translate all my websites and customized scripts into another language. Also, I think advancing technology may make it a little easier to do some of the things the big boys do.

I may still replace my Google blogs with a simple WordPress blog, though.

Thanks for the tips.

Haha nah I meant that WordPress automatically handles sanitization and a few other stuff for you. It’s not a bad way to go

Anyways, good luck!

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.