Why is & turning into & after page load? - html

I'm using Firefox and working on a page when I notice that & turns into &.
Usually I can fix this by using html_entitiy_decode() - but in this case it's not working.
Then I discovered this. The alert is fired once the page is loaded.
Before
After
The data is loaded using PHP / Yii - not through JS / Ajax. I am however adding / removing brands using JS Knockout.
<ul data-bind="template: { name: 'brand-item-template', data: $root.brands}">
<li>
<span id="<?= $brand->id?>" data-bind="text: brand_name, attr: {'id': brand_id}"><?= $brand->name; ?></span>
</li>
</ul>
Update
I've discovered that this JS Knockout code is what makes the change. But this code should not be triggered until I add a brand. So why is this affecting my &s?
It's the self.addBrand = function() that makes the change. If I remove this function and leave the rest as it is, everything is fine. Can it be a Knockout bug?
$('#store.manage-special-offers').exists(function(){
Store.mangeSpecialOffers();
});
function manageBrandListModel() {
var self = this;
var store_id = $('.data-item-id').val();
var exiting_list = $('.brand-list ul').clone();
// Data
self.brands = ko.observableArray(create_list(exiting_list));
self.brand_name = ko.observable();
self.brand_id = ko.observable();
self.store_id = ko.observable(store_id);
// This is the function that makes the chage
self.addBrand = function() {
if (self.brand_name() != "") {
// Update DB
$('#store.manage-brands').exists(function(){
$.ajax({
url: site_url + '/associatebrand',
type: "POST",
dataType: 'json',
data: {
Brand: {
brandId : self.brand_id(),
storeId : self.store_id(),
add : true
}
},
success: function (data) {
// Add brand to GUI list
self.brands.push(new brand(self.brand_id(), self.brand_name()));
self.brand_name("");
}
});
});
}
}.bind(self);
(...)
function create_list(exiting_list){
var arr_list = [];
$(exiting_list).find('li').each(function(e,li){
var id = $(li).find('span').prop('id');
var name = $(li).find('span').html(); // <--- This is the problem. Must be .text()
arr_list.push(new brand(id,name));
});
return arr_list;
}
Can anyone explain why this is happening?

The credit should really go to both JeremyCook and Quentin for pointing me in the right direction.
$(exiting_list).find('li').each(function(e,li){
var id = $(li).find('span').prop('id');
var name = $(li).find('span').html(); // <--- This is the problem. Must be .text()
arr_list.push(new brand(id,name));
});
What I did wrong was that I used .html() and the text was returned in HTML format. Changing this to .text() solved my problem.

Related

variable insert to a blink function

I'm new to HTML and ajax. I'm trying to insert a ip list from flask , to the ajax and trigger the js function to blink.
but somehow I can't find a way to insert the ip variable (response[i]) into the function value column in a right way.
it is to trigger the blink on the required ip tab in html.
function ajaxForm(){
// var form= new FormData(document.getElementById("myform2"));
var data = {"name":"John Doe"}
$.ajax({
url:"{{ url_for('Submit_form') }}",
type:"post",
contentType:'application/json',
data:JSON.stringify(data),
dataType: "json",
processData:false,
// async: false
success:function(response){
// alert(response)
if (response == "success")
{alert("Success !!!" );}
else {
for(i in response)
{
BLINK(response[i]);
}
}
},
// #time out 也进入 error
error:function(e){
// alert(e.)
alert("Failed submit form trigger!!!!");
}
})
}
<script type="text/javascript">
function BLINK(){
var t = null;
function blink() {
var obj = $('input[id="IP"][value=response[i]]') . <---- here
obj.addClass("blink-class");
t = setTimeout(function () {
obj.removeClass("blink-class");
t = setTimeout(function () {
blink(IP);
}, 550);
}, 550);
}
blink(IP);
t = setTimeout(function () {
clearTimeout(t);
}, 5000);
}
At first, you shoul always provide the HTML code too :) because now we dont know if the issue is there.
So let's try to solve the problem blindly :)
if i see this correctly, you just go wrong on the element and make it even more complicated than it is since you're using jquery, because if u have an ID on your elem, check this out:
// change this:
var obj = $('input[id="IP"][value=response[i]]') . <---- here // .. is your problem :)
obj.addClass("blink-class");
// with the dot you add this obj, which is it self, on it self :) that cant work :)
// you can try:
var obj = $('input[value="' + response[i] + '"]') // with NO dot and no fixed ID!
obj.addClass("blink-class");
// or try this
var obj = $('#' + response[i]);
obj.addClass("blink-class");
// and put the IP into the ID attraktion of your input element.
Second Problem is you are using an undefined variable "ID":
blink(IP); // in your timeout function
but you didnt declare this var, so if i understand your code right then your response[i] should be the IP?
Your function should look like this:
function BLINK(IP) { // <-- here you need the ip as parameter for your: BLINK(response[i]) from ajax
var t = null;
function blink() {
var obj = $('#' + IP) // and put IP in the id from input
obj.addClass("blink-class")
t = setTimeout(function () {
obj.removeClass("blink-class");
t = setTimeout(function () {
blink(IP);
}, 550);
}, 550);
}
blink(IP);
t = setTimeout(function () {
clearTimeout(t);
}, 5000);
}
try this, if its doesnt work please provide complete html and your css code too, also we could need an eventually error message from console, you can see that by pressing F12 in FireFox or Chrome and then switch to the console tab, press F5 then to reload the page and see errors, post it too please.
Or try out my jsfiddle for you:
https://jsfiddle.net/AIQIA/tjg659sr/17/
You have to remove dots from your IP and put it as id in your elem you wants get to blink, further you need to remove the dots from the response[i] or in your php code before, easy use $ip = preg_replace('/\./','',$ip);
Or use this to use only the complete IP in your input value, then you dont need to remove dots:
https://jsfiddle.net/AIQIA/tjg659sr/21/
greetz Toxi

Using data in html from an API response

As a starter in html world, i would like to know and start using simple APIs to insert into my blog posts.
I tried to include as html values some simple API like: https://bitcoinfees.earn.com/api/v1/fees/recommended and I used examples given here: Display Json data in HTML table using javascript and some others more like: http://jsfiddle.net/sEwM6/258/
$.ajax({
url: '/echo/json/', //Change this path to your JSON file.
type: "post",
dataType: "json",
//Remove the "data" attribute, relevant to this example, but isn't necessary in deployment.
data: {
json: JSON.stringify([
{
id: 1,
firstName: "Peter",
lastName: "Jhons"},
{
id: 2,
firstName: "David",
lastName: "Bowie"}
]),
delay: 3
},
success: function(data, textStatus, jqXHR) {
drawTable(data);
}
});
function drawTable(data) {
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(drawRow(data[i]));
}
$("#personDataTable").append(rows);
}
function drawRow(rowData) {
var row = $("<tr />")
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.firstName + "</td>"));
row.append($("<td>" + rowData.lastName + "</td>"));
return row;
}
but the result is always blank.
Please, can you give me some hint to can use that API and insert that numbers values for "fastestFee","halfHourFee","hourFee" as html values?
Thank you all!
Welcome to the html world. You are certainly right in assuming that data from APIs is a great way to make your websites more dynamic.
There is an example on W3 Schools on how to handle a http request. I think this is a good place to start https://www.w3schools.com/xml/xml_http.asp. You create a http object that does some sort of data fetching. In this example it is done with the xhttp.send(). At the same time you have a listener that monitors if the onreadystatechange property of the xhttp has changed. And if that change is status 200 (success) then perform some actions.
Here is my JSfiddle with example from your API
http://jsfiddle.net/zvqr6cxp/
Typically these actions would be to structure the returned data and then do something with the data, like show them in a table.
The example shows the native html xhttp object in use with an event listener. Typically as you learn more about this you would probably start using a framework such as jquery or Angular that can handle http requests smoother, keyword here is callback functions.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//In this example, I used your API link..first I would do is turn the JSON into a JS object
myObject = JSON.parse(xhttp.responseText)
document.getElementById("fast").innerHTML = myObject.fastestFee
document.getElementById("half").innerHTML = myObject.halfHourFee
document.getElementById("hour").innerHTML = myObject.hourFee
}
};
xhttp.open("GET", "https://bitcoinfees.earn.com/api/v1/fees/recommended", true);
xhttp.send();

How to use post from script?

Ths script generates a number:
function updateDue() {
var kmold1 = parseInt(<?php echo $km; ?>);
var kmnew1 = parseInt(document.getElementById("kminput").value);
var tot = kmnew1 - kmold1;
document.getElementById("kmtot").innerHTML = tot;
document.getElementById("kmnew").innerHTML = kmnew1;
document.getElementById("kmold").innerHTML = kmold;
}
The number is displayed on a webpage with this code:
Diff in Km: <span name="kmtot" id="kmtot" value=""></span><br>
This is part of an form that is used to post to an other file.
How can I send the output of id="kmtot" to the next php file?
I have tried:
Diff in Km: <span name="kmtot" id="kmtot" value=""></span><br>
Not working.
<input type="hidden" name="kmtot" id="kmtot">
If I add this, the number of id="kmtot" is not displayed on the webpage, and is not transfered.
Any hints or solutions?
If you are using jQuery, use this code:
$.ajax({
url: 'your-php-file.php',
method: 'post',
data: {
'kmtot': $('#kmtot').val(),
},
success: function(data) {
console.log(data);
}
})
In your-php-file.php, $_POST['kmtot'] will return the value of your element with the ID kmtot.
If you are not using jQuery, you could use Fetch API.

Pass a random JSON pair into an aframe component

Edit 3: The code is now working across numerous objects (thanks to Noam) and he has also helped in getting the random function working alongside it. I'll update the code in the question once its implemented.
Edit 2: I've taken #Noam Almosnino's answer and am now trying to apply it to an Array with numerous objects (unsuccessfully). Here's the Remix link. Please help!
Edit: I've taken some feedback and found this page which talks about using a JSON.parse function. I've edited the code to reflect the new changes but I still can't figure out exactly whats missing.
Original: I thought this previous answer would help in my attempt to parse a json file and return a random string and its related pair (e.g Title-Platform), but I couldn't get it to work. My goal is to render the output as a text item in my scene. I've really enjoyed working with A-frame but am having a hard time finding documentation that can help me in this regard. I tried using the following modified script to get text from the Json file...
AFRAME.registerComponent('super', { // Not working
schema: {
Games: {type: 'array'},
jsonData: {
parse: JSON.parse,
stringify: JSON.stringify}
},
init: function () {
var el = this.el;
el.setAttribute('super', 'jsonData', {src:"https://cdn.glitch.com/b031cbf1-dd2b-4a85-84d5-09fd0cb747ab%2Ftrivia.json?1514896425219"});
var hugeArray = ["Title", "Platform",...];
const el.setAttribute('super', {Games: hugeArray});
el.setAttribute('position', {x:-2, y:2, z:-3});
}
});
The triggers are also set up in my html to render the text. My code is being worked on through glitch.com, any help will be much appreciated!
To load the json, I think you need to use an XMLHttpRequest (as Diego pointed out in the comments), when that's loaded, you can set the text through setAttribute.
Here's a basic example on glitch:
https://glitch.com/edit/#!/a-frame-json-to-text
On init it does the request, then when done, it set's the loaded json text onto the entity.
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var jsonText = JSON.parse( event.target.response )
textEntity.setAttribute("value", jsonText.text)
} );
request.send( null );
}
});
Updated version: https://glitch.com/edit/#!/peppermint-direction
AFRAME.registerComponent('json-text-loader', {
schema: {},
init: function () {
var textEntity = document.querySelector('#text');
var url = 'json/text.json';
var request = new XMLHttpRequest();
request.open( 'GET', url, true );
request.addEventListener( 'load', function ( event ) {
var games = JSON.parse( event.target.response ).games;
// Get a random game from the list
var randomGame = games[Math.floor(Math.random()*games.length)];
// Get the next game if it's available
var nextGame = null
if (games.indexOf(randomGame) < games.length - 1) {
nextGame = games[games.indexOf(randomGame) + 1]
}
// Build the string for the games
var gameInfo = randomGame.Title + '\n' + randomGame.Developer + '\n\n'
if (nextGame != null) {
gameInfo += nextGame.Title + '\n' + nextGame.Developer + '\n'
}
textEntity.setAttribute("value", gameInfo);
var sceneEl = document.querySelector('a-scene');
sceneEl.querySelector('a-box').setAttribute('material', {src:"https://cdn.glitch.com/4e63fbc2-a1b0-4e38-b37a-9870b5594af8%2FResident%20Evil.jpg?1514826910998"});
});
request.send( null );
}
});

Some HTML buttons aren't working

I have a small website and it is complete. I am just a senior and it is just for a project on learning how to code. Everything works to perfection on the source computer that it was all coded on. I then exported the files and tried on several other computers. The files open up and everything looks okay, but two out of the five HTML buttons won't work. Is there a common reason why this is happening?
This is the java function for the button
$('#createPassSubmit').click(function() {
var create = true;
var location = $('[name="reason"]').val();
var passnumber = $('#passnumber').val();
var note = $('[name="notes"]').val();
var student = $('#studentID').val();
var teacher = $('#teacherID').val();
var dataString = "CreatePass="+create+"&reason="+location+"&notes="+note+"&studentID="+student+"&teacherID="+teacher+"&passnumber="+passnumber;
$.ajax({
method: 'POST',
url: 'ajax.php',
data: dataString,
success: function(data) {
if(JSON.parse(data) === 'ERROR') {
alert("Pass " + passnumber + " is currently in use");
}
else {
$('#form input[type=text]').val('');
$("#form select").val('')
$('#sname').val('');
}
}
});
});
});
Then this is the HTML button its self
<input type="button" id="createPassSubmit" value="Create">