1

I have an HTML slider called myRange that represents years. I want to get the value and print it in this field when I click a button:

<div id="test">HELLO</div>

I read the value in the script:

var slider = document.getElementById("myRange");

function post()
{
  var year = slider.value
  $.post('year.php', {slideryear:year}, 
  function(data){
    $("#test").html(data);
  });
}

And this is the year.php file:

<?php
    $year = $_POST['slideryear'];
?>

When I click the button to show the number in the id="test" paragraph, the paragraph goes blank ("HELLO" disappears). My first attempt with PHP, what am I doing wrong?

I'm running on Apache.

1 Answer 1

2

You only store the post value in the variable $year but you have to give the value back as the response if you want to get it in the callback or else HELLO will be replaced with an empty string.

Try for example:

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $year = $_POST['slideryear'];
    echo $year;
}

?>
Sign up to request clarification or add additional context in comments.

11 Comments

I think you meant ==, I tried but still nothing shows up, it keeps going blank.
Are you sure you have a value for slider? What do you see when you run var slider = document.getElementById("myRange"); console.log(slider.value); Do you see an error in the browser console?
Yes, the slider gives correct values. I print them in another <div> which I haven't included in the post. The console log also shows them when I click the button.
That seems like the response is the php code itself. Are you sure your php/apache setup is working correctly? I think that if that is working you should get the right result.
That was indeed the problem. I reviewed the installation and it wasn't working properly. Now the variable is read correctly. Thank you for the step-by-step instructions.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.