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>');
});
}
}
Related
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>
I have one html page which contains a jquery function.
<script>
function loadCustomers() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getCustomers',
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td><a href="clientSiteInfo.html?client=">'+id+'</td><td>'+value+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadCustomers;
</script>
I have linked another html page for each row. When each rows populated, the id values has to be passed to the clientSiteInfo.html page.
In the clientSiteInfo.html page i have another jquery function similar to above.
<script>
function loadSites() {
$.ajax({
type: 'GET',
url: 'http://localhost:8080/cache/getSite?clientName='+${param.client},
dataType: 'json',
success: function(data) {
var rows = [];
$.each(data,function(id,value) {
rows.push('<tr><td>'+id+'</td><td>'+value.machine+'</td><td>'+value.state+'</td></tr>');
});
$('table').append(rows.join(''));
}
});
};
window.onload = loadSites;
</script>
in the GET url I try to read client parameter. But it is not passing from my initial page.
What Im doing wrong here? I look for simple solution
jQuery doesn't have a native way to read the url parameters. However, javascript works just fine:
function getParameterByName(name) {
const match = RegExp(`[?&]${name}=([^&]*)`).exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' ') );
}
In your code you would just call it as getParameterByName('client')
I had to integrate search engine in website. But there is already a list of data on first page.
my question is how this data should hide or remove when making a new search request. !https://1drv.ms/f/s!AsW4Pb3Y55Qjb34OtQI7qQotLzc
In mention image let I enter something to search and upon hitting enter how the present elements should be removed.
I mean after getting successful response how can I remove the already present list of data on website.
I tried to find resources but no clue. If someone give me some directions, I will be thankful. I am completely new to ajax and jquery.
Code start :
$("#search").keyup(function(){
clearInterval(timer);
timer = setInterval(update, 50);
});
function update() {
clearInterval(timer);
var myInput = $("#search").val();
if ((myInput != "") && (myInput != searchText)) {
$.ajax({
url: '/search-start',
type: 'GET',
data: {"data": myInput},
success: function (response) {
console.log(response);
},
error: function () {
console.log("Error.")
}
Assumptions
<div id="data-container"> <!-- main container which holds your data list -->
<ul id="data-list"> <!-- list of data here -->
<li>Data 1</li>
<li>Data 2</li>
<!--- ...other datas --->
</ul>
</div>
Then
$.ajax({
url: '/search-start',
type: 'GET',
data: {"data": myInput},
success: function (response) {
if(/**response contains correct data**/){
$('#data-list').html(''); // empty the data list
//prepare the data list view like
var newDataList = "";
$.each(response['data'], function(key, val){
newDatalist += "<li>"+val+"</li>";
});
// then append your new data to the data list
$('#data-list').html(newDataList);
}
},
error: function () {
console.log("Error.")
}
});
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.
I tried to create a jquery plugIn that load multiple feed rss (they are flexible can be 1 or 2 or 3 ect...), for create an html that show the news feed loaded. My target is having the possibility to load multiple rss feed (xml) and display them by html. When I tried seem that the callback is overwrite,I received 2 results but equal.
Example:
(function($){
$.fn.getFeed = function(Obj){
var
arrOpt = Obj.arrayOptions,
arrOptLng = arrOpt.length;
for(var i = 0; i < arrOptLng; i++){
var
index = i,
Opt = arrOpt[i],
feedUrl = Opt.feed,
sucFnc = Opt.callback,
$cnt = this;
console.log(index);
// here:
// 0
// 1
$.ajax({
url:feedUrl,
dataType: "jsonp",
success:function(data){
sucFnc(data,$cnt,Opt,index);
},
error:function(){
$cnt.html('error');
}
});
}
}
})(jQuery);
function feedManipulation(){
console.log(index)
// here:
// 1
// 1
}
/* DOM LOADED */
$(function(){
$('.news').getFeed({ // Activation getFeed
arrayOptions:[{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
},{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
}]
});
});
Ciao, I wrote this question and I created the solution so I would explain.
In this code I removed the cyclo for and I create a function that contain the ajax call.
The first time that I trigger the ajax function I pass an argument to the ajax function with inside an object that I used to set the plugIn (lock on the bottom) whereas my ajax function is itself calls, before sending the same object to the ajax function I change some information like "Opt.index" creating in this way a ajax cyclo. Is it really usefull ;) use it.
(function($){
$.fn.getFeed = function(Obj){
// Options object
Opt = new Object();
Opt.index = 0;
Opt.$cnt = this;
Opt.arrOpts = Obj.arrayOptions;
Opt.arrOptLng = Opt.arrOpts.length;
Opt.arrOpt = Opt.arrOpts[Opt.index];
Opt.feedUrl = Opt.arrOpts[Opt.index].feedUrl;
// ajax call
cycloAjax(Opt);
}
/* ajax cyclo */
function cycloAjax(Obj){
$.ajax({
url: Obj.feedUrl,
dataType: "jsonp",
success:function(data){
feedManipulation(data,Obj.$cnt,Obj);
if(Obj.index < Obj.arrOptLng - 1){
Obj.index++;
Obj.arrOpt = Obj.arrOpts[Obj.index];
Obj.feedUrl = Obj.arrOpts[Obj.index].feedUrl;
cycloAjax(Obj);
}
else{
completeLoadFeeds(Obj.$cnt,Obj);
}
},
error:function(){
Obj.$cnt.html('<p>error</p>');
}
});
}
.
.
.
})(jQuery);
/* DOM LOADED */
$(function(){
$('.news').getFeed({ // Activation getFeed
arrayOptions:[{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
},{
feed:'http://feed',
callback:feedManipulation,
imgDefault:'http://img',
nArtc:1
}]
});
});