Click here to Skip to main content
15,897,891 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have been trying to access the JavaScript variable value outside the script, into the PHP variable so that I can process it and store it into database.
This is JavaScript function:

JavaScript
<script type = "text/javascript">
function Connect() {

	var host="localhost";
	var port=1883;
	document.getElementById("messages").innerHTML ="Connected to "+host +"on port "+port;
	
	  }
</scipt>

I am not getting how to postback or send an AJAX request, or send information back to the PHP for processing so that I can assign this value to a PHP variable.

What I have tried:

I tried to assign value inside JavaScript to another variable like this:

JavaScript
<script type = "text/javascript">
function Connect() {

	var host="localhost";
	var port=1883;
	document.getElementById("messages").innerHTML ="Connected to "+host +"on port "+port;
	var msg1 = "Connected to "+host +"on port "+port;
	  }
</scipt>

It works in usual way - Messages:<p id="messages"></p> But I want to get this into a variable. Something like <?php $msgs = "<script>document.write(msg1)</script>"; echo $msgs;

But it won't work.
Posted
Updated 4-May-23 4:34am
v2

How Str_replace document.write(obj with PHP?
 
Share this answer
 
Comments
Richard Deeming 4-May-23 11:09am    
Your question is not a "solution" to someone else's question.

If you want to ask a question, then ASK A QUESTION[^]. But you're going to have to provide a lot more information than you have here if you want anyone to be able to help you.
Try the following code:
<html>
<body>
<script type="text/javascript">
     var jsVal = "I love PHP!";
</script>

<?php
$txt = "PHP";
echo "Result: "."<script>document.writeln(jsVal);</script>";
?>

</body>
</html>

Result: I love PHP!
 
Share this answer
 
Comments
Member 12010285 1-Feb-22 20:08pm    
It won't work! If it is outside the function it works. It is outside the function so it doesn't work. I tried it.
M Imran Ansari 2-Feb-22 4:31am    
Add a hidden field, store the msg1 value into hidden field on post you page and then get the value from your hidden field.
input type="hidden" id="message1"
document.getElementById("message1").value = msg1;
echo $_POST['message1'];
Member 12010285 2-Feb-22 13:24pm    
It says Undefined index: message1. I did like this: var msg1 = "Connected to "+host +"on port "+port; document.getElementById("message1").value = msg1; `
and in html - input type="hidden" id="message1" name="message1"
echo $_POST['message1'];

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900