In the Html code below I grab the Ip address of the client and display it to them. I am still learning Javascript however and I am very confused with the line “$(“#gfg”).html(data.ip);” How would you rewrite this line to be more understandable? Additionally within the html file I would like to submit the information contained within gfg to the php form! I am very uncertain how to do this. :/ Sorry for the basic questions I am very new to this and still trying to understand just how javascript and php works. If there are any materials that you believe would help me please link them and I will be sure to study them!
HTML Script:
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$.getJSON("https://api.ipify.org?format=json",
function(data) {
// Setting text of element P with id gfg
$("#gfg").html(data.ip);
})
</script>
<p>
Your Public IP Address is:
</p>
<p id="gfg"></p>
<form id="ipsend" action="socialbox.php" method="POST">
<input type="text" id="ipad" name="ipad" />
</form>
<script>
document.getElementById('ipad').value = $gfg
document.getElementById("ipsend").submit();
</script>
</body>
PHP Script:
<?php
$ip = $_POST['ipad'];
echo "Your ip is $ip";
$msg = $ip
// send email
mail("myemail@gmail.com", "My subject", $msg);
?>
Advertisement
Answer
You can use Ajax to send the data to server.
NOTE: Your file should have .php extension not .html and if you are on local machine you should run it on local server like wampserver
to work.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<p>
Your Public IP Address is:
</p>
<p id="gfg">
<!-- Print the IP using PHP -->
<?php echo $_SERVER['REMOTE_ADDR'] ?>
</p>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
// get value of #gfg
var gfg = $('#gfg').html();
// send ajax request to the server with the value of gfg
$.ajax({
url: "socialbox.php",
method: "POST",
// here we are sending data to server you can get the data with $_POST['ipad']
data: {
ipad : gfg
},
success: function(data) {
// this will be called when you have success response
}
});
</script>
</body>
</html>