I am trying to display next item from array json with displayItem function, but after click on the button, the form reloads the first value (arrayResponse[0]). What should I do to display the next item instead?
$(document).ready(function () {
var firstElement;
var arrayResponse;
var index = 0;
var request = new XMLHttpRequest();
// When the file has loaded,
request.onload = function () {
// parse the JSON text into an array of post objects.
arrayResponse = JSON.parse(request.responseText);
var firstelement = arrayResponse[0];
$("#name").val(firstelement.name);
$("#author").val(firstelement.author);
$("#content").val(firstelement.content);
// Pass the posts array to the callback.
};
request.open("GET", "http://127.0.0.1:8887/posts.json", true);
request.send(null);
$("#nextButton").bind("click", function () {
displayItem(arrayResponse[++index])
});
function displayItem(item) {
$("#name").val(item.name);
$("#author").val(item.author);
$("#content").val(item.content);
}
});
I checked your code with this test json
I created this jsfiddle and it seems to work perfect. There must be some kind of error with your json.
Html:
<input id="name" /><br>
<input id="author" /><br>
<input id="content" /><br>
<button id="nextButton">Next</button>
Js:
$(document).ready(function() {
var firstElement;
var arrayResponse;
var index =0;
var request = new XMLHttpRequest();
// When the file has loaded,
request.onload = function () {
// parse the JSON text into an array of post objects.
arrayResponse = JSON.parse(request.responseText);
firstelement = arrayResponse[0];
$("#name").val(firstelement.id);
$("#author").val(firstelement.name);
$("#content").val(firstelement.username);
// Pass the posts array to the callback.
};
request.open("GET", "https://jsonplaceholder.typicode.com/users", true);
request.send(null);
$("#nextButton").bind("click", function(){
displayItem(arrayResponse[++index])
});
function displayItem(item) {
$("#name").val(item.id);
$("#author").val(item.name);
$("#content").val(item.username);
}
});
Change this :
$("#nextButton").bind("click", function(){
displayItem(arrayResponse[++index])
});
to this:
$("#nextButton").bind("click", function(){
displayItem(arrayResponse[index]);
index++;
});
Related
In the script , a button have an onclick function that call deleteByName function
<button onclick='deleteByName("name","view","view_value")' type='button'>
In this function , it use AJAX to execute delete method and calls search function to update page
function deleteByName (target,view,view_value){
var url = "http://localhost/assignment_web/index.php/facility/name/"+target;
request.open("DELETE", url, true);
request.send(null);
search("all");
}
In search function , it use AJAX get method to retrieve data and use updatePage attribute to update the innerHTML
function search(type) {
var target = "" ;
if(type=="district"|type=="name"){
var target = document.getElementById('option_txt').value;
}
var url = "http://localhost/assignment_web/index.php/facility/"+type+"/"+target;
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
function updatePage() {
if (request.readyState==4) {
if (request.status==200) {
var serverData = request.responseText;
console.log("serverData: "+serverData);
var dataArr = JSON.parse(serverData);
var objLen = Object.keys(dataArr).length;
var view = document.querySelector('input[name="option"]:checked').value;
var view_value;
var html ="<ul>";
for(let i=0;i<objLen;i++){
var name =dataArr[i].Name_en ;
if(view=="district"){view_value = dataArr[i].District_en;}else if(view=="name"){view_value = dataArr[i].Name_en;
}else{view_value = "all" ; }
html = html+"<li>District : "+dataArr[i].District_cn+" "+dataArr[i].District_en
+"</li>...<li><button onclick='deleteByName(\""+name+"\",\""+view+"\",\""+view_value+"\")' type='button'>delete</button>
<div name=\""+name+"_textBox\" id=\""+name+"_textBox\"></div></li><hr>" ;
}
html = html+"</ul>";
document.getElementById("displayArea").innerHTML = html;
}
}
}
The question is , in get method , it retrieved the data (shown in console.log(DataArr) ) i was deleted from the delete method before . How do i make sure the update function won't retrieve any data that is deleted before instead retrieving the data after the delete method is complete ...
I am trying to replace text in my page using handlebars. But its not working and i am not getting any errors either.
The following code kicks in when the user presses the submit button
<button type="submit" id="add_lunch" class="button button-contactForm boxed-btn" onclick="addToCart()">Submit</button>
this then
function addtoCart() {
var request = new XMLHttpRequest();
var base_id = $("input[name='base_id']:checked").val();
var protein_id = $("input[name='protein_id']:checked").val();
var dessert_id = $("input[name='dessert_id']:checked").val();
var side_id = $("input[name='dessert_id']:checked").val();
request.open('POST', '/cart');
request.onload = () => {
// Extract JSON data from request
var template = Handlebars.compile(document.querySelector('#js_result').innerHTML);
var data_response = JSON.parse(request.responseText);
var content = template({'base_name': data_response.base.name});
console.log("****" + data_response.base.name)
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#add_lunch').onclick = () => {
document.querySelector('#media_js_body').innerHTML += content;
};
});
}
var data = new FormData();
data.append('base_id', base_id);
data.append('protein_id', protein_id);
data.append('side_id', side_id);
data.append('dessert_id', dessert_id);
// Send request
request.send(data);
return false;
}
plus the template
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<script id="js_result" type="text/x-handlebars-template">
{{ base_name }}
</script>
<script src="{{ url_for('static', filename='js/util.js') }}"></script>
What i have figured out so far is that it has something to do with DOM state? and onclick even.
Any suggestions and corrections?
i do not know if it was the coffee i drank, but after a few sips and few changes it seems to work partially now. i am getting the text being placed in the right place.
Now i only have to make sure that the values from data_response gets transferred in content as well
This is what i changed.
function addToCart() {
var request = new XMLHttpRequest();
var limit=2;
var base_id = $("input[name='base_id']:checked").val();
var protein_id = $("input[name='protein_id']:checked").val();
var dessert_id = $("input[name='dessert_id']:checked").val();
var side_id = [];
$.each($("input[name='side_id']:checked"), function(){
side_id.push($(this).val());
});
if(side_id.length==limit) {
request.open('POST', '/cart');
request.onload = () => {
// Extract JSON data from request
var data_response = JSON.parse(request.responseText);
var templateInfo=document.querySelector('#js_result').innerHTML
console.log("TempInfo:" + templateInfo)
var template = Handlebars.compile(templateInfo);
var content = template({'base_name': data_response.base.name});
console.log("DataResponse:" + data_response.base.name);
console.log("Content:" + data_response.base.name);
document.querySelector('#media_js_body').innerHTML += content;
}
var data = new FormData();
data.append('base_id', base_id);
data.append('protein_id', protein_id);
data.append('side_id', side_id);
data.append('dessert_id', dessert_id);
// Send request
request.send(data);
} else {
alert("Kindly select "+limit+" sides")
}
return false;
}
I'm loading data from api into html table and would like to use user input field to change api call.
<input id="stockInput" value="AAPL"></input>
<br/>
<button id="submit">Submit</button>
const stocksBody = document.querySelector("#stocks-table > tbody
#data");
var input = $("#stockInput").val();
var url = "https://api.iextrading.com/1.0//stock";
var quote = "/quote";
function setup() {
var button = select("#submit");
button.mousePressed(loadData);
}
function loadData(){
const request = new XMLHttpRequest();
request.open("get", url + input.val() + quote);
request.onload = () => {
try {
var response = JSON.parse(request.responseText);
console.log(response);
populateData(response);x
} catch (e) {
console.warn("Could not load data!");
}
};
request.send();
I expect stock symbol entered by user to return stock data.
You are calling .val() twice.
Change this line:
request.open("get", url + input.val() + quote);
// ^^^^^^ - remove
I am working with a JSON file that I have, and I am linking it in my JavaScript.
I am trying to get it requested through AJAX to show up on my console.log, but I am just getting null for my readystatechange function. What am I doing wrong?
Also to better clarify I am doing this for my course and ideally what my goal is; I have a json file that I created (myjson.com), I have that URL its in my JavaScript, and I am trying to get that json url to update to my JavaScript so when I do a console.log it shows up the values of the objects from the json. Here's my code:
<div id="btn1"> Update </div>
<div id="output"></div>
<script>
var output = document.getElementById("output");
document.getElementById("btn1").onclick = function () {
var a = newXMLHttpRequest();
a.onreadystatechange = function () {
}
a.open("GET", "https://api.myjson.com/bins/z79bt", true);
a.send();
};
</script>
UPDATE
Code from the comment:
var output = document.getElementById("output");
document.getElementById("btn1").onclick = function () {
var a = new XMLHttpRequest();
a.onreadystatechange = function () {
if(this.readyState == 4) {
var myObj = this.responseText;
}
console.log(a);
}
a.open("GET", "api.myjson.com/bins/z79bt";, true);
a.send();
};
Two issues:
you're missing a space in newXMLHttpRequest
you're not doing anything inside the state change callback
(third: you're also not populating the output div)
See the live example here:
var output = document.getElementById("output");
document.getElementById("btn1").onclick = function () {
var a = new XMLHttpRequest();
a.onreadystatechange = function () {
if(a.readyState === XMLHttpRequest.DONE && a.status === 200) {
console.log(a.responseText);
output.textContent = a.responseText;
}
}
a.open("GET", "https://api.myjson.com/bins/z79bt", true);
a.send();
};
<div id="btn1"> Update </div>
<div id="output"></div>
UPDATE
Fixed code from the comment:
var output = document.getElementById("output");
document.getElementById("btn1").onclick = function () {
var a = new XMLHttpRequest();
a.onreadystatechange = function () {
if(this.readyState == 4) {
var myObj = this.responseText;
console.log(myObj);
}
}
a.open("GET", "https://api.myjson.com/bins/z79bt", true);
a.send();
};
<div id="btn1"> Update </div>
<div id="output"></div>
I'm trying to use XML to get a list of cities from a website, then go through and add each of the cities to a datalist so that when I put in an input it will filter the cities in the list.
example of city list:
Aleppo
Alexandria
Alger
Almaty
Ankara
Anshan
Baghdad
Baku
Bandung
Bangalore
Bangkok
Barcelona
*[Each city name is on a new line]
current html:
<div id="namearea">
<h2>City Name:</h2>
<div>
<input id="citiesinput" list="cities">
<datalist id="cities"></datalist>
<button id="search">
Search
</button>
<span class="loading" id="loadingnames">
Loading...
</span>
</div>
</div>
current JS code:
window.onload = function() {
var request = new XMLHttpRequest();
request.onload = processCities;
request.open("GET", "url", true);
request.send();
};
Inspecting the page with Firebug shows that nothing is being added to the datalist, so I'm wondering what I'm doing wrong. I also tried using .responseText rather than .responeXML but it didn't make any difference.
[Fixed]
I changed the processCities() function to:
function processCities() {
var response = this.responseText;
var city = response.split("\n");
var options = "";
for(var i = 0; i < response.length; i++) {
options += "<option value='"+city[i]+"'>\n";
}
document.getElementById("cities").innerHTML = options;
}
This code seems to work.
Here is an example of making the request. If you really are getting XML, you'll have to parse it. It's better if you could get json.
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();