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 )
Related
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
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();
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, ' ').replace(/\n/g, '<br>'));
$("#response").css('font-family', 'courier');
};
I am trying to get the json object from a dojo xhrGet call.
What I want is jsonobject = stuff;
I can see the json object in the console, but cannot access it!
var xhrargs = {
url: "/rest/url",
handleAs: "json",
preventCache : false,
load: function(json_results){
console.log(json_results);
store = json_results;
return dojo.toJson.json_results;
},
error: function(response, ioArgs) {
console.error(response);
console.error(response.stack);
}
};
var deferred = dojo.xhrGet(xhrargs);
console.log("Json is "+JSON.stringify(deferred));
The console.log part that shows the json_results is fine, exactly what I want.
The dojo.xhrXXX methods are asynchronous. This means that the lines following
var deferred = dojo.xhrGet(xhrargs);
Will continue to execute while the call to an external endpoint is processing. This means you need to use the promise API to tell a certain block of code to execute once the XHR request is complete:
var deferred = dojo.xhrGet(xhrargs);
deferred.then(function(result){
//this function executes when the deferred is resolved (complete)
console.log('result of xhr is ',result);
});
Due to the asynchronous nature of the request, for most intents and purposes that value doesn't exist outside the scope of the callback function. One way to structure your code around this is in multiple blocks. for example:
var xhrLoaded = function(results){
console.log('results = ',results);
store = results;
}
var performXhr = function(){
var xhrargs = {
url: "/rest/url",
handleAs: "json",
preventCache : false,
error: function(response, ioArgs) {
console.error(response);
console.error(response.stack);
}
};
var deferred = dojo.xhrGet(xhrargs);
deferred.then(xhrLoaded);
}
performXhr();
You can still access variables outside of the scope of the function (for example if store were defined globally).
try this
var xhrArgs = {
url:"MethodName.action?Id="+id,
handleAs: "json",
load: function(Data){
var values = Data;
var count = Object.keys(values).length // gives u all keys count in a json object. In mine it is 0,1,2,3
for (var i =0; i<count; i++){
var temp = values[i]; // values['name']
// do somthing ..
}
}
},
error: function(error){
alert(error);
}
}
dojo.xhrPost(xhrArgs);
Hello I have a JQuery/Ajax function as following:
$.ajax({
type : "POST",
url : "/posts/getids",
success: function(response){
console.log(response);
},
error: function() {
alert('An unexpected error has occurred! Please try later.');
}
});
In my cakePHP script I'm sending an array using the json_encode($array) function.
In firebug I get this result :
[{"Post":{"id":1}},{"Post":{"id":2}},{"Post":{"id":4}},{"Post":{"id":3}}]
So my question is How can I simply print only the ids like this : 1, 2, 3, 4
Thank you.
// Convert JSON to JavaScript array.
var dataFromServer = JSON.parse(response);
// Creating an array of id's.
var idArray = [];
// Moving data to "idArray".
for(i = 0; i < dataFromServer.length; i++){
idArray[i] = dataFromServer[i].Post.id;
}
// Checking the result.
console.log(idArray);
// [1, 2, 3, 4].