Need help Ajax / Javascript - javascript

I'm stumped on this one. I am going to have an unknown number of hidden and unhidden (depending the amount of information the user has in my database) with an Onclick function. when each of the unhidden div's are clicked i pass the value of them through AJAX and grab some text from a php file.
function selectProduct(index) {
var option = document.getElementById('sel'+index).value;
var queryStringOne = "?option="+option;
http.open("GET", "product.php" +
queryStringOne, true);
http.onreadystatechange = getHttpResOne+index;
http.send(null);
}
function getHttpResOne(index) {
if (http.readyState == 4) {
resOne = http.responseText; // These following lines get the response and update the page
document.getElementById('prohidden'+index).innerHTML = resOne;
}
}
HTML
<div id="sel1" value="sel1" onClick="selectProduct(1); return false;">Select Item</div>
<div id="prohidden1" class="sel"></div> <!-- hidden -->
<div id="sel2" value="sel2" onClick="selectProduct(2); return false;">Select Item</div>
<div id="prohidden2" class="sel"></div><!-- hidden -->
I need the response text from each div clicked, to replace the hidden div right underneath it. I am having trouble passing the (index) to the getHttpRequestOne() function.

You can always add custom properties to the native objects. It might not be the best way. but you can try this.
function selectProduct(index) {
var option = document.getElementById('sel'+index).value;
var queryStringOne = "?option="+option;
http.open("GET", "product.php" +
queryStringOne, true);
http.onreadystatechange = getHttpResOne;
http.myCustomValue = index;
http.send(null);
}
function getHttpResOne() {
if (http.readyState == 4) {
resOne = http.responseText; // These following lines get the response and update the page
var index = http.myCustomValue;
document.getElementById('prohidden'+index).innerHTML = resOne;
}
}

Related

change the html content after getting it from a url with javascript

i am using javascript code to get html content from one the pages, while at the same time i also want to change the content i get from html (inside the carttitle id). how can i change the value of id=carttitle on the cartbox.html below dynamically?
this is the code (div where the html will be located)
<!-- index.html -->
<!-- button to trigger the function -->
<button onclick="getcontent('cartbox.html','#cartboxes','#cartbox');">getcontent</button> <!-- the cartbox.html will fill the content below -->
<ul class="cartboxes" id="cartboxes">
</ul>
this is the javascript code function to get the html
// select.js
function getcontent(url, from, to) {
var cached = sessionStorage[url];
if (!from) {
from = "body";
} // default to grabbing body tag
if (to && to.split) {
to = document.querySelector(to);
} // a string TO turns into an element
if (!to) {
to = document.querySelector(from);
} // default re-using the source elm as the target elm
if (cached) {
return to.innerHTML = cached;
} // cache responses for instant re-use re-use
var XHRt = new XMLHttpRequest; // new ajax
XHRt.responseType = 'document'; // ajax2 context and onload() event
XHRt.onload = function() {
sessionStorage[url] = to.innerHTML = XHRt.response.querySelector(from).innerHTML;
};
XHRt.open("GET", url, true);
XHRt.send();
return XHRt;
}
this is the html code that i will get the content from
<!-- cartbox.html -->
<div id="cartbox">
<li>
<div class="cartbox">
<div class="cartboxleft">
<img src="img/search.png" width="60px" height="60px">
</div>
<div class="cartboxright">
<!-- i want to change the value of the carttitle below dynamically -->
<b class="carttitle" id="carttitle">nice Pizza</b>
<p class="cartdescription">Number: <b>1</b></p>
<p class="cartdescription">Price: <b>$ 11.22</b></p>
</div>
<div class="cartboxdelete">
<button class="deletebutton" onclick="deleteitem(this);">X</button>
</div>
</div>
</li>
</div>
You should use responseType = 'text' as document responseType is not recommended to avoids wasting time parsing HTML uselessly. Now regarding your issue, you can do like this:
function getcontent(url, fromSelector, toSelector) {
var cached = sessionStorage[url];
if (cached) {
return toSelector.innerHTML = cached;
}
fromSelector = fromSelector || 'body';
toSelector = toSelector && document.querySelector(toSelector) || document.querySelector(fromSelector);
var XHRt = new XMLHttpRequest();
XHRt.open("GET", url, true);
XHRt.responseType = 'text';
XHRt.onload = function() {
if (XHRt.readyState === XHRt.DONE && XHRt.status === 200) {
toSelector.innerHTML = XHRt.responseText;
document.getElementById('carttitle').innerHTML = 'your new value';
sessionStorage[url] = toSelector.innerHTML; // Now it will work after loading from session storage.
}
};
XHRt.send();
}
Your cache process will not work because you are selecting a property with the brackets operator [] on the session storage object.
Instead use the getItem() method to get the key that you are looking for.
var cached = sessionStorage.getItem(url);
In your second if statement you check to and to.split. Unless the to string has a split property, this will fail. Your intentions here seem unknown. Instead just check for the string to be a valid string instead.
if (to && 'string' === typeof to) {
The part where you create a new instance of XMLHttpRequest will fail because you are missing the parenthesis to call the constructor.
var XHRt = new XMLHttpRequest();
Then in your onload callback you have to save the innerHTML of your result in the session storage using the setItem() method.
But before doing that, select the cart title element with querySelector and change the content of the element if you need it to.
XHRt.onload = function() {
let element = this.response.querySelector(from);
if (element !== null) {
let cartTitle = element.querySelector('#carttitle');
cartTitle.textContent = 'An even better pizza';
let html = element.innerHTML;
to.innerHTML = html;
sessionStorage.setItem(url, html);
}
};

Script not altering text in <span>

I have this script that is collecting the names of places via API from postal codes. The postal codes are inserted to a field, and the corresponding place shows up in a <span>. It's working perfectly fine on several of my web sites, but on this one page (Wordpress, Kinetika theme) it won't work.
The site is using Contact form 7, but it doesn't seem to be related to that (works on other sites with CF7).
I'm clueless to what's causing this problem with this particular theme. Any suggestions?
Tried changing [text....] to <input type="text" id="poststed">. No change.
As you can se here, it runs just fine: https://js.do/code/275407
[text* postnummer id:postnummer class:postnummer]
<span id="poststed" style="font-weight: 700; color: #00ba00">POSTSTED</span>
<script>
function validatePostalcode(postnummer) {
if (postnummer.length < 4) {
return;
} else {
var conn = new XMLHttpRequest();
conn.onreadystatechange = function () {
if (conn.readyState === XMLHttpRequest.DONE) {
var data = JSON.parse(conn.responseText);
document.getElementById('poststed').textContent = data.result;
}
};
var url = 'https://fraktguide.bring.no/fraktguide/api/postalCode.json?pnr=' + postnummer + '&callback=?'; conn.open('GET', url, true); conn.send();
}
}
var ele = document.getElementById('postnummer');
ele.addEventListener('keyup', function (evt) {
validatePostalcode(ele.value);
});
</script>
Solved!
I changed
if (conn.readyState === XMLHttpRequest.DONE) {
to
if (conn.readyState === 4) {
And now it works! I'm not sure why this is not an issue with other WP themes, but at least this solved the problem for me.

Replace div contents javascript (no jquery)

Every time a selection is made from a dropdown menu, specific data is pulled from facebook and added to different divs. I am trying to update the contents of the div every time a different selection is made, however at the minute, the contents are just appended on after the initial contents.
This is the code that gets data based on a selection and creates the list from the returned data
<script>
city = document.getElementById("citySelection")
city.addEventListener("change", function() {
var selected = this.value;
var eventsList = document.getElementById("events");
if (selected == "None") {
eventsList.style.display = "none";
} else {
eventsList.style.display = "block";
};
if (selected == 'Bristol') {
getBristolEvents();
};
if (selected == 'Leeds') {
getLeedsEvents();
};
if (selected == 'Manchester') {
getManchesterEvents();
};
if (selected == 'Newcastle') {
getNewcastleEvents();
};
});
function createList(response, listId) {
var list = document.createElement('UL')
for (var i = 0; i < 10; i++) {
var events = response.data[i].name
var node = document.createElement('LI');
var textNode = document.createTextNode(events);
node.appendChild(textNode);
list.appendChild(node)
listId.appendChild(list);
}};
</script
This is the div being targeted:
<html>
<div id="events" style="display: none">
<div id="eventsDiv" style="display: block">
<div id="eventsListOne">
<h3 id='headerOne'></h3>
</div>
<div id="eventsListTwo">
<h3 id='headerTwo'></h3>
</div>
<div id="eventsListThree">
<h3 id='headerThree'></h3>
</div>
</div>
</div>
</div>
</html>
I have tried resetting the innerHtml of the div every time the function to get the data from facebook is called:
<script>
function getEventsThree(fbUrl, title) {
var listId = document.getElementById('eventsListThree');
var headerThree = document.getElementById('headerThree');
listId.innerHtml = "";
headerThree.append(title)
FB.api(
fbUrl,
'GET', {
access_token
},
function(response) {
listId.innerHtml = createList(response, listId)
}
)};
</script>
However, that still doesn't reset the contents of the div.
I've looked at other response but they all use jquery which I am not using.
Can anyone advise on the best way to fix this? Thanks.
I think your Hennessy approach is fine. Generate the inner content, then set .innerHTML.
At least one of your problems, maybe the only one, appears to be that you set .innerHTML to the return value of createList, but that function does not return anything.

How to load dropdown list in html from a properties file?

If anyone could help
I have a properties file as below (db.properties) :-
1=DEV;
2=NATIVE;
and i have to load this value from the properties file into the drop down present in html file
below is my html file :-
<body>
<p> Select the environment </p>
<br>
<select name="env">
<option value="DEV">DEV</option>
<option value="NATIVE">NATIVE</option>
</select>
</body>
the values from the properties file should come automatically into the drop down present in HTML. Even if a new value is added in the properties file that should be present in the drop down.
Can anyone suggest some code to do the same it would be really helpful
Thank you :)
It would be better to have this file is in json format, but you can download it using XMLHttpRequest (it must be on the same server regarding same-origin policy), parse with split("=") and modify DOM tree by means of appendChild and innerHTML.
If you want to have live changes, you can use setTimeout (first time in DOMContentLoaded, subsequently after modifying SELECT).
Hope this helps.
oo = {};
oo.refreshInterval = 1000;
oo.fileToRequest = 'config.txt';
oo.loadList = function() {
var req = new XMLHttpRequest();
var lines;
var select = document.querySelector('select:first-of-type');
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
lines = req.responseText.split('\n');
while (select.firstChild) {
select.removeChild(select.firstChild);
}
lines.forEach(function(value) {
var describer = value.split('=')[1];
var option = document.createElement('option');
var text =
document.createTextNode(
describer.substr(0, describer.length - 1)
);
option.appendChild(text);
select.appendChild(option);
});
}
}
req.open('get', oo.fileToRequest);
req.send(null);
}
window.addEventListener('load', function() {
oo.loadList();
// Refresh the select box.
setInterval(oo.loadList, oo.refreshInterval);
});
You can do it very easily with ajax using jQuery I have created a demonstration here http://plnkr.co/edit/7PbH8AdQxGc9RGmxslkr?p=preview
Your HTML
<p> Select the environment </p>
<br>
<select name="env"></select>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
Your db.properties file
1=DEV;
2=NATIVE;
js
$(function(){
jQuery.ajax({
url: "db.properties"
}).done(function(data){
var options = data.split(/\n/);
$('select[name="env"]').html('');
for (i=0; i<options.length; i++) {
console.log(options[i].split('='));
var optionVal = options[i].split('=').pop().replace(';', "");
$('select[name="env"]').html('<option value="'+ optionVal +'">'+ optionVal +'</option>');
}
})
});
Don't be afraid of using Ajax, it's pretty simple:
<script>
window.onload = function(){
var xhr = new XMLHttpRequest(),
dropdown = document.getElementById("env"),
lines = [], i, count, line, item;
xhr.open('GET', '/db.properties');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
if (xhr.responseText) {
dropdown.innerHtml = "";
lines = xhr.responseText.split('/\n|\r\n/');
for(i=0,count = lines.length; i < count; i+ = 1){
line = lines[i].split('=');
item = document.createElement('option');
item.text = line[1];
item.value = line[0];
dropdown.appendChild(item);
}
}
}
}
xhr.send();
}
</script>
<body>
<p> Select the environment </p>
<br>
<select name="env" id="env">
</select>
</body>

Javascript: Populating a select list from a json file and displaying in a div

I have created a space invaders game using the following tutorial: http://www.html5rocks.com/en/tutorials/canvas/notearsgame/
I now need to populate a select list of states using json within the javascript. I have tried the following set up; I have created a div where the select box can be displayed.
<body>
<h1>Game</h1>
<div id="displaycontent"></div>
<script type='text/javascript'>
I now have the callback functions to populate the list.
function getStates()
{
var url = "states_json.php";
req = new XMLHttpRequest();
req.open("GET", url, true);
//req.setRequestHeader("Accept","application/json; charset=utf-8");
req.onreadystatechange = getStatesCallBack;
req.send(null);
}
function getStatesCallBack()
{
if (req.readyState == 4)
{
if (req.status == 200)
{
var response = req.responseText.parseJSON();
var displaycontent = document.getElementById("displaycontent");
while (displaycontent.hasChildNodes())
{
displaycontent.removeChild(displaycontent.lastChild);
}
var stateSelect = document.createElement("select");
stateSelect.setAttribute("id", "stateslist");
//artistSelect.setAttribute("onChange", "getArtistInfo()");
displaycontent.appendChild(stateSelect);
var state = response.statesarray;
for (i = 0; i <state.length; i++)
{
var state_id = state[i].state_id;
var state_name = state[i].state_name;
if (stateSelect != null && stateSelect.options != null)
{
stateSelect.options[stateSelect.options.length] =
new Option(state_name, state_id, false, true);
}
}
stateSelect.options[0].selected = true;
displaycontent.appendChild(stateSelect);
var stateDetailDiv = document.createElement("div");
stateDetailDiv.setAttribute("id", "statedetails");
displaycontent.appendChild(stateDetailDiv);
//getArtistInfo();
}
}
}
The game code from the tutorial follows the above code. The game works fine however there is no select list populated at all. I have checked the json file output and it is displaying the correct information so that is not the issue. I have tried debugging in firebug but it doesn't show any errors.
The HTML for your select list should look like this eventually:
<select name="stateslist">
<option value="value1">Label For value 1</option>
<option value="value2">Label For value 2</option>
<option value="value3">Label For value 3</option>
</select>
So you should try changing the contents of your for (i = 0; i <state.length; i++) loop and do something like that for each iteration:
var option = document.createElement("option");
option.setAttribute('value', state_id);
option.textContent = state_name;
stateSelect.appendChild(option);

Categories

Resources