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.
Related
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 have a JS script doing multiple AJAX requests. First I'm requesting a product by ID and then I'm requesting every single variant of this product. I can't do any form of backend coding since the environment I'm working in is closed.
My requests works fine, but right now I'm appending every single variant to a div, and my client don't really like this, so I was thinking is it possible to load all data into a variable and then fade in the parent div of all variants at the very end?
My script looks like this:
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
variants.find('.variant').fadeIn(300);
}
});
});
}
});
Some fast and dirty solution, but idea and concept of solution is clear. It is bad solution, but works for you in your case when you have no access to backend code.
var all_load_interval;
var is_all_data_ready = false;
var all_data_count = 0;
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
var data_count = $(data).find('Combinations Combination').length;
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
// make div with class variant hidden
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
// count every variant
all_data_count += 1
if (all_data_count == data_count) {
// when all data got and created, lets trigger our interval - all_load_interval
is_all_data_ready = true;
}
}
});
});
}
all_load_interval = setInterval(function() {
// Check does all data load every second
if (is_all_data_ready) {
// show all div.variant
variants.find('.variant').fadeIn(300);
clearInterval(all_load_interval);
}
}, 1000);
});
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++) {
I am pulling in data through ajax to populate a facebook-like wall type application (or a twitter wall).
But I'm getting undefined when i try to access the first li- if anyone can spot my obvious mistake it would be appreciated
var get_venues = function(){
$.ajax({
type: "GET",
url: '<?=base_url()?>wall/start_to_grab/',
dataType: "JSON",
success: function(data) {
var sel = $("#wall");
sel.empty();
for (var i=0; i < data.length; i++) {
sel.append('<li id="'+data[i].post_id +'"> ' + data[i].title + '</li>');
}
}
});
//start_poll($('ul#wall li:first').attr('id'));
alert($("ul#wall li:first").attr("id")); // returns undefined
};
The code returns undefined even when i can see the element on the page.
That is the way AJAX works (asynchronously, as the name suggests). The alert is executed before the AJAX request has returned a response, so no li elements have been appended.
Move the alert inside the AJAX success event handler. Alternatively, you could make the AJAX request synchronous, but that's almost always not what you want.
Your mistake is trying to access the results of an asynchronous request before the asynchronous request has completed. Simply put, when you attempt to alert your ID, the async request hasn't yet completed and therefore hasn't appended the li. The solution is to call a function within the async request that alerts your ID:
var get_venues = function() {
$.ajax({
type: "GET",
url: '<?=base_url()?>wall/start_to_grab/',
dataType: "JSON",
success: function(data) {
var sel = $("#wall");
sel.empty();
for (var i = 0; i < data.length; i++) {
sel.append('<li id="' + data[i].post_id + '"> ' + data[i].title + '</li>');
// Request complete, call handler to alert ID
HandleResponse()
}
}
});
};
function HandleResponse() {
alert($("ul#wall li:first").attr("id")); // returns undefined
}
I have an ajax call which will return a set<E>. I need to process this set from the JavaScript function from which I call this ajax.
<script type="text/javascript">
function mySr(id){
$.ajax({
type: 'POST',
url: '../controller/action',
data: 'id=' + id,
success: function(data) {
var length= data.length
var size = data.size
alert(data[0]+'----'+length+'--'+size+'----'+data)
},
error: function () {
alert('error')
}
});
</script>
This is the way i used,
The alert will display like this
["37",
"40","80","90"]----22--undefined----[
I understood the data is clearly reached in the script but i don't know how to iterate through it.
How to iterate here?
How to get the length?
How to get each elements?
You need to parse the data. Try putting data = $.parseJSON(data); after the line success: function(data) {
See http://api.jquery.com/jQuery.parseJSON/ for more details.