I've got the following code block within a larger javascript file. It uses an API to get the strCategoryID value and returns a list of three document names with appropriate links. works fine except that I need to sort the documents by date of input. I have a stored procedure in the SQL database that gives me what I need but I'm not sure how to make that call and populate the loop with the sorted documents. I'm modifying someone else's code and am pretty new to ajax.
var list = "<ul style=\"list-style: none; text-indent: -1.2em;\" class=\"news-list\" id=\"news-" + strCategoryID + "\">";
$.ajax({
type: "POST",
async: false,
data: strParams,
url: "/Utilities/AJAXUtilities.aspx",
success: function(msg){
msg = $.createXMLDocument(msg);
var li_count = 0;
$(msg).find('CONTENT_SEARCH').each(function(){
if ($(this).find("CNT_AVAILABLE").text() == "T") {
var title = $(this).find("CNT_TITLE").text();
var trimtitle = title.substring(0,39);
list = list.concat("<li>" + trimtitle + "...</li><hr>");
li_count = li_count+1;
if (li_count == 3) {
return false;
}
}
});
}
});
list = list.concat("</ul>");
list = list.concat("<br />View previous news releases>>");
$("#newscatlist").append(list);
return list;
I think that if you are not very familiar with AJAX your easiest solution will be to modify AJAXUtilities.aspx to return the records order by what you need, in that way you don't have to deal with AJAX and/or Javascript.
Related
I've been trying to do this, but I was only able to get the data populated inside the select of HTML.
2 Questions.
Q1.
I was able to get the JSON data using AJAX from an API. (using AJAX because I learned that it doesn't need the browser to refresh to fetch new data):
$(document).ready(function() {
getDataJson();
});
function getDataJson(ajaxurl) {
$.ajax({
method: "GET",
url: "https://corona.lmao.ninja/v2/jhucsse",
datatype: "json",
success: onSuccess,
error: onError
});
}
Next I tried to populate the select in my HTML on OnSuccess:
function onSuccess(jsonReturn) {
$("#dropdown").empty();
//console.log(jsonReturn);
let dropdown = $('#dropdown');
dropdown.empty();
dropdown.append('<option selected="true" disabled>Choose Country</option>');
dropdown.prop('selectedIndex', 0);
// Populate dropdown with list of countries
$.each(jsonReturn, function (key, entry) {
dropdown.append($('<option></option>').attr('value', entry.data).text(entry.data));
});
var $dropdown = $('#dropdown'),
$objView = $('#objView'),
$docFragment = $(document.createDocumentFragment());
for (var prop in jsonReturn) {
$('<option/>', {
val: prop,
text: prop
}).appendTo($docFragment);
}
$dropdown.append($docFragment);
$dropdown.on('change', function() {
var objString = JSON.stringify(jsonReturn[$dropdown.val()]);
objString = objString.replace(/[\{\}\[\]\"]*/ig, ''); // Remove unwanted chars
objString = objString.replace(/\,/ig, '<br/>'); // Replace commas with new lines (i.e. br tags)
$objView.html(objString);
});
$dropdown.trigger('change');
}
//if JSON fails
function onError() {
$("#dropdown").html("i failed.");
}
And It worked. But then I tried to do the next step I wanted to do which is to when I click on the name of a country it should display the rest of its JSON data with names and their values.
How to display JSON data on click with JavaScript
this isn't the exact, but close enough but it's a very different(difficult?for me) solution that I couldn't understand.
Currently my dropdown looks like this:
JSFIDDLE
Now I'm intended to do this Populate HTML Table with Certain Items from a JSON Array
but with all the other JSON data like this for each country How to display JSON data on click with JavaScript
How can I resolve the rest of the scripting?
Q2. How to reduce the AJAX fetching lag?
There's a little bit of a lag/slow that I've noticed even with fewer data. Or is it just normal?
Answer for Q1
First of all, I prepare these 3 variables to make it simpler.
let jsonResponseContainer = []
let dropdown = $("#dropdown")
let objView = $("#objView")
Then prepare this when the document is ready
$(document).ready(function() {
// Initiate everything
getDataJson();
// Move dropdown change to standalone
dropdown.on('change', function() {
let chosenResponse = JSON.stringify(jsonResponseContainer[$("#dropdown").val()])
// Remove unwanted chars
chosenResponse = chosenResponse.replace(/[\{\}\[\]\"]*/ig, '');
chosenResponse = chosenResponse.replace(/\,/ig, '<br/>');
// Change objView
objView.html(chosenResponse)
})
});
Your ajax is
function getDataJson(ajaxurl) {
$.ajax({
method: "GET",
url: "https://corona.lmao.ninja/v2/jhucsse",
datatype: "json",
success: onSuccess,
error: onError
});
}
I made a function just to populate the dropdown
function populateDropdown(index, data){
let newOption = "<option value=\"" + index + "\">" + data + "</option>"
dropdown.append(newOption)
}
Major changes I made
function onSuccess(jsonReturn) {
// Populate container with ajax return directly
jsonResponseContainer = jsonReturn
// Do what you need to do
dropdown.empty();
dropdown.append('<option selected="true" disabled>Choose Country</option>');
dropdown.prop('selectedIndex', 0);
// Populate dropdown with list of countries
$.each(jsonReturn, function (key, entry) {
populateDropdown(key, entry.country);
});
}
//if JSON fails
function onError() {
$("#objView").html("i failed.");
}
Notice that I copy jsonReturn to another variable just to make sure the data now can be accessed everywhere. Next is your on-change listener was put on a loop, I moved it out of the loop. Now, I make <option> with string (you may change it with fragment if you want). Pay attention I make the value with key (array key for jsonReturn which is the same for jsonResponseContainer). When the on-change listener is evoked, it just needs to retrieve from the array to <pre>.
Answer for Q2
I don't understand about it, I suppose it is not your fault.
note: I apologize if I was using the wrong grammar.
i am trying to populate an asp.net dropdownlist returned as JSON from my webservice.
WebService
[WebMethod(EnableSession = true)]
public string GetActiveDepositAccountsForLoanAlert(string customerId)
{
var data = BusinessLayer.SMS.SmsSetup.GetActiveDepositAccountsForLoanAlert(customerId.ToLong());
var json = new JavaScriptSerializer().Serialize(data);
return json;
}
The webservice returns
[{"AccountNumber":"NS-0000092"},{"AccountNumber":"6MR-0000002"},{"AccountNumber":"1YFD-0000007"}]
I am calling the data from ajax call and populating it to my dropdownlist.
Ajax call
function GetActiveDepositAccounts(customerrId) {
var customerId = $('#CustomerIdHiddenField').val();
var data = { customerId: $('#CustomerIdHiddenField').val() };
var json_data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "/WebMethods/Misc.asmx/GetActiveDepositAccountsForLoanAlert",
data: json_data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(r) {
var depositRadioList = $("[id*=DepositAccountDropDownList]");
depositRadioList.empty().append('<option selected="selected" value="0">Please select</option>');
for (var i = 0; i < r.d.length; i++) {
depositRadioList.append('<option>' + r.d[i] + '</option>');
}
}
The data gets populated in json.In my dropdown i only want the accountnumber as
NS-0000092.I am getting the whole json in my dropdown.i have searched and seen lots of question with this Json parse thing in here.But couldnt get hold of this.It isnt that i didnt tried,I am newbie,so before marking this as duplicate,please for once have a look at the code.Thank you.
I can't shake the feeling that because your GetActiveDepositAccountsForLoanAlert is returning a string and not an object, r.d is being seen as a string. Try one of 2 things. Either:
Change your method signature to return data type and don't use the JavaScriptSerializer. or,
In your OnSuccess function, add var data = JSON.parse(r.d) and use that variable in your for loop.
Single Object Returned
If by "whole json", you mean you are getting a single {"AccountNumber":"6MR-0000002"} per option -- try outputting the value of the target AccountNumber object (e.g. r.d[i].AccountNumber or r.d[i]["AccountNumber"]).
Modified Function
var depositRadioList = $("[id*=DepositAccountDropDownList]");
depositRadioList.empty().append('<option selected="selected" value="0">Please select</option>');
for (var i = 0; i < r.d.length; i++) {
depositRadioList.append('<option>' + r.d[i].AccountNumber + '</option>');
}
Array of Objects Returned
If the result per option is an entire AccountNumber array of objects, you'll need to loop through your r object until you get to the list of Account Number objects.
Take a look at my Example JS Fiddle. There is probably a cleaner way to do this, but to present the principle, I've laid out nested loops to get you into the list of object values that you need for your <select></select>.
I'm using the JQuery $.each() method, but you can use the for loop. I recommend just using one or the other for consistency. If the data set is really large, for loops have better performance.
I have an ajax request that gets called several times based on the number of request objects in an array. The order in which these objects are in inside of the array is important, and needs to be reflected in a dynamically generated list in that same order. When the server sends back each response I update a <ul> as shown below.
$.ajax({
type: 'POST',
url: baseServiceURL + 'report/',
processData: false,
dataType: 'json',
contentType: 'application/json',
data: payload,
crossDomain: true,
})
.done(function (response) {
updateUI(response);
})
.fail(function (jqXHR, textStatus) {
// handle failure
});
var updateUI = function (response) {
// Update the drop-down list
$('#dropdown').append('<li><a class="dd-option" data-value="' + response.ReportName + '" data-path="' + response.ReturnURL + '" href="#">' + response.ReportName + '</a></li>');
// do more stuf...
};
How can I dynamically build the list in such a way to where the response display in the proper order? One thing I have done is add a order param to the request who's value is the index of the request object in the array. My thought is my service can send that value back in the response so the javascript can act on it.
EDIT: The question here is asking basically the same thing except rather than using a getJSON command and appending divs I'm using a post and appending <li> elements.
There are two possible strategies here.
Update your UI immediately upon receiving response and then re-render if a new value is received
Wait until all ajax replies have finished and then render your UI
For (1) you should just keep a running total of all items
var $dropdown = $('#dropdown');
var renderDropdown = function(reports) {
//use lodash or underscore.js here cause implementing this manually is annoying
var sortedSelections = _.sortBy(reports, 'order');
var htmlPerItem = sortedSelections.map(function(item) {
return '<li><a ..... </li>';
});
$dropdown.html(htmlPerItem.join(''));
}
var reportSelections = [];
payloads.map(function(payload) {
$.ajax({ ... })
.then(function(response) {
reportSelections.push(response);
renderDropdown(reportSelections);
})
})
for (2) you can use jquery $.when
var gettingResults = payloads.map(function(payload) {
return $.ajax({ .... });
});
$.when(gettingResults).then(function() {
//the first arg will be response1, the second response2, etc
var reportSelections = _.sortBy(arguments, 'order');
renderDropdown(reportSelections);
});
Note in (1) you render once per item but get an updating view as items come in. In (2) you render only once but have to wait until all loading is complete.
Of course a variation of (1) is that you don't re-render anything, but merely insert items into the correct location as they are loaded. That's going to be more difficult to debug and more code so I leave it as an exercise for the reader (use jquery's $.fn.data to store the original item with the element).
I'm currently working on a project for university. we are trying to use the twitter api but we are having some trouble with the query. I want to search a complete string, therefore I need to put my string in quote sings.( like "I'm seraching for this whole sting")
the problem is that the command I use to get the array from twitter somehow encodes the whole string but I need the quote sings to not be encoded. I hope you guys understand my problem. in addition i'll post my js code.
JS CODE: first I tryed a json command but it didnt work. afterwards I tryed ajax but I ran into the same problem. I don't get a response when I use quote signs in my query.
$( document ).ready(function()
{
console.log("ready");
// div mit id unique1 - bei klick mache onClick1
$('a#unique1').bind('click', onClick1);
});
function onClick1(elem)
{
var inputString = $("#SearchInput").val();
var EncodedString = encodeURI(inputString);
console.log('test' + inputString);
var endNode = 'search/tweets.json?q=hate%20' + EncodedString + '&result_type=mixed&count=200';
/*
$.getJSON('twitter/twitter-proxy.php?url='+encodeURIComponent(endNode),
*/
$.ajax({
type: "GET",
url: 'twitter/twitter-proxy.php?url='+encodeURIComponent(endNode),
data: " ",
success: function(twitterResponse){
var respStr = "start";
console.log(twitterResponse);
console.log(twitterResponse.statuses);
for(var i = 0; i < twitterResponse.statuses.length; i++)
{
$('.container .apiCall ol').append('<li>'+ twitterResponse.statuses[i].created_at + '</br>' + twitterResponse.statuses[i].text.toLowerCase() + '</li>');
respStr = respStr + twitterResponse.statuses[i].created_at + twitterResponse.statuses[i].text.toLowerCase();
}
}
});
/*
function(twitterResponse)
{
var respStr = "start";
console.log(twitterResponse);
console.log(twitterResponse.statuses);
for(var i = 0; i < twitterResponse.statuses.length; i++)
{
$('.container .apiCall ol').append('<li>'+ twitterResponse.statuses[i].created_at + '</br>' + twitterResponse.statuses[i].text.toLowerCase() + '</li>');
respStr = respStr + twitterResponse.statuses[i].created_at + twitterResponse.statuses[i].text.toLowerCase();
}
*/
/*
// respSgtr = " ";
// write tweets to file
$.post("writer.php", { fileString:respStr},
function(response)
{
//alert("Data Loaded: " + data);
});
});*/
}
Your approach is flawed.
jQuery does all the parameter encoding for you. Don't interfere, just pass an object which contains keys and values. Do not build URLs from individual bits of string.
Important security consideration: Don't build a server-side proxy script that accepts any arbitrary URL. Doing this is plain stupid.
Instead change your PHP script to accept a set of operation verbs, like "search", which are hard-wired to the correct URL on the server side.
I recommend using $.get() and $.post() over $.ajax(), for the benefit of cleaner code.
Further, use $.each() rather than a regular for loop. The resulting code will be cleaner and easier to read.
Avoid building HTML from bits of string. Especially if the bits of string come from a completely untrustworthy source, like Twitter. Use jQuery's capabilities and the DOM to build HTML safely. (read about XSS vulnerabilities if you're not sure why I bring this up)
Suggested solution (appendText() jQuery plugin taken from here):
$.fn.appendText = function(text) {
return this.each(function() {
var textNode = document.createTextNode(text);
$(this).append(textNode);
});
};
$(function () {
$('a#unique1').on('click', function (event) {
$.get('twitter/twitter-proxy.php', {
operation: 'search',
params: {
q: 'hate ' + $("#SearchInput").val(),
result_type: 'mixed',
count: 200
}
}).done(function (twitterResponse) {
$.each(twitterResponse.statuses, function (index, status) {
$("<li>")
.appendText(status.created_at)
.append("<br>")
.appendText(status.text.toLowerCase())
.appendTo(".container .apiCall ol");
});
});
});
});
Hi everyone i'm trying to display some random images while not loading (refresh) page
So how can i display random images on a page without refreshing the page ?
<script type="text/javascript">
$(function () {
$.ajax({
type: "get", url: "Home/Oku", data: {}, dataType: "json",
success: function (data) {
for (var i = 0; i < data.length; i++) {
var newFirmDiv= $(' <img src="../../banner_image/' + data[i] + '" width="154px" height="108px"/>');
$(".firmShowCase").append(newFirmDiv);
}
}
});
});
</script>
Here is my action method that provides return values an array
public ActionResult Oku()
{
var query = from table in db.news select table.news_image_name;
return Json(query, JsonRequestBehavior.AllowGet);
}
Here is result as you can see below
2nd Try:
function for min and max
(http://www.naden.de/blog/zufallszahlen-in-javascript-mit-mathrandom)
function getRandom(min, max) {
if(min > max) {
return -1;
}
if(min == max) {
return min;
}
var r;
do {
r = Math.random();
}
while(r == 1.0);
return min + parseInt(r * (max-min+1));
}
And Your Code
for (var i = 0; i < data.length; i++) {
randomIndex = getRandom(0, data.length-1);
var newFirmDiv= $(' <img src="../../banner_image/' + data[randomIndex] + '"width="154px" height="108px"/>');
$(".firmShowCase").append(newFirmDiv);
}
If you want to keep the random order...
...you have to save it like in a new array, afterwards you could save it via ajax in a database or a temp file. And the top of your current file you would have to check if there is an existing temp file; if it shall be bound to a user, you could generate a random key (like with time) save it in a session variable and name the tmp file or the data in the database with the same random key... so far my ideas, if it's that what you are looking for. Of cause it would be easier to do this on the server side right from the start.
First Answer:
(The question was not really clear - if something does not work and so on...)
First of all data is not returned as an array, but an object. But i think you do not understand the parameters of the ajax function very well.
In the url parameter should be the script (for example getImages.php) which shall be executed. So there you should collect the images, parse them to jason and print them, in that way it will be returned as data.
In the parameter data you can pass some params to the skript, which you can get by decoding them in php.
I just chose PHP for example.
If I am wrong and "Home/Oku" leads to some script you might show us what it does?