My JavaScript/ajax code works the first time, but not there after. The GetAttribute element is null when the function is called again. I have try using createElement and AppendChild, but it does the same thing. If I didn't need the getAttribute it would work fine, but I cannot get the function to work with the getAttribute method. Any help would be appreciated.
function ajaxFunction(Picked) {
var getdate = new Date();
if(xmlhttp) {
var Pic1 = document.getElementById("Pic1").getAttribute("name");
var Pic2 = document.getElementById("Pic2").getAttribute("name");
if (Picked === Pic1 ){
var Chosen = Pic1;
var NotChosen = Pic2;
}
else {
var Chosen = Pic2;
var NotChosen = Pic1;
}
xmlhttp.open("POST","choice.php",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("Chosen=" + Chosen + "&NotChosen=" + NotChosen );
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
var response = xmlhttp.responseText;
response = response.split("|");
document.getElementById('Pic1').innerHTML = response[0];//New Pic
document.getElementById('Pic2').innerHTML = response[1];
}
else {
alert("Error. Please try again");
}
}
}
Change your if to
if (Picked === Pic1)
By writing if (Picked = Pic1 ), you're assigning Picked to Pic1.
Related
I am creating timers for workers. A user can add worker with some time. After that it will create a countdown timer for that worker. Start time and target time is saved on database so i am starting timer according to that. And the timer is worked fine. Now i want that if i click on any of the created child it should i want to call my php with POST id of the Work which is added on child creation and then open detailed information of the work which was filled when worker was added. So basically i want help in post WorkID of the selected child on click and call my php script.
On Page load i am getting data like this
function GetMachineSinger() {
var http = new XMLHttpRequest();
var url = 'php/StitchTimerSinger.php';
http.open('GET', url, true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
var data = this.responseText;
var jsonResponse = JSON.parse(data);
for(var i=0;i<jsonResponse.length;i++){
var index = jsonResponse[i];
var empname = index["EmployeeName"];
var hour = index["Hour"];
var minute = index["Min"];
var second = index["Sec"];
var available = index["Available"];
var id = index["WorkID"];
if(available<50){
addEmployee(id,empname,hour,minute,second);
}
document.getElementById("avlmc").innerHTML = available;
}
}
}
http.send();
}
addEmployee()
function addEmployee(id,emp,hr,mi,sec)
{
var employee = new Employee(id,emp,hr,mi,sec);
display.appendChild(employee.domObj);
employee.startTimer();
}
class Employee
{
constructor(id,name,hr,min,sec)
{
var self=this;
this.timer;
this.timeInSec;
this.domObj=document.createElement("div");
this.timeSpan=document.createElement("span");
this.domObj.style.backgroundColor = '#4CA';
this.domObj.style.border = 'none';
this.domObj.style.height = '100px';
this.domObj.style.width = '100px';
this.domObj.style.color = 'white';
this.domObj.style.padding = '20px';
this.domObj.style.textAlign = 'center';
this.domObj.style.textDecoration = 'none';
this.domObj.style.display = 'inline-block';
this.domObj.style.fontSize = '26px';
this.domObj.style.borderRadius = '50%';
this.domObj.style.margin = '20px';
this.domObj.style.justifyContent = "center";
this.timeInSec=hr*60*60+min*60+parseInt(sec);
this.timeSpan.innerHTML=hr+":"+min+":"+sec;
this.domObj.innerHTML=name+"<br>";
this.domObj.appendChild(this.timeSpan);
// console.log("0:"+this.timeInSec);
}
startTimer()
{
this.timer=setInterval(this.updateTime.bind(this),1000);
}
updateTime()
{
var hr,min,sec,temp;
if (this.timeInSec<=0)
{
clearInterval(this.timer);
}
else
{
this.timeInSec--;
//console.log("1:"+this.timeInSec);
sec=this.timeInSec % 60;
temp=this.timeInSec-sec;
temp/=60;
//console.log("2:"+temp);
min=temp % 60;
temp-=min;
hr=temp/60;
this.timeSpan.innerHTML=hr+":"+min+":"+sec;
if (min<10 && hr<1){
this.domObj.style.backgroundColor = '#ef5350';
}
}
}
}
Try
this.domObj.addEventListener('click', function (event) {
// do something
//for opening new window
let w = window.open('about:blank','name','height=200,width=150');
// w.document.open()
w.document.write('any HTML');
w.document.close();
});
G'morning folks,
I just have a small problem to fix this issue:
I have a page which should GET some data from a url when opening and the display in the own content. But the GET url contains Parameters from my url.
So:
1. Get Parameters from my URL like www.mydomain.com?test=1&test1=bla
2. open GET with this parameters (1 and bla) and display result
Here my current version:
<body>
<h3>Visa Informationen</h3>
<p id="data"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("data").innerHTML = myObj.response.visa.content;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
<script>
function getURLParameter(name) {
var value = decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, ""])[1]);
return (value !== 'null') ? value : false;
}
var param = getURLParameter('test');
if (param) document.getElementById("testnr").innerHTML = param;
var param1 = getURLParameter('test1');
if (param1) document.getElementById("testnr1").innerHTML = param1;
var url = "https://api01.otherdomain.com?test=" + param + "&test1" + param1 + "&trv=0&vis=1"
</script>
</body>
Any hint where the problem is with this code?
Kind regards,
Chris
It seems like you having issue with script execution order.
I assume that testnr element coming from your XML ajax request.
You have two script block in your HTML and it will executed while page load.
When second script block is running your fist XMLHttpRequest not completed so it not able to find given HTML tag document.getElementById("testnr").innerHTML
To overcome this issue you need to execute script only after XMLHttpRequest request is completed.
In your case :
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("data").innerHTML = myObj.response.visa.content;
// Execute new created function here
SetValues();
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function getURLParameter(name) {
var value = decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, ""])[1]);
return (value !== 'null') ? value : false;
}
function SetValues()
{
var param = getURLParameter('test');
if (param) document.getElementById("testnr").innerHTML = param;
var param1 = getURLParameter('test1');
if (param1) document.getElementById("testnr1").innerHTML = param1;
var url = "https://api01.otherdomain.com?test=" + param + "&test1" + param1 + "&trv=0&vis=1"
}
</script>
Okay, i fixed the matter.
Here my result which works fine for me:
<script>
function getURLParameter(name) {
var value = decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, ""])[1]);
return (value !== 'null') ? value : false;
}
var param = getURLParameter('test');
var param1 = getURLParameter('test1');
var url = "https://api01.otherdomain.com?test=" + param + "&test1" + param1 + "&trv=0&vis=1"
</script>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("additionalContent").innerHTML = myObj.response.additionalContent;
document.getElementById("data").innerHTML = myObj.response.visa.content;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
i'm a complete newbie when it comes to Js, trying to make some very simple script that takes a string of binary numbers from a txt document on my server using ajax, to then put it in a string var and change the first 0 it finds in a 1, using an if construct inside a loop.
Problem is, when the page tries to execute the if line, it simply freezes. Taking the same if construct out of the loop, the script is executed no problem, so i'm guessing it has something to do with either that or/and some fundamental misunderstanding of how Js scripts works in the first place.
Here is the script:
function loadPos()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
document.getElementById("demo").innerHTML = this.responseText;
};
xhttp.open("GET", "posizioni.txt", true);
xhttp.send();
}
function takeFirst()
{
var i=0;
var check=false;
var oldPos=[];
loadPos();
oldPos = document.getElementById("demo").innerHTML;
for(i=0;!check||i<10;i++)
{
if(oldPos[i]=="0")
{
oldPos[i]="1";
check=true;
}
}
document.getElementById("demo").innerHTML=oldPos;
}
I don't see any use of loop in it if you can achieve the same without it. Please update your function to the following:
function takeFirst()
{
loadPos();
var oldPos = document.getElementById("demo").innerHTML;
if(oldPos.indexOf("0") > -1){
oldPos = oldPos.replace('0', '1');
}
document.getElementById("demo").innerHTML = oldPos;
}
I think you want for(i=0;!check && i<10;i++).
But there is another way to do this using break;
function loadPos()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
document.getElementById("demo").innerHTML = this.responseText;
};
xhttp.open("GET", "posizioni.txt", true);
xhttp.send();
}
function takeFirst()
{
var i=0;
var oldPos=[];
loadPos();
oldPos = document.getElementById("demo").innerHTML;
for(i=0;i<10;++i)
{
if(oldPos[i]=="0")
{
oldPos[i]="1";
break;
}
}
document.getElementById("demo").innerHTML=oldPos;
}
Using Ajax, I've created a sort of console that allows me to execute some PHP functions dynamically.
It looks like this
The problem is that after a bunch of commands, the console becomes hard to read. So I've created a javascript function, named "wipe();", which clears the <div> containing the console.
I tested this function with the developpers tools of chrome (the javascript console) and it works perfectly.
But when I try to call this function by making the PHP-AJAX return a "<script>wipe();</script>", it doesn't work. It does nothing.
I've read on the internet that all the "<script></script>" works independently from each other, but that you can call a <script>function</script> from another <script></script> block.
So why is it failing to do that ?
here is the php code :
echo '<script>wipe();</script>';
and here is the the first <script> block:
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data="+data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML+escapeHtml(data)+'<br>'+xmlhttp.responseText+'<br><br>';
}
xmlhttp.send();
}
function wipe(){
span.innerHTML = '';
}
To avoid security issues ( like a cross-site scripting attack) HTML5 specifies that a <script> tag inserted via innerHTML should not execute.
A way to execute the script is to evaluate the html using eval() . Be warned: using eval can be dangerous.
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data=" + data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML + escapeHtml(data) + '<br>' + xmlhttp.responseText + '<br><br>';
evalJSFromHtml(span.innerHTML);
}
xmlhttp.send();
}
function wipe() {
span.innerHTML = '';
}
function evalJSFromHtml(html) {
var newElement = document.createElement('div');
newElement.innerHTML = html;
var scripts = newElement.getElementsByTagName("script");
for (var i = 0; i < scripts.length; ++i) {
var script = scripts[i];
eval(script.innerHTML);
}
}
}
Call the 'wipe' function as a callback function directly from the 'send' function. Check status = 200 for a success response.
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data="+data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML+escapeHtml(data)+'<br>'+xmlhttp.responseText+'<br><br>';
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
wipe(); // 'Wipe' callback function
}
}
xmlhttp.send();
}
function wipe(){
span.innerHTML = '';
}
But when I try to call this function by making the PHP-AJAX return a "wipe();", it doesn't work. It does nothing.
try create script tag and add to document rather than change inner html.
var spaScript = document.getElementById("spaScript");
var wraper = document.createElement("div");
wraper.innerHTML = xmlhttp.responseText;
var script = document.createElement("script");
script.innerHTML = wraper.getElementsByTagName("script")[0].innerHTML;
spaScript.appendChild(script);
Test if wipe() is in the input and if it is trigger it instead of the ajax call
var xmlhttp = new XMLHttpRequest();
var span = document.getElementById("screen");
function send(data) {
if (data.indexOf('wipe()') == -1) {
window.setInterval(function() {
var elem = document.getElementById('screen');
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "./_rcons-transmetter.php?data=" + data, true)
xmlhttp.onloadend = function() {
span.innerHTML = span.innerHTML + escapeHtml(data) + '<br>' + xmlhttp.responseText + '<br><br>';
}
xmlhttp.send();
}
} else {
wipe();
};
}
function wipe() {
span.innerHTML = '';
}
inserting a script tag directly inside an element should not work (and by the way generating an error in the console).
Using the native eval() function on the response text without speciying the tag attribute should solve the problem.
on server side
echo 'wipe()';
on client side
eval(xmlhttp.responseText)
I've been trying to retrieve information about the latest commit of a specific repo using Javascript, but without many results.
I've been using a XMLHttpRequest to get the data from the repo's commits page (for example: https://api.github.com/repos/trapped/rotmg_svr/commits), but seems like it returns null.
Also, I tried to use regular expressions to get the first match of specific line values (for example, to get the value of the commit description, I used this one: "message": "(.*)", ), making it loop through all lines until it finds something (in the code I've posted I temporarily changed it to line numbers, trying to speed up the process since it wasn't working).
Also, when trying to load the page, it blocks. As my previous experience with C#'s webclient suggests me, it's probably related to the XMLHttpRequest thing (indeed when I tried to debug it was returning an undefined object).
Thanks in advance for all the help.
var messagelineindex = 14;
var linklineindex = 17;
var response = "";
function loadcommits() {
httpGet("https://api.github.com/repos/trapped/rotmg_svr/commits");
var lines = response.split("\n");
var message = parsemessage(lines[messagelineindex]);
var link = parselink(lines[linklineindex]);
addcommit(//+message+"");
//for (var i = 0; i < numlines; i++) {
// var line = lines[i];
// var commitmessage = parsemessage(line);
// if (commitmessage != "") {
// addcommit(commitmessage);
// break;
// }
//}
}
function parselink(text) {
var regex = /"link": "(.*)",/;
var match = regex.exec(text);
if (!match) {
return "";
}
else {
return match[1];
}
}
function parsemessage(text) {
var regex = /"message": "(.*)",/;
var match = regex.exec(text);
if (!match) {
return "";
}
else {
return match[1];
}
}
function addcommit(text) {
document.getElementById("commits").innerHTML = document.getElementById("commits").innerHTML + text.toString() + "\n\r";
}
function httpGet(theUrl) {
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
response = xmlHttp.responseText;
}
}
xmlHttp.open("GET", theUrl, false);
xmlHttp.send(null);
}