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

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>

Related

Do a javascript redirect after an ajax call

I'm trying to use ajax to parse data to be processed on a php page and have php echo a javascript redirect to another page but it is not working. I have read that js does not work after running an ajax call so I will like to know if there s a way around it. This is my code:
html
<form>
<div class="depart_time bottom_white w-40 ml-auto">
<p>Time</p>
<input type="time" name = "return_time" id = "rt">
</div>
<div class = "search_button r_search">
<button id = "r_search" onclick = "return false" onmousedown = "rent()">SEARCH</button>
</div>
</form>
ajax call is a normal xhttp request that gets sent to php for processing after which a redirection should occur:
if(isset($_POST['return_time'])){
echo '<script type="text/javascript">window.location.href="link.html"</script>';
}
Please an help is appreciated. I'm new to using ajax.
EDIT
the ajax code:
gid("r_search").addEventListener("mousedown", rent);
function rent(){
rt = gid('rt').value;
r_search = gid('r_search').value;
form_array = '&rt=' + rt +
'&r_search=' + r_search;
send_data = form_array;
ajax_data('app/rent.php', 'error', send_data);
//gid('error').innerHTML = send_data;
}
function ajax_data(php_file, getId, send_data){
gid(getId).innerHTML = "loading";
var xhttpReq = new XMLHttpRequest();
xhttpReq.open("POST", php_file, true);
xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttpReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
gid(getId).innerHTML = xhttpReq.responseText;
}
};
xhttpReq.send(send_data);
}
please note that 'gid' is for getelementbyid
You have to make bit alteration to your way of redirection.
First you need to make changes in your PHP response
if(isset($_POST['return_time'])){
...
// If you get your process success return 1
if(success) {
echo 1; die();
} else {
// else set some flag that you could get on your AJAX response
echo 0; die();
}
}
Now, get this flag on your AJAX and make changes to your below functions:
function ajax_data(php_file, getId, send_data){
gid(getId).innerHTML = "loading";
var xhttpReq = new XMLHttpRequest();
xhttpReq.open("POST", php_file, true);
xhttpReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttpReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if( xhttpReq.responseText == 1 ) window.location.href="URL where you wish to redirect page";
}
};
xhttpReq.send(send_data);
}
I've written this answer for others who come here for help.

JS functions self-executing in incognito mode?

I load a javascript at the end of my html page with a function loginsucces(),
which should be executed after a successfull login redirect to the page. It works perfectly in default browser mode(chrome), however when i load the page in incognito mode, it executes the function while the page is loaded the first time.
Due to this behavior i got syntax errors because the php variables are not initialized yet. I know i can get around that somehow but i am curios to know why is the js function is executed in incognito mode while first-time page load and how can i avoid this?
<script>
function loginsuccess(){
if(!<?php echo isAuth() ?>){ return; }
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var json = JSON.parse(xhr.responseText);
...
}
}
xhr.open("GET","http://myurl.com/api/users/"+<?php echo currentUserId()?>,true);
xhr.send();
}
</script>
You should perhaps do this instead.
<script>
<?php if (isAuth()): ?>
function loginsuccess(){
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var json = JSON.parse(xhr.responseText);
...
}
}
xhr.open("GET","http://myurl.com/api/users/"+<?php echo currentUserId()?>,true);
xhr.send();
}
<?php endif ?>
</script>
Alternatively to keep things separate and allow you to move the code out later on, instead of it being inline, is to define the state beforehand in a global var.
This could be put in the head of the document.
<?php if (isAuth()): ?>
<script>
var user = {
loggedIn: true,
userId: <?php echo currentUserId()?>
};
</script>
<?php endif ?>
Now you don't have PHP vars in your js which will allow you to move it out into a .js file if you wanted.
<script>
function loginsuccess() {
if (typeof user === "undefined" || user.loggedIn !== true) {
return
}
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && xhr.status == 200){
var json = JSON.parse(xhr.responseText);
...
}
}
xhr.open("GET","http://myurl.com/api/users/"+user.userId,true);
xhr.send();
}
</script>

Ajax To PHP converter get value from ajax

i need help, here my code :
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "getstok.php?secretkey=123&sku=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Masukkan kode barang / SKU:</b></p>
<form>
Kode Barang: <input type="text" onkeyup="showHint(this.value)">
</form>
<div id="txtHint"></span>
</body>
</html>
What I need is:
I want to hide this "secretkey=123" so visitor cannot see my secret key
when call "xmlhttp.send();" return the value and I want to convert it to php like example
$getxmlhttp = xmlhttp.send();
when I type something it will be call function, but when I press enter that refresh, how to disable the enter or what the best suggestion for me.
this is my site sample:
http://stok.tk
for example type "YI 067"
1 : You can't. The browser (and so the visitor) can always know wich page is called with wich URL and parameters
2 : You can't do it like that. You need to get the value of your request into getstok.php with the super global variables $_GET['your var']
3 : It's reloading the page because it's sending your form. By default it send it to the same page. Just remove your <form>

why php results in HTML are undefined when using 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.

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

Categories