-3

My question: I need a JavaScript variable to pass to a PHP variable. I have done this, but the passed PHP variable does not support input text field value="" attribute. How can I fix this problem?

<input type="number" onchange="myFunction()" >
<script>
function myFunction() {
  var x = 4;
  document.getElementById("demo").innerHTML = x;
}
</script>

Working $p:

<?php 
    $p ='<p id="demo"></p>';
    echo $p;   
?>

But, $p variable does not work within value=''

<input type='text' name='p3' value='<?= $p ?>'>
disinfor
  • 10,865
  • 2
  • 33
  • 44
  • Welcome to Stack Overflow! We're missing some information from your question. You have a JS script that sets the `innerHTML` for a PHP rendered element with the `id` of "demo". But then you show us an `input`, but nothing else. Where is `$p` being set for the `input` element? – disinfor Jul 28 '22 at 21:28
  • i updated my question . check now – Ahinsa Disanayake Jul 28 '22 at 21:35
  • That input isn't the same as what you provided. Do you have a PHP function somewhere? As of right now, you are only using an input to run a JS function. You could put a PHP rendered value into the `script`, but if you need to get a dynamic value from PHP using JS, you'll need to use AJAX. – disinfor Jul 28 '22 at 21:37
  • can you give me ajax reference for solve my problem – Ahinsa Disanayake Jul 28 '22 at 21:39
  • i need to javascript variable pass to php variable and after that php variable add to text field like as value=" " – Ahinsa Disanayake Jul 28 '22 at 21:50
  • Why do you need to pass a Javascript variable to PHP? This now seems like an [XY Problem](https://xyproblem.info/) – disinfor Jul 28 '22 at 21:56
  • that is short part of my code – Ahinsa Disanayake Jul 28 '22 at 22:00
  • We need more code to know what you want, please [take the tour](http://stackoverflow.com/tour), and read [how to ask](https://stackoverflow.com/help/how-to-ask), an [On Topic question](https://stackoverflow.com/help/on-topic), then look at the [Question Check list](https://meta.stackoverflow.com/questions/260648/stack-overflow-question-checklist), the [perfect question](http://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) and how to create a [Minimal, Complete and Verifiable Example](http://stackoverflow.com/help/mcve) – disinfor Jul 28 '22 at 22:13
  • JavaScript can not update PHP. That requires you to send an http request back to the server for PHP to interact with a value. You need to learn about the page lifecycle to understand how PHP interacts with JavaScript. – epascarello Jul 29 '22 at 13:28

1 Answers1

0

PHP is a server language so it means that it loads the values before the page is rendered. Javascript renders and handles everything after the page is loaded by PHP.

For this you need to create an alternate php file that receives that value and the give it back to your input.

Alejandro Giraldo
  • 609
  • 1
  • 6
  • 11