settimeout not getting called? - javascript

I have a javascript which call a server and get a JSON data which contains some config to enable/disable redirecting to another link. I need to delay the redirection by a few seconds, but it seems that setTimeout() is not getting called in my method. Even if I change redirect() as an anonymous function and pass it in setTimeout it is still not getting called.
<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
xhr.onreadystatechange = function() {
function redirect(){
alert("in redirect");
window.top.location=migrationConfig.REDIRECT_LINK;
}
if (xhr.readyState == 4 && xhr.status==200) {
var data = xhr.responseText;
migrationConfig = JSON.parse(data);
if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
document.body.innerHTML = '';
document.write("<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>");
document.write("<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>");
setTimeout(redirect,3000);
}
}
}
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);

// set global object for using it inside the settimeout function
var redirect;
and then inside the xhr.onreadystatechange = function() {
redirect = function(){
alert("in redirect");
window.top.location=migrationConfig.REDIRECT_LINK;
}
setTimeout('redirect()',3000);

Thanks for all the suggestions. I have improved it as per suggestion by talsibony, and I further found out also that document.write() removes all my content, which makes it unable to find the redirect global variable. So I have instead changed it to add a div element and set the innerHTML. Here is the fixed code in case if someone encountered similar issue.
<script>
var xhr = new XMLHttpRequest();
var migrationConfig;
var redirect;
xhr.onreadystatechange = function() {
redirect = function(){
window.top.location=migrationConfig.REDIRECT_LINK;
}
if (xhr.readyState == 4 && xhr.status==200) {
var data = xhr.responseText;
migrationConfig = JSON.parse(data);
if(migrationConfig.SHOW_REDIRECT_MESSAGE == 'Y'){
if (window.confirm(migrationConfig.REDIRECT_MESSAGE)){
document.body.innerHTML = '';
var div = document.createElement("div");
document.body.insertBefore(div, document.body.firstChild);
div.innerHTML += "<h1><font color='red'>You will now be redirected to the new URL at:</font></h1>";
div.innerHTML += "<h1><font color='red'>"+ migrationConfig.REDIRECT_LINK +"</font></h1>";
div.innerHTML += "<h1><font color='red'>Remember to save the new URL to your favorites</font></h1>";
setTimeout(redirect,3000);
}
}
}
}
xhr.open('GET', '/MyApp/migration-config?APP_NAME=MyApp', true);
xhr.send(null);

Related

Send PHP Variable with Ajax Call

I wrote a PHP application that makes an AJAX call (XMLHttpRequest) and is called every 5 seconds. The page called makes a database query. However, I need a variable from the main page and am unable to find a solution to attach it to the Ajax call.
Using $_GET seems a bit too insecure to me. Is there another way here?
This is my first expierence with ajax so please dont be to hard with me :)
Here is my Ajax Call
const interval = setInterval(function() {
loadText() }, 5000);
function loadText(){
//XHR Objekt
var xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.'&name='.$_SESSION['name'].'&org='.$_SESSION['org'];?>', true);
xhr.onload = function() {
if(this.status == 200){
document.getElementById('table_view_div').innerHTML = this.responseText; }
})
if(this.status == 404){
document.getElementById('apps').innerHTML = 'ERROR';
}
}
xhr.send();
// console.log(xhr);
}
Ill hope i provided enough Information
WIsh u all a great weekend
You do not need sending session variables at all: those are already known to the called page, because it can share the session information of the calling page.
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?= $role ?>'
is enough, provided that "table_view.php" issues a session_start() command.
I have fixed your code; It's here:
(Note: \' means that the character ' doesn't closing the string.)
const myInterval = setInterval(function(){loadText();}, 5000);
function loadText(){
//XHR Objekt
var xhr = new XMLHttpRequest();
// OPEN
xhr.open('GET', 'ajax/table_view.php?role=<?php echo $role.\'&name=\'.$_SESSION[\'name\'].\'&org=\'.$_SESSION[\'org\']; ?>', true);
xhr.onload = function(){
if(this.status == 200){
document.getElementById('table_view_div').innerHTML = this.responseText;
}
if(this.status == 404){
document.getElementById('apps').innerHTML = 'ERROR';
}
}
xhr.send();
}

What is wrong with my Ajax Javascript when submitting or displaying a form?

The code below SHOULD be opening an 'add' form and allowing Ajax to send the response back to the server. I'm a bit of a newb when it comes to this and I can't find what's wrong with it. In the Developers Console, it says the problem is with the xhr.send(); line. Can you tell me what I need to change to get this to work?
function DisplayForm() {
var div = document.getElementById("formDiv");
div.classList.toggle("show");
div.innerHTML = '<img class="loadingImg" src="images/loading.gif" alt="Loading..." height="60" width="60" border="0">';
var xhr = new XMLHttpRequest();
xhr.open('GET', "add.php", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var data = xhr.responseText;
DisplayAfterLoad(data);
var button = document.getElementById("saveForm");
button.addEventListener("click", function(event) {
event.preventDefault();
recordAdd();
});
}
}
}
xhr.send();
}
It shows the "loading.gif" but does nothing else.

How do I get around refreshing my videos?

I am making a messaging system and I recently added file uploads, and I refresh the messages every 1.5 seconds Here is my function :
function load_messages(){
var id = document.getElementById('group_id').value;
var fullurl = "loadmessages.php?id=" + id;
var request = new XMLHttpRequest();
request.open("GET",fullurl,false);
request.onload = function(){
if(request.status == 200){
document.getElementById("groupchat").innerHTML = this.responseText;
}
}
request.send();
};
setInterval(load_messages, 1500);
I think the problem is that it keeps refreshing it there for I can't view it. How do I get around that?

Javascript function running after return false

In my code, when a select box is changed, a js function (ConfirmDelete) is called which asks the user if they are sure they want to change the select box. If the user selects no, it will return false and would normally stop the execution.
My problem is that I also have another AJAX/JS function defined after this that is waiting for the select box to be changed and if it is, it sends details to a php script which adds a record into a mysql database.
I'd like to know if there is anyway that I can stop the AJAX/JS code from running after a user has selected No.
The JS function
function ConfirmDelete()
{
var x = confirm("Are you sure?");
if (x)
return true;
else
return false;
}
The AJAX/JS function
$( ".dropdown" ).change(function() {
var request = new XMLHttpRequest();
var id = this.value;
var content = this.name;
request.open("POST", "samefile.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
}
}
request.send("id="+id+"&content="+content);
window.location.reload();
window.location.reload();
}
);
The HTML Select box
<select class="dropdown" name="09:00-1-0-16-05-26" Onchange="return ConfirmDelete();">
<option class="co0es0sp1fd1oo0fs0" value="47">mike berry</option>
<option value="cancel-47">Cancel</option></select>
The order of the html is
JS Function defined in header
HTML code
AJAX/JS Script tag after
The AJAX/JS function
$( ".dropdown" ).change(function() {
if(!ConfirmDelete()) return; // right here, use this to confirm
var request = new XMLHttpRequest();
var id = this.value;
var content = this.name;
request.open("POST", "samefile.php", true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if(request.readyState == 4 && request.status == 200) {
var return_data = request.responseText;
alert (return_data);
}
}
request.send("id="+id+"&content="+content);
window.location.reload();
window.location.reload();
}
);
Adding onchange event directly in HTML does not solve the problem.
Use this instead;

how to click submit on achor tag without it refreshing the data on page php, sql and javascript

when ever I click send on the anchor tag the whole data on the page coming from the database refreshes. How do I prevent this. I have tried several options online but none works.
my JavaScript code is below. In some way I'm trying to get it like a facebook activity feed where the reatime info is being pushed out and the content that is already there does not disappear and appear on refresh.
<script>
function submitChat() {
if (form1.msg.value == '') {
alert('enter your message');
return;
}
$('#imageload').show();
var msg = form1.msg.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
$('#imageload').hide();
}
}
xmlhttp.open('GET', 'insert.php?&msg=' + msg, false);
xmlhttp.send();
return false;
}
$(document).ready(function(e) {
$.ajaxSetup({
cache: false
});
setInterval(function() {
$('#chatlogs').load('reg.php')
}, 2000);
});
</script>
here is the anchor tag being echod by php
<a href=\"#\"onclick=\"submitChat()\" \"onsubmit=return false\" >send</a>
send
Change
document.getElementById('chatlogs').innerHTML = xmlhttp.responseText;
to
currentData = document.getElementById('chatlogs').innerHTML;
document.getElementById('chatlogs').innerHTML = currentData + xmlhttp.responseText;

Categories