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>
Related
I have this variable in js :
var video_embed = '<script src="https://stream.laminor.academy/1qwyvs9ystd9/embed"><\/script>';
$('.my_video').after("<div class='col-xs-12' id='video_content'>"
+ video_embed +
"</div>");
but my rendered HTML code is :
<div class="col-xs-12" id="video_content">
<script src="https://stream.laminor.academy/1qwyvs9ystd9/embed"></script>
</div>
embed code not working!
Thanks for help
when you generate script tags after the document is loaded, it won't run.
You need to download the script and execute it :
//Code that will download the script
function loadScript() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Making sure there's no error
if (this.readyState == 4 && this.status == 200) {
// Executing the script
eval(this.responseText)
} else if (this.readyState == 4) {
// If the server responded with something else than a 200 OK
console.warn(this.status)
}
};
xhttp.open("GET", "https://stream.laminor.academy/1qwyvs9ystd9/embed", true);
xhttp.send();
}
// Executing the function
loadScript()
Let me know if it isn't working.
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.
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>
Here is my javascript:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
hanapin.send(reqdata);
hanapin.onreadystatechange = function() {
if (hanapin.readyState == 4 && hanapin.Status == 200) {
document.getElementById('province').innerHTML=hanapin.ResponseText
}
}
window.alert(targeturl);
window.alert(reqdata);
}
I know the function is receiving the data because I used the alert.
but on php:
<?php
$findwat = $_POST['condo'];
echo $findwat;
?>
even when I open the php file using a separate link it won't echo the variable
An example using jQuery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
function fetchprov(proptype) {
$.post("testajax.php", {condo:proptype}, function(data){
// data is the result received from php
alert(data);
});
}
A mandatory header field for http post request is Content-length. change your code to:
function fetchprov(proptype) {
var reqdata = "condo="+proptype;
hanapin=new XMLHttpRequest();
hanapin.open('POST', 'testajax.php', true);
hanapin.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hanapin.setRequestHeader("Content-length", reqdata.length);
hanapin.setRequestHeader("Connection", "close");
hanapin.send(reqdata);
hanapin.onreadystatechange=function() {if (hanapin.readyState == 4 && hanapin.Status == 200) {document.getElementById('province').innerHTML=hanapin.ResponseText} }
window.alert(targeturl);
window.alert(reqdata);
}
also a better solution is to use jquery to handle ajax
<?php
if(isset($_GET['dt']))
{
echo 'a';
die();
}
?>
<div onclick="call('data_call.php?dt=a')">DATA</div>
<script>
function call(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function (e) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
alert(xhr.responseText);
} else {
alert("");
}
}
};
xhr.onerror = function (e) {
alert("");
};
xhr.send(null);
}
</script>
If I run the above code in chrome (the latest version) and click the div it alerts a
If, without refreshing my window I edit the php file and change the echo 'a' to echo 'b' then save it and click the div, it alerts b.
The above is the expected behaivor. In the lastest version of internet explorer, for some reason it always alerts a.
Why please?
To prevent caching issues (typically response headers should mitigate this to a certain degree), you're better off busting the cache yourself:
function getUniqueURL(url)
{
return url + (url.indexOf('?') == -1 ? '?' : '&') + '_=' + new Date().getTime();
}
xhr.open("GET", getUniqueURL(url), true);