Data download Ajax in Ajax - mysql

I'm catching data from Database with Ajax.
In the second Ajax request I try to put the variables from first Ajax request to the new DOM elements from second request but there the variables have same value from last array possition.
I have no idea why .
unfortunately I didn't find the information about that.
a simple example:
//Firt ajax request
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: "connect/get-fistinformations.php",
data: {
folder_type:folder_type
},
dataType: "json",
for(var first_key in json){
var info = json[first_key];
//If I put there some alert - alert('some_alert'); - the rest of the code works fine
//Catching Data with Json - working correctly
var folder_id = info[0];
var folder_name = info[1];
var folder_date = info[2];
folder_id;
//Second ajax request
$.ajax({
type: 'GET',
contentType: 'application/json; charset=utf-8',
url: 'connect/get-secondinformations.php',
data: {
folder_type:folder_type,
folder_id:folder_id
},
dataType: 'json',
success: function(json){
for(var s_key in json){
var second_info = json[s_key];
//Catching more data from other Data table - working correclty
var count = second_info[0];
var route = second_info[1];
var distance = second_info[2];
var price = second_info[3];
var price_per_km = +(price) / (+(route) + +(distance));
//Without the alert from the firt ajax request
//There inside new elements I try to put variable from first Ajax catching (folder_id, folder_name,folder_date)
//But every time when I add new elemets to DOM, these three variables have same value - from last arrray position
//For example folder_id = '50' | folder_name = 'Some folder name' | folder_date = '2020-07-04'
//New elements for DOM
if(count>0){
var full_line_folder = '<div class="full-line-folder folder">'+
'<i class="some-line"></i>'+
'<span class="folder-name">'+folder_name+'</span>'+
'<span class="folder-comment">Utworzono: '+folder_date+'<br />Pozycje: '+count+'<br />Dystans: '+route+'km<br />Stawka: '+price_per_km+' €/km<br />Puste kilometry: '+distance+'km</span>'+
'<input type="radio" name="folderid" value="'+folder_id+'" style="display:none;" checked/>'+
'</div>';
$(full_line_folder).appendTo(point);
}else{
var empty_line_folder = '<div class="empty-line-folder folder">'+
'<i class="empty-line"></i>'+
'<span class="folder-name">'+folder_name+'</span>'+
'<span class="folder-comment">Utworzono:'+folder_date+'<br />Pozycje: 0<br />Dystans: 0km<br />Stawka: 0 €/km<br />Puste kilometry: 0km</span>'+
'<input type="radio" name="folderid" value="'+folder_id +'" style="display:none;" checked/>'+
'</div>';
$(empty_line_folder).appendTo(point);
}
}
},
error: function(note){
alert('error');
}
});
}
},
error: function(note){
alert('error');
}
});

The problem is that your first loop proceeds to the next iteration before the data arrives for the ajax request it makes. Mostly, by the time your first ajax response arrives, the loop is already gone and any external variables you try access will have their last values.
There are many workarounds for this. I don't think discussion all that is the scope of this answer.
Your options:
Use closures correctly.
Serialize the requests by using async/await

Related

Using data in html from an API response

As a starter in html world, i would like to know and start using simple APIs to insert into my blog posts.
I tried to include as html values some simple API like: https://bitcoinfees.earn.com/api/v1/fees/recommended and I used examples given here: Display Json data in HTML table using javascript and some others more like: http://jsfiddle.net/sEwM6/258/
$.ajax({
url: '/echo/json/', //Change this path to your JSON file.
type: "post",
dataType: "json",
//Remove the "data" attribute, relevant to this example, but isn't necessary in deployment.
data: {
json: JSON.stringify([
{
id: 1,
firstName: "Peter",
lastName: "Jhons"},
{
id: 2,
firstName: "David",
lastName: "Bowie"}
]),
delay: 3
},
success: function(data, textStatus, jqXHR) {
drawTable(data);
}
});
function drawTable(data) {
var rows = [];
for (var i = 0; i < data.length; i++) {
rows.push(drawRow(data[i]));
}
$("#personDataTable").append(rows);
}
function drawRow(rowData) {
var row = $("<tr />")
row.append($("<td>" + rowData.id + "</td>"));
row.append($("<td>" + rowData.firstName + "</td>"));
row.append($("<td>" + rowData.lastName + "</td>"));
return row;
}
but the result is always blank.
Please, can you give me some hint to can use that API and insert that numbers values for "fastestFee","halfHourFee","hourFee" as html values?
Thank you all!
Welcome to the html world. You are certainly right in assuming that data from APIs is a great way to make your websites more dynamic.
There is an example on W3 Schools on how to handle a http request. I think this is a good place to start https://www.w3schools.com/xml/xml_http.asp. You create a http object that does some sort of data fetching. In this example it is done with the xhttp.send(). At the same time you have a listener that monitors if the onreadystatechange property of the xhttp has changed. And if that change is status 200 (success) then perform some actions.
Here is my JSfiddle with example from your API
http://jsfiddle.net/zvqr6cxp/
Typically these actions would be to structure the returned data and then do something with the data, like show them in a table.
The example shows the native html xhttp object in use with an event listener. Typically as you learn more about this you would probably start using a framework such as jquery or Angular that can handle http requests smoother, keyword here is callback functions.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//In this example, I used your API link..first I would do is turn the JSON into a JS object
myObject = JSON.parse(xhttp.responseText)
document.getElementById("fast").innerHTML = myObject.fastestFee
document.getElementById("half").innerHTML = myObject.halfHourFee
document.getElementById("hour").innerHTML = myObject.hourFee
}
};
xhttp.open("GET", "https://bitcoinfees.earn.com/api/v1/fees/recommended", true);
xhttp.send();

How to use post from script?

Ths script generates a number:
function updateDue() {
var kmold1 = parseInt(<?php echo $km; ?>);
var kmnew1 = parseInt(document.getElementById("kminput").value);
var tot = kmnew1 - kmold1;
document.getElementById("kmtot").innerHTML = tot;
document.getElementById("kmnew").innerHTML = kmnew1;
document.getElementById("kmold").innerHTML = kmold;
}
The number is displayed on a webpage with this code:
Diff in Km: <span name="kmtot" id="kmtot" value=""></span><br>
This is part of an form that is used to post to an other file.
How can I send the output of id="kmtot" to the next php file?
I have tried:
Diff in Km: <span name="kmtot" id="kmtot" value=""></span><br>
Not working.
<input type="hidden" name="kmtot" id="kmtot">
If I add this, the number of id="kmtot" is not displayed on the webpage, and is not transfered.
Any hints or solutions?
If you are using jQuery, use this code:
$.ajax({
url: 'your-php-file.php',
method: 'post',
data: {
'kmtot': $('#kmtot').val(),
},
success: function(data) {
console.log(data);
}
})
In your-php-file.php, $_POST['kmtot'] will return the value of your element with the ID kmtot.
If you are not using jQuery, you could use Fetch API.

Trying to display ajax response in html

I am trying to display some ajax response that i receive from a controller each time i scroll at the bottom of the page.
if($(window).scrollTop() == $(document).height() - $(window).height()){
load++;
$.ajax({
type: 'POST',
url: 'get-response',
dataType: 'json',
data: {
"load" : load,
"key" : key
},
success: function(response){
var out = "";
var i;
for(i=0;i<response.length;i++){
out += response[i];
}
document.getElementById("response").innerHTML = out;
}
});
}
The response i get is in JSON format and looks like this :
I am not sure how to traverse the result and display it in html appending each time the results are returned. Can anyone help me with what else i can write in this section to get the results displayed ?
success: function(response){
var out = "";
var i;
for(i=0;i<response.length;i++){
out += response[i];
}
document.getElementById("response").innerHTML = out;
}
Try this, I have added table implementation, you can change into either div
var out = "<table>";
var i;
for(i=0;i<response.length;i++){
out +='<tr>';
out +='<td>'+response[i].brand_name+'</td>';
out +='<td>'+response[i].product_name+'</td>';
out +='<td>'+response[i].selling_price+'</td>';
out +='<td>'+response[i].mark_price+'</td>';
out +='</tr>';
out += response[i];
}
out += "</table>";
If you have no Problem by displaying the objects in json, you just have to write
JSON.stringify(response[i])
Or you could use another for loop
for(var x: response[i]){...}
This should 'pretty-print' it with the space indentation, suitable for viewing in HTML:
success: function(response){
$("#response").html(JSON.stringify(response, null, '&nbsp').replace(/\n/g, '<br>'));
$("#response").css('font-family', 'courier');
};

How to Write public function for Fill DropDownList

i Want write public function for Fill DropDownlist. and when programer want fill DropDownlist Call this method and set parametrs. i write this code
function FillDropDownlist(url,dataPas,selector,indexValue,indexText) {
$.ajax({
cache: false,
contentType: 'application/json; charset=utf-8',
url: url,
data:{dataPas},
success: function (data) {
var rows = data.rows;
var drpTransportType = $(selector);
var strOption = '<option value=0>...Select.....</option>';
$(selector+" option").remove();
if (data.rows.length >= 0) {
for (var i = 0, l = rows.length; i < l; i++) {
var ri = rows[i];
strOption += '<option value="' + ri.cell[indexValue] + '">' + ri.cell[indexText] + '</option>';
}
drpTransportType.append(strOption);
}
},
dataType: 'json'
});
}
and for call i write this code
FillDropDownlist("JQGridHandler.ashx", "ActionPage:'TransportType',Action:'FillDrop'", "#Select1", 0, 1);
but this code not work, and get Error
Error: FillDropDownlist is not defined
i think this line have error
data:{dataPas},
please help me for complete this function, thanks all
Couple of things: (1) use camelCase naming convention for JavaScript function names. (2) Make sure the function is evaluated before you call it. So if it's in a different js file, make sure that is included before the one that calls the function. (3) Change data:{dataPas} to data: dataPas (I think you misspelled "pass" but anyway). Then your dataPas object should be in javascript object notation like dataPas = {foo: "foo", bar: "bar"};
If dataPas is a native JavaScript object then pass dataPas as data:JSON.stringify(dataPas)
P.S: On an un-related sidenote you can omit dataType: 'json' and contentType just needs to be contentType: 'application/json' ( Link here )

How would I send a POST Request via Ajax?

I have a php page, Post.php it recieves the POST's Action, and that has two functions. Insert, and Update.Now how would I go about posting INSERT with this Ajax code. The code posts update fine but is doesnt post insert at all.
$(document).ready(function(){
//global vars var inputUser =
$("#nick"); var inputMessage =
$("#message"); var loading =
$("#loading"); var messageList =
$(".content > ul"); //functions
function updateShoutbox(){ //just
for the fade effect
messageList.hide();
loading.fadeIn(); //send the post to shoutbox.php
$.ajax({ type:
"POST", url: "Shoutbox.php", data:
"action=update",complete:
function(data){
loading.fadeOut();
messageList.html(data.responseText);
messageList.fadeIn(2000); } }); }
function checkForm(){
if(inputUser.attr("value") &&
inputMessage.attr("value"))return
true; else return false; }
//Load for the first time the
shoutbox data updateShoutbox();
//on submit event
$("#form").submit(function(){
if(checkForm()){ var nick =
inputUser.attr("value"); var
message = inputMessage.attr("value");
//we deactivate submit button while
sending $("#send").attr({
disabled:true, value:"Sending..." });
$("#send").blur(); //send the
post to shoutbox.php $.ajax({
type: "POST", url: "Shoutbox.php", data: "action=insert&nick=" + nick +
"&message=" + message,
complete: function(data){
messageList.html(data.responseText);
updateShoutbox();
//reactivate the send button
$("#send").attr({ disabled:false, value:"Shout it!" });
}
}); } else alert("Please fill all fields!"); //we prevent the
refresh of the page after submitting
the form return false; }); });*emphasized text*
List item
Your second call to $.ajax uses type: "GET" whereas the first uses type: "POST". Try switching the second one to "POST".