why php results in HTML are undefined when using JavaScript - javascript

I need to get the IP of the client. I am able to get it through PHP variable
"$_SERVER['REMOTE_ADDR']". I get this ip from server side php to html page through AJAX request but when I want to use this IP value in JavaScript it is showing that the value is undefined.
any solution?
PHP code:
<?php echo $_SERVER['REMOTE_ADDR'];?>
HTML CODE:
<body onload='ip(); ip2();'>
<kbd id='ip' ></kbd>
JavaScript code:
function ip() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ip").innerHTML =
this.responseText;
}
};
xhttp.open("POST", "ip.php");
xhttp.send();
}
function ip2() {
setTimeout(function () {
var ip = document.getElementById("ip").value;
alert(ip);
}, 1000);
}

First of all you should validate that you are getting the right response from your AJAX request by check that the result is certainly written to the element with id attribute "ip", and than instead of using:
var ip = document.getElementById('ip').value;
You should use Node.textContent to get the text content:
var ip = document.getElementById('ip').textContent;
Code example (without AJAX request):
function ip() {
document.getElementById('ip').innerHTML = '127.0.0.1';
}
function ip2() {
setTimeout(function () {
var ip = document.getElementById('ip').textContent;
console.log(ip);
}, 1000);
}
<body onload="ip(); ip2();">
<kbd id="ip" ></kbd>

You want your Ip Address in java script , so have to put ip address in that tag i think.
<?php $ip_address = $_SERVER['REMOTE_ADDR'];?>
<body onload='ip(); ip2();'>
<kbd id='ip' ><?php echo $ip_address; ?></kbd>

<?php echo $_SERVER['REMOTE_ADDR'];?>
<html>
<head>
</head>
<body onload='ip();'>
<div id='ip' ></div>
</body>
</html>
<script>
function ip() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ip").innerHTML =
this.responseText;
ip2(this.responseText);
}
};
xhttp.open("POST", "try.php");
xhttp.send();
}
function ip2(stringvalue) {
setTimeout(
function() {
var ip = document.getElementById("ip").value;
alert(stringvalue);
},2000);
}
</script>
run this code you might found what is the problem.

Related

inject jsp with js result into html>body>div

My question is: Could insert a jsp response (html) in html?
I think using XmlHttpRequest.
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.jsp", true);
xhttp.send();
My question is: But if I have javascript in my jsp that it executes after page loading, is it executed like when I call jsp directly by browser url?
Thanks in advance
For example:
This is index.html
<html>
<head>
<script type="text/javascript" src="app.js"></script>
</head>
<body onload="loadInfo();">
<div id="container"></div>
</body>
This is app.js:
function loadInfo(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("container").innerHTML =this.responseText;
}
};
xhttp.open("GET", "info.html", true);
xhttp.send();
}
This is info.html (i have jsp but i think it is the same..):
<html>
<head>
<script type="text/javascript" src="info.js"></script>
</head>
<body>
<div id="body_info">This is info..</div>
<script type="text/javascript" >
console.log("wait for info..");
info();
</script>
</body>
This is info.js:
function info(){
document.getElementById("body_info").innerHTML ="info.js is executed";
}
If i call info.html, typing url in browser(example http://localhost:8000/info.html), the script is executed and i get
"info.js is executed",instead if i call index.html, maybe the xhr request not return the same but I see "This is info".
how can i resolve and accomplish this problem using xhr?
Thanks
Roberto
When you make ajax called to some page so what ever will there under <body></body> will return as response so in your code this.responseText will be having <script></script> code in it also. You can check if you are using chrome then click on element tab you will see <script></script> also which is return as response .Now,to execute this you can do like below :
function loadInfo() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("container").innerHTML = this.responseText;
//getting the script which is return as response back
var datas = document.getElementById("container").getElementsByTagName("script");
//looping unders <script></script>
for (var i = 0; i < datas.length; i++) {
console.log("inside script executing")
eval(datas[i].innerText); //executing script
}
}
};
xhttp.open("GET", "n.html", true);
xhttp.send();
}
And your script for info.html look like below :
<script>
console.log("wait for info..");
info();
function info() {
document.getElementById("body_info").innerHTML = "info.js is executed";
}
</script>

Serverside send information to vanilla HTML

Is it possible to send information from the serverside to the client side like you would with Pug or EJS but without a view engine?
Right now I am using XHTTP requests to access data but it would be a lot easier to not have to use it so much.
function getAllBears(id){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("allBear").innerHTML = this.responseText;
}
};
xhttp.open("GET", "allBears", true);
xhttp.send();
}
You can insert a script tag in HTML and stringify the variable you have on server side, then read the serialized global variable on window.
response.body = ('
<html>
<head>
...
</head>
<body>
<p>text...</p>
<script>
window.bar = ###
</script>
</body>
</html>
'.replace(###, JSON.stringify(bar))
Be careful that some patterns/chars should be replaced in the result of JSON.stringify, a much safer method is as follows:
function toJSONSafely (obj: any) {
return JSON.stringify(obj)
.replace(/\u2028/g, '\\u2028')
.replace(/\u2029/g, '\\u2029')
.replace(/<\/script>/g, '<\\/script>')
}
User your javascript inside the html code i.e inline javascript
as shown below
<html>
<head>
</head>
<body>
<p>use this code </p>
<script>
function getAllBears(id){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("allBear").innerHTML = this.responseText;
}
};
xhttp.open("GET", "allBears", true);
xhttp.send();
}
</script>
</body>
</html>

AJAX logic not working

I am new to AJAX and learning it. I am searching a food item in my HTML textbox and trying to communicate with the server to know if the item is available. The respective status of the item should be shown in the div tag below the textbox but it is not showing.
I haven't studied jQuery yet and would like to know the below things:
How to get the response from the server in plaintext using AJAX and JavaScript, and display it in the div tag below the textbox (advise the changes to be made in the code).
What change should I make in JavaScript code to send the AJAX request in POST method (I know about the changes in PHP code)?
//index.html
<head>
<script type="text/javascript" src="food.js">
</script>
</head>
<body>
<h3>The Cheff's Place</h3>
Enter the food you want to order
<input type="text" id="userInput" name="input" onkeypress="sendInfo()"></input>
<div id="underInput"></div>
</body>
</html>
//food.js
var request;
function sendInfo() {
var v = document.getElementById("userInput").value;
var url = "index.php?food=" + v;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
if (request.readyState == 0 || request.readyState == 4) {
try {
request.onreadystatechange = getInfo;
request.open("GET", url, true);
request.send(null);
} catch (e) {
alert("Unable to connect to server");
}
}
}
function getInfo() {
if (request.readyState == 4) {
if (request.status == 200) {
var val = request.responseText;
document.getElementById('underInput').innerHTML = val;
}
}
}
//index.php
<?php
header('Content-Type: text/plain');
$food = $_GET['food'];
$foodArray = array("paneer", "butter", "chicken", "tandoori", "dal");
if (in_array($food, $foodArray))
{
echo "We do have " .$food;
}
elseif($food == "")
{
echo "Kindly enter some food";
}
else
{
echo "We do not sell " .$food;
}
?>
I ran your code. It's working fine. Just replace onkeypress with onkeyup.
<input type="text" id="userInput" name="input" onkeyup="sendInfo()"></input>
Using JQuery (Assuming you have included jquery file or cdn) :
Include the following snippet in script tag at the end of the body.
$("#userInput").keyup(function(){
$.get("index.php", { food: $("#userInput").val() })
.done(function(data) {
$("#underInput").html(data)
})
});

How to show php file output on Page where from it is called?

I have webpage on which i run a php file by javascript as given below
<script type="text/javascript">
var bhs = document.createElement('script');
var bhs_id = "yvw3lwc1tnvqfh4k4k4hisossew";
bhs.src = "//example.com/insert.php?site=" + bhs_id + "";
document.head.appendChild(bhs);
document.write("<span id='calc'></span>");
</script>
This JavaScript successfully insert data into insert.php file and then send to database. Besides i want to show one variable value generated in insert.php file in span id calc on a webpage where from above JavaScript is executed. How to do this? Thanks in advance.
It´s better use AJAX:
function loadDoc() {
var xhttp = new XMLHttpRequest();
var bhs_id = "yvw3lwc1tnvqfh4k4k4hisossew";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert('OK!');
}
};
xhttp.open("GET", "//example.com/insert.php?site=" + bhs_id, true);
xhttp.send();
}
Reference:
http://www.w3schools.com/xml/ajax_intro.asp

How to check if a session is empty using javascript inside php

Also, how do i unset the session through javascript?
I have made this code with PHP:
if(isset($_SESSION) && !empty($_SESSION)) {
unset($_SESSION['Plan1']);
unset($_SESSION['excel_array']);
$_POST['excel_name']['Main'] = "Main".date("y_m_d_Hi");
$_POST['excel_array']['Main']['Plan1'] = array();
}
else{
$_SESSION['excel_name']['Main'] = "Main".date("y_m_d_Hi");
$_SESSION['excel_array']['Main']['Plan1'] = array();
}
So here i check if there is a session. If there is, i unset it and send the $_POST data instead. however, if there isn't one, i create it.
The problem is, i might want to call this on a button click. How would i make a code with the same functionality, but using a javascript function?
Put your php in a file on its own, called set_session.php for example:
<?php
session_start();
unset($_SESSION['Plan1']);
echo 'unset';
?>
Call it in javascript:
<script>
function unset() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhttp.open("GET", "set_session.php", true);
xhttp.send();
}
</script>
<button type="button" onclick="unset()">Unset</button>
<div id="result"></div>

Categories