This code is meant to send a JSON request and store it under the variable json. It is then meant to display a picture depending on the value of a key (specifically if the key gender = male). No picture is displaying and I can't find a solution anywhere so is anyone able to help?
var i=20
while (i<10)
{var json = new XMLHttpRequest();
json.open('GET', "http://localhost:8081/getPersons?format=json", true);
json.send();
json.onreadystatechange = processRequest;
function processRequest(e) {
if (json.readyState == 4 && json.status == 200) {
var response = JSON.parse(json.responseText);
alert(response.ip);
}
}
var wantedKey = 'gender'; // your key here
var wantedVal = 'male'; // your value here
for(var i = 0; i < json.length; i++){
if(json[i].hasOwnProperty(gender) && json[i][gender] === male) {
document.createElement("img");
img.src = "http://advertdemo.ga/adverts/emotion_neutral/male/young/iphone.jpg";
img.width = "300px";
img.height = "300px";
// This next line will just add it to the <body> tag
document.body.appendChild(img);
break;
}
}}
There are a multitude of problems with your code, most importantly that you seem to misunderstand how AJAX works. Here's my fix with comments on what was wrong and where.
var json = new XMLHttpRequest();
json.open('GET', "http://localhost:8081/getPersons?format=json", true);
json.send();
// It's better to declare event handlers this way,
// your version relied on variable hoisting (look it up),
// which is not usually recommended.
json.onreadystatechange = function(e) {
if (json.readyState == 4 && json.status == 200) {
var response = JSON.parse(json.responseText);
// This was the main problem:
// Processing the result of the XHR should be *inside* the
// readystate (or load) event handler
for (var i = 0; i < response.length; i++) {
// You forgot to put the property name "gender" in quotes
// as well as the value "male"
// Also, the double check was unnecessary. This is perfectly safe.
if(response[i]['gender'] === 'male') {
var img = document.createElement("img");
img.src = "http://advertdemo.ga/adverts/emotion_neutral/male/young/iphone.jpg";
// You should set dimensions on the style property,
// not img directly
img.style.width = "300px";
img.style.height = "300px";
document.body.appendChild(img);
break;
}
}
}
}
try this:
var i=20
while (i<10)
{var json = new XMLHttpRequest();
json.open('GET', "http://localhost:8081/getPersons?format=json", true);
json.send();
json.onreadystatechange = processRequest;
function processRequest(e) {
if (json.readyState == 4 && json.status == 200) {
var response = JSON.parse(json.responseText);
alert(response.ip);
}
}
var wantedKey = 'gender'; // your key here
var wantedVal = 'male'; // your value here
for(var j = 0; j < json.length; j++){
if(json[i].hasOwnProperty(gender) && json[i][gender] === male) {
img= document.createElement("img");
img.setAttribute("src", "http://advertdemo.ga/adverts/emotion_neutral/male/young/iphone.jpg");
img.setAttribute("width", "300");
img.setAttribute("height", "300");
// This next line will just add it to the <body> tag
document.body.appendChild(img);
break;
}
}}
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();
});
I have written this function to make ajax-requests to my server that serves JSON objects in string-format. I want to parse these JSON-objects into Javascript objects using JSON.parse(). But when I check the type of the object returned by JSON.parse(), it's a string! Here's the function:
function getDBMatches(){
var xhr = createXHR();
xhr.dropdown = this.parentNode.parentNode.getElementsByClassName("dropdown-content")[0];
xhr.dropdown.innerHTML = "";
if(!xhr.dropdown.classList.contains('show')){
xhr.dropdown.classList.add('show');
}
xhr.onreadystatechange = function(){
if (this.value == ""){
return;
}
if (xhr.readyState == 4){
if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304){
var xhrResponse = xhr.responseText;
alert(xhrResponse); // "[{\"model\": \"workoutcal.liftactivity\", \"pk\": 1, \"fields\": {\"name\": \"benchpress\"}}]"
alert(typeof xhrResponse); // string
var dbMatches = JSON.parse(xhrResponse);
alert(typeof dbMatches); // string! This is what I don't understand.
for(var i = 0; i < dbMatches.length; i++){
var link = document.createElement("a");
link.innerHTML = dbMatches[i]["name"];
link.onclick = function(){
var textbox = link.parentNode.parentNode.getElementsByTagName('input')[0];
textbox.value = link.innerHTML;
xhr.dropdown.innerHTML = "";
};
xhr.dropdown.appendChild(link);
}
} else {
document.getElementById("xhrPar").innerHTML = "Request was unsuccessful: "+xhr.status;
}
}
};
var url = "http://localhost:8000/workoutcal/";
if (this.name == "lift_string"){
url += "get_lifts";
} else if (this.name == "cardio_string"){
url += "get_cardio";
}
url = addURLParam(url, this.name, this.value);
xhr.open("get", url, false);
xhr.send(null);
}
Why isn't the string parsed into a Javascript object?
JSON.parse() returns literal which can be of type Object, String or other types depending upon the parameter being passed to the parse function. Consider the below expression which will return val of type string.
var val = JSON.parse(JSON.stringify("Hello"));
I am trying to append an image into a span, it works perfectly outputting the image path as text using:
homeTeamName_span.appendChild(homeTeamName_crest);
However, when trying to wrap image tags around it, it doesn't do anything and no data will load because of it.
What would be the reason for this?
homeTeamName_span.appendChild("<img src='homeTeamName_crest' />");
Function source
window.onload = function() {
var xmlhttp = new XMLHttpRequest();
var url = "http://bushell.net/football/site/includes/webservice.php?service=allfixtures&limit=10&competition=427";
var url2 = "http://bushell.net/football/site/includes/webservice.php?service=allfixtures&limit=10&competition=426"
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
getECL(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function getECL(response) {
var ECL_arr = JSON.parse(response);
var i;
//add 6hrs
var ecl_games = document.getElementById("ecl-games");
for(i = 0; i < ECL_arr.length; i++) {
var gameInfo_container = document.createElement("LI");
ecl_games.appendChild(gameInfo_container);
var homeTeamName_span = document.createElement("SPAN");
homeTeamName_span.className = "text-right";
var homeTeamName_text = document.createTextNode(ECL_arr[i].homeTeamName);
homeTeamName_span.appendChild(homeTeamName_text);
gameInfo_container.appendChild(homeTeamName_span);
var date_span = document.createElement("SPAN");
date_span.className = "d-g";
var date_span_text = document.createTextNode(ECL_arr[i].date);
date_span.appendChild(date_span_text);
gameInfo_container.appendChild(date_span);
var awayTeamName_span = document.createElement("SPAN");
awayTeamName_span.className = "text-left";
var awayTeamName_text = document.createTextNode(ECL_arr[i].awayTeamName);
awayTeamName_span.appendChild(awayTeamName_text);
gameInfo_container.appendChild(awayTeamName_span);
}
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
getPrem(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url2, true);
xmlhttp.send();
function getPrem(response){
var prem_arr = JSON.parse(response);
var prem_games = document.getElementById("prem-games");
for(var j = 0; j<prem_arr.length; j++) {
var gameInfo_container = document.createElement("LI");
prem_games.appendChild(gameInfo_container);
var homeTeamName_span = document.createElement("SPAN");
homeTeamName_span.className = "text-right";
var homeTeamName_text = document.createTextNode(prem_arr[j].homeTeamName);
var homeTeamName_crest = document.createTextNode(prem_arr[j].homeTeamCrest);
homeTeamName_span.appendChild("<img src='homeTeamName_crest' />");
homeTeamName_span.appendChild(homeTeamName_text);
gameInfo_container.appendChild(homeTeamName_span);
var date_span = document.createElement("SPAN");
date_span.className = "d-g";
var date_span_text = document.createTextNode(prem_arr[j].date);
date_span.appendChild(date_span_text);
gameInfo_container.appendChild(date_span);
var awayTeamName_span = document.createElement("SPAN");
awayTeamName_span.className = "text-left";
var awayTeamName_text = document.createTextNode(prem_arr[j].awayTeamName);
awayTeamName_span.appendChild(awayTeamName_text);
gameInfo_container.appendChild(awayTeamName_span);
}
console.log("loop finished");
}
}
this shoud work , if homeTeamName_crest is the path of the picture
$(homeTeamName_span).append("<img src='"+homeTeamName_crest+"' />")
What if you do this?
var homeTeamName_crest = prem_arr[j].homeTeamCrest; // <--- change this line, don't make it a textNode
homeTeamName_span.appendChild("<img src='" + homeTeamName_crest + '/>"); // <--- change this line, we want to interpolate the string as the path to the image
$.ajax({
url: 'http://' + window.location.host + '/',
success: function(data){
$(data).find("a:contains(.jpg)").each(function(){
// will loop through
var images = $(this).attr("href");
$('<p></p>').html(images).appendTo('a div of your choice')
});
}
});
I couldn't find a way to do the same in javascript, I can make ajax call like this
request = new XMLHttpRequest();
request.open('GET', 'http://' + window.location.host + '/', true);
request.onload = function(files) {
if (request.status >= 200 && request.status < 400){
// Success!
resp = request.responseText;
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
but how do I get the list of the files in the directory?
CSJS and/or SSJS both answers are okay.
My main goal is not to use jQuery to accomplish what I want.
If you want to loop through the a:contains(.jpg) like in your jQuery example, your best bet is probably to use a DocumentFragment and then call .querySelectorAll on it :
var div = document.createElement('div');
div.innerHTML = request.responseText;
// if you want to search using text
var links = div.querySelectorAll('a')
for (i = 0; i < links.length; i++) {
var link = links[i];
if (!~link.innerHTML.indexOf('.jpg'))
continue;
// found one !
}
// if you want to search using an attribute
var links = div.querySelectorAll("a[href*='.jpg']");
You can dump the response text into a newly created <div> and use the standard methods to access the anchors; the following should even work for IE7:
// $(resp)
var doc = document.createElement('div');
doc.innerHTML = resp;
// .find('a')
var anchors = doc.getElementsByTagName('a'), // get all anchors
container = document.getElementById('some_id');
// .filter(":contains(.jpg)")
for (var i = 0; i < anchors.length; ++i) {
var contents = anchors[i].textContent || anchors[i].innerText || '';
if (contents.indexOf('.jpg') != -1) {
// var images = $(this).attr("href");
// $('<p></p>').html(images).appendTo
var para = document.createElement('p'),
text = document.createTextNode(anchors[i].href);
para.appendChild(text);
container.appendChild(para);
}
}
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.