This question already has answers here:
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 5 years ago.
I've got a script which gets a bunch of information from an api and then lists it on my site. I then have a function, newLink(z) which is supposed to get the information from the new elements created and do stuff with it, to simplify it I'm just trying to console.log whatever it says below. Any number that I put into the brackets of the function, in this case 76561198008132325, has the last digit replaced with a 0 for whatever reason, resulting in the console logging '76561198008132320'. I've been scratching my head on this for a good half hour now and I literally can not figure out what is causing this.
var searchRequest = "https://api.roleplay.co.uk/v1/search/player?name=ant";
var searchData = "";
function success(data) {
for (i = 0; i < data['length']; i++) {
document.getElementById("searchResults").innerHTML += "<div class='result' onclick='newLink(76561198008132325)'>new link</div>";
}
}
function newLink(z) {
console.log(z);
}
$.ajax({
dataType: 'json',
url: searchRequest,
data: searchData,
success: success
});
<div class="results" id="searchResults">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
This is because you are passing the argument to the function as Number. Pass the argument value as string.
var searchRequest = "https://api.roleplay.co.uk/v1/search/player?name=ant";
var searchData = "";
function success(data) {
for (i = 0; i < data['length']; i++) {
document.getElementById("searchResults").innerHTML += "<div class='result' onclick='newLink(\"76561198008132325\")'>new link</div>";
}
}
function newLink(z) {
console.log(z);
}
$.ajax({
dataType: 'json',
url: searchRequest,
data: searchData,
success: success
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="results" id="searchResults">
</div>
Related
I need to make an AJAX request to API to get the word for a hangman game. Also struggling, on reading the word length and displaying it with placeholders. I referenced this link enter link description here , but am still stuck.
//function to get the word from the API using AJAX
jQuery.extend({
getValues: function(url) {
var result = null;
$.ajax({
url: url,
type: 'get',
dataType: 'xml',
async: false,
success: function(data) {
result = data;
}
});
return result;
}
});
//accessing global variable (word)
var results = $.getValues("https://hangman-api.lively.software");
for (var i < 0; i < word.length; i++) {
results[i] = "_";
}
Hopefully my snippet can help you in some ways. have a nice day!
$(function(){
$.ajax({
url: "https://hangman-api.lively.software/",
type: 'get',
success: function(data) {
//how to access word
console.log(data.word)
//how to create placeholders
placeHolder = " _ ";
placeHolders = placeHolder.repeat(data.word.length)
//how to print place holder
$(".placeHolder").text(placeHolders)
}
});
})
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
Placeholders : <span class="placeHolder"></span>
</body>
</html>
Each time data returns from the PHP file, it seems like the json object are doubled is some way!? When I run the script for the first time I get 5 rows which is the same amount of rows in the table. But the second time, I get the result twice! What have I done wrong in my script?
function readData() {
$.ajax({
url: "read.php",
type: "POST",
dataType: "json",
data: {
input: 1
},
cache: false,
success: function(data) {
var html = "";
for (i = 0; i < data.length; i++) {
html += "<tr><td>" + data[i].text + "</td></tr>";
}
$(".contentList table").append(html);
},
});
}
Try changing
$(".contentList table").append(html);
to
$(".contentList table").html(html);
.append() will just append more results to the end of the content inside the tag, while .html() will completely replace the content.
i am calling an ajax and output api response in textbox. I want count total number of data sets received(counteri) and display it each time i click a button. For example if i click the button first time i want to an alert display counteri=20 and next time i click button it display counteri=40 and... counteri=60.
Currently my code keeps showing 20 each time and not adding the values. could any one tell me how to fix this.Thanks
<script>
var maxnumId = null;
var counteri= null;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......"),
success: function(data) {
maxnumId = data.pagination.next_num_id;
for (var i = 0; i < 100; i++) {
$(".galaxy").append("<div class='galaxy-placeholder'><a target='_blank' href='" + data.data[i].link +"'><img class='galaxy-image' src='" + ok.images.standard_resolution.url +"' /></a></div>");
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
//alert('www!'+i);
counteri=i;
}
}
});
counteri=counteri+counteri;
alert('counteri is now: ' + counteri);
}
</script>
<body>
<br>
<center>
<div id="myDiv"></div>
<div class="galaxy"></div>
<button id="mango" onclick="callApi()">Load More</button>
</html>
EDIT:
Adding this in start of success added up total number of records from ajax response
var num_records = Object.keys(data.data).length;
num_records2=num_records2+num_records;
alert('number of records:'+ num_records2);
and
var num_records2 =null; // outside function
Ajax are async calls.
Move the alert to just after the for. Not outside the success callback.
Looks like the problem is that you are setting counteri to the value of i instead of adding the value of i. Try this instead:
counteri += i;
Ajax calls are asynchronous. You should increment your counter on success, not outside of the ajax call. Something like this:
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
maxnumId = data.pagination.next_num_id;
for (var i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri=counteri+i;
alert('counteri is now: ' + counteri);
}
});
}
Considering that your ajax request is executed with success, to get what you want you need to declare the i variable before for ( ....) loop as is the follow script:
var counteri = 0;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
var i,
maxnumId = data.pagination.next_num_id;
for (i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri=counteri+i;
alert('counteri is now: ' + counteri);
}
});
}
Please ses here demo
EDIT
Also i have rechecked if the variable i is not declared before for(...) loop and works OK. So, the only fix is to remove counter=i from for(...) loop and to change the counteri=counteri+counteri; to counteri+=i;
Take in consideration that the ajax requests produce a number of different events that you can subscribe to. Depending of your needs you can combine this events to accomplish the desired behavior. The complete list of ajax events is explained here
EDIT2
After reading your comments, i see that you need the last value of i globally,
you need to add a second global variable too keep the sum of last i during all ajax requests.
To do this, id have added a minor change to answer:
var counteri = 0,
totali =0;
function callApi() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.somesite.com/......",
success: function(data) {
var i,
maxnumId = data.pagination.next_num_id;
for (i = 0; i < 100; i++) {
document.myform.outputtext.value = document.myform.outputtext.value+data.data[i].images.ok.url+'\n' ;
}
counteri = i;
totali = totali + i;
alert('totali is now: ' + totali );
}
});
}
JSFiddle demo
EDIT 3
After your last comment, you need to add in the API response the number of returned rows. For this, you need to change for (i = 0; i < 100; i++) { to something like this:
var num_records = data.num_rows;
for (i = 0; i < num_records ; i++) {
or, without adding the number of rows in response
var num_records = Object.keys(data.data).length;
for (i = 0; i < num_records ; i++) {
My ajax call is returning 27 results, and I need to split these results in to three equal parts, so 9 results for each sections, which are displayed below.
HTML:
<div id="content">
<section>
</section>
<section>
</section>
<section>
</section>
</div>
JS looks roughly like this. Currently, all of the 27 results are going inside of every sections. How do I define the method for each of my sections to take only 9 results inside of them?
var query = "http://ajaxcallfromservice&maxResults=27";
$.ajax({
url: query,
async: true,
dataType: "jsonp",
success: function (result) {
ajax.parseJSONP(result);
}
});
var ajax = {
parseJSONP : function(result) {
$.each(result.items, function(i, row) {
$('section').append('<h2'+ row.stuffWhatINeed +'</h2>');
});
}
}
Any advice would be greatly appreciated.
You'll need to append to the correct section. Assuming you want the first 9 in the first section, etc...
var ajax = {
parseJSONP : function(result) {
var sections = $('section');
var perSection = Math.ceil(result.items.length / sections.length); // will be 9
$.each(result.items, function(i, row) {
var secNo = Math.floor(i / perSection); // 0 for 0..8, 1 for 9..17, 2 for 18..26
sections[secNo].append('<h2>'+ row.stuffWhatINeed +'</h2>');
});
}
}
I've got two divs on my page
<div id="1"></div>
<div id="2"></div>
That I'm trying to dynamically fill with the following php call.
<script>
var queries = ["SELECT * from table1", "SELECT * from table2"]
for (var i = 0; i < queries.length; i++) {
$.ajax({
url: "querySQL.php",
type: "GET",
cache: false,
data: {query: queries[i]},
success: function(data) {
$("#" + i).html(data);
}
});
}
</script>
It looks like it's looping through the queries properly, however it 'erases' the first one and when I view the page, only the results of the second query remain. What am I doing wrong?
Notwithstanding the warnings about exposing a raw SQL interface in your API, the problem you have is that i in the callback once the AJAX call completes doesn't have the same value it did when you initiated the call.
The easiest solution is to use $.each or Array#forEach instead of a for loop, and use the index parameter that is then correctly bound to the current value in the callback:
$.each(queries, function(i, query) {
$.ajax({
url: "querySQL.php",
type: "GET",
cache: false,
data: { query: query },
success: function(data) {
$("#" + (i + 1)).html(data); // NB: i starts at 0, not 1
}
});
});
This will work
var queries = ["SELECT * from table1", "SELECT * from table2"];
function callAjax(i){
$.ajax({
url: "querySQL.php",
type: "GET",
cache: false,
data: {query: queries[i]},
success: function(data) {
console.log(i)
$("#" + (i+1).html(data);
}
});
}
for (var i = 0; i < queries.length; i++) {
callAjax(i)
}
It looks that you have only 2 results. The problem here is your var i. it starts with i=0 and ends in i=1. So only div $("#" + 0).html(data) and $("#" + 1).html(data).
To fix this start with
i=1; i <= queries.length; i++
i guess you need to send only one request on page load.And in your php file that is ajax url,you need to execute the both queries one by one and then populate data in the div in the same file.and just return all data.On ajax success,you just populate a div with returned data.
I would set the datatype to application/json, so the answer can be a json object, not only text/html. I would return the following parameters from the php as a json via json_encode, something like this:
{firstResult:{divToUse: "#1", dataToFill: "#1 content"},
secondResult:{divToUse: "#2", dataToFill: "#2 content"},
....
}
I hope it helps.