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?
Related
I'm a having problems using AJAX to have value on the client side to draw a graph in real time with flot.
I am using one of the code examples of the flot library: the realtime.
http://www.flotcharts.org/flot/examples/realtime/
The values of this example are generated locally on the client side using javascript. But i want values from the server side, so i have to reuse the example code using ajax.
var data = [],
totalPoints = 10;
var y;
function getRandomData() {
if (datagraph.length > 0)
datagraph = datagraph.slice(1);
// Do a random walk
while (datagraph.length < totalPoints) {
$.ajax({
url: 'request.php',
type: "POST",
dataType: "text",
cache: false,
success: function(data) {
y = data;
console.log("ajax: " + y);
},
});
datagraph.push(y);
}
// Zip the generated y values with the x values
var res = [];
for (var i = 0; i < datagraph.length; ++i) {
res.push([i, datagraph[i]])
}
return res;
}
I have to pass the returned value from the request.php to the variable y of the function getradomData() inside of javascript on the html code above.
Note: the request.php calls a function: getVoltage() that returns a value. I am echo that value on the request.php. plus, the console.log on success does not return anything.
Whats wrong on Ajax part?
Ricardo
edit:
redirect.php
<?php
include('database.php');
echo getVoltage();
?>
The function getVoltage return a value like 176, and its working. I can see the value if i echo the value. getVoltage() is a function that connect to a mysql database and read the most recent value of that database.
Edit: It's working properly now after transformed the echoes string into a int.
Collect data from page format.json.
In JS I have:
$('input[name="q"]').autoComplete({
source: function(term, response){
$.getJSON('/search.json', { q: term }, function(data){ response(data); });
}
});
For autocomplete I use this plugin.
What is responsible for the output?
I have in the autocomplete drop all the names. To fall out only need to apply. it is necessary to drop only those which coincide.
Is responsible for it .indexOf(term)? what to use?
The screen shows all the results (which have match and those who do not have a match). Need to see only those that have a match.
Being you're getting the data from a JSON file you'll have to do the filtering on the client side. The way that it would work with an actual AJAX request to a server, you'd do the filtering on the server to only return the data you need (that's why you send the query term as a parameter).
So you will need to change your code to look like this:
$('input[name="q"]').autoComplete({
source: function (term, response) {
$.getJSON('/search.json', function (data) {
term = term.toLowerCase();
var matches = [];
for (i = 0; i < data.length; i++)
if (~data[i].toLowerCase().indexOf(term)) matches.push(data[i]);
response(matches);
});
}
});
You may need to do something different depending on what your data structure looks like but I'm assuming it's an array of strings
EDIT
If you want to limit your matches you can do it in the for loop rather than in the last line, this will be better for performance as it won't have to loop around once you've got 5 matches
$('input[name="q"]').autoComplete({
source: function (term, response) {
$.getJSON('/search.json', function (data) {
term = term.toLowerCase();
var matches = [];
for (i = 0; i < data.length; i++)
if (~data[i].toLowerCase().indexOf(term) && matches.length == 4) {
matches.push(data[i]);
break;
}
response(matches);
});
}
});
Archive.org json doc: http://archive.org/help/json.php
I am using this url: https://archive.org/metadata/AhmedAlajmiTheCompleteHolyQuran
The json format is displayed in this order
036.mp3
016.mp3
However the actual order on the details page is
001.mp3
002.mp3
The details page: https://archive.org/details/AhmedAlajmiTheCompleteHolyQuran
How can i get the uploaders sorted order that is displayed in the details page. How come the json is sorted in a different format. I can sort the urls based on the numbers, but the file name will not always be by numbers.
This is what i have so far. It just gets the mp3 urls. BUT THE ORDER IS WRONG!
var urlJ = "https://archive.org/metadata/AhmedAlajmiTheCompleteHolyQuran";
function functionName() {
var url = "https://archive.org/metadata/AhmedAlajmiTheCompleteHolyQuran";
var details = "https://archive.org/download/AhmedAlajmiTheCompleteHolyQuran";
function jsonpCallback(response) {
//after success some staff
var files = response.files;
for(var i=0; i < files.length; i++){
if(files[i].source == "original"){
console.log(details + "/" + files[i].name);
}
}
console.log(response.files[0]);
}
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error.message);
},
success: jsonpCallback
});
return false;
}
functionName();
There's no way to sort it with the API provided, however the metadata provides one piece of data you can use to sort it yourself.
mtime - Unix-style timestamp of file
Therefore, you can just sort it with JavaScript (put this right after you pull response.files):
var files = response.files;
for (var i = files.length - 1; i >= 0; i--)
if (typeof files[i].mtime === 'undefined')
files.splice(i, 1);
files.sort(function(a, b) {
return a.mtime - b.mtime;
});
Also, if you're only pulling the files, you can just request only the files with:
https://archive.org/metadata/AhmedAlajmiTheCompleteHolyQuran/files
When I run the code:
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.
I have a page where I want to add couple of controls
when I click on 1st control, I want my javascript to open particular JSONpage, gram the content and then output the content in specific <DIV id="one">. Then, when I select some of the elements in div id="one", I want The JavaScript to connect to another JSON page and get another array of data from there.
My question - how do I do the JSON part?
In other words, how do I get JavaScript version of:
$dataSet = json_decode(file_get_contents($url), true);
I am new to JavaScript and this thing takes so much time!!
Got this working
function getDates() {
jQuery(function($) {
$.ajax( {
url : "jsonPage.php",
type : "GET",
success : function(data) {
// get the data string and convert it to a JSON object.
var jsonData = JSON.parse(data);
var date = new Array();
var i = -1;
$.each(jsonData, function(Idx, Value) {
$.each(Value, function(x, y) {
if(x == 'date')
{
i = i + 1;
date[i] = y;
}
});
});
//output my dates; [0] in this case
$("#testArea").html(date[0]);
}
});
});
}