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:
Related
I have written a function in PHP which takes product information and user's desired calories information from a database and puts all of the information in an array. Afterwards it's encoded in JSON. Then the PHP file is used in a Javascript .html file where it should take the information I just said about from the PHP file and outputs the linear program results. The problem is that the .html file with Javascript in it returns an error in the console and a white page (screenshot).
The PHP file output is shown in the screenshot. I took the output and pasted it in a JSON validator, which shows that it's valid, so I don't see the issue here.
Any suggestions?
PHP(part):
// Add the product data to the products array
$products[] = [
'name' => $productRow['product_name'],
'price' => $price,
'calories' => $energyRow['energy_value'],
'UserCalories' => $userCaloriesRow['calories'],
];
}
// Output the products array as a JSON string
header('Content-Type: application/json');
echo json_encode($products, JSON_UNESCAPED_UNICODE);
$mysql->close();
return $products;
}
fetchProductsFromDatabase();
?>
Javascript:
<script src="https://unpkg.com/javascript-lp-solver#0.4.24/prod/solver.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Initialize the products and calories arrays
var products = [];
var calories = 0;
// Make an AJAX request to the PHP script that fetches the products and user's desired calories from the database
$.ajax({
url: 'fetchProductsFromDatabase.php',
success: function(response) {
// The response is a JSON object, so we need to parse it to get the products array and user's desired calories
var data = JSON.parse(response);
products = data.products;
// Set up the linear programming problem
var lp = new LinearProgramming(0, LinearProgramming.MAXIMIZE);
// Set up the constraints
var caloriesConstraint = {};
for (var i = 0; i < products.length; i++) {
caloriesConstraint[i] = products[i]['calories'];
}
lp.addConstraint(caloriesConstraint, LinearProgramming.EQUAL, calories);
// Set up the objective function
var priceObjective = {};
for (var i = 0; i < products.length; i++) {
priceObjective[i] = products[i]['price'];
}
lp.setObjective(priceObjective);
// Solve the linear program
var result = lp.solve();
// Print the results
for (var i = 0; i < products.length; i++) {
console.log(products[i]['name'] + ': ' + result[i]);
}
console.log('Total cost: ' + lp.getObjectiveValue());
},
error: function(jqXHR, textStatus, errorThrown) {
// There was an error with the request
console.log(jqXHR.responseText); // Output the response from the server
console.log(textStatus); // Output the error type
console.log(errorThrown); // Output the exception object, if available
}
});
</script>
The parameter passed to the success callback in jQuery's ajax method has already been parsed. It is not the string of JSON returned by the PHP, it is the result of reading that string of JSON into an ordinary JS object.
In short, JSON.parse has already been run before it gets to your code.
So instead of this:
success: function(response) {
// The response is a JSON object, so we need to parse it to get the products array and user's desired calories
var data = JSON.parse(response);
products = data.products;
// ...
You just want this:
success: function(data) {
// The response data is an object, from which we can get the products array and user's desired calories
products = data.products;
// ...
The reason you get the error you do is that JSON.parse expects a string (a string of JSON data), but you're passing it an object (the one jQuery has passed you). JavaScript "helpfully" turns the object into the string '[Object object]', and passes it to JSON.parse.
you need to stringify the JSON before parsing, something like:
JSON.parse(JSON.stringify(response));
Best regards,
Help me with the detailed code, Because am new to this environment. My need is, I need to upload a image into a SharePoint Document library from the client side using REST API and also I want to retrieve the item which is there in the document Library and append it into a page. I trying this one as a SharePoint Hosted App.
I'm Using SharePoint Online;
We can use REST API an jQuery in SharePoint hosted add-in to achieve it, the following code for your reference.
'use strict';
var appWebUrl, hostWebUrl;
jQuery(document).ready(function () {
// Check for FileReader API (HTML5) support.
if (!window.FileReader) {
alert('This browser does not support the FileReader API.');
}
// Get the add-in web and host web URLs.
appWebUrl = decodeURIComponent(getQueryStringParameter("SPAppWebUrl"));
hostWebUrl = decodeURIComponent(getQueryStringParameter("SPHostUrl"));
});
// Upload the file.
// You can upload files up to 2 GB with the REST API.
function uploadFile() {
// Define the folder path for this example.
var serverRelativeUrlToFolder = '/shared documents';
// Get test values from the file input and text input page controls.
// The display name must be unique every time you run the example.
var fileInput = jQuery('#getFile');
var newName = jQuery('#displayName').val();
// Initiate method calls using jQuery promises.
// Get the local file as an array buffer.
var getFile = getFileBuffer();
getFile.done(function (arrayBuffer) {
// Add the file to the SharePoint folder.
var addFile = addFileToFolder(arrayBuffer);
addFile.done(function (file, status, xhr) {
// Get the list item that corresponds to the uploaded file.
var getItem = getListItem(file.d.ListItemAllFields.__deferred.uri);
getItem.done(function (listItem, status, xhr) {
// Change the display name and title of the list item.
var changeItem = updateListItem(listItem.d.__metadata);
changeItem.done(function (data, status, xhr) {
alert('file uploaded and updated');
});
changeItem.fail(onError);
});
getItem.fail(onError);
});
addFile.fail(onError);
});
getFile.fail(onError);
// Get the local file as an array buffer.
function getFileBuffer() {
var deferred = jQuery.Deferred();
var reader = new FileReader();
reader.onloadend = function (e) {
deferred.resolve(e.target.result);
}
reader.onerror = function (e) {
deferred.reject(e.target.error);
}
reader.readAsArrayBuffer(fileInput[0].files[0]);
return deferred.promise();
}
// Add the file to the file collection in the Shared Documents folder.
function addFileToFolder(arrayBuffer) {
// Get the file name from the file input control on the page.
var parts = fileInput[0].value.split('\\');
var fileName = parts[parts.length - 1];
// Construct the endpoint.
var fileCollectionEndpoint = String.format(
"{0}/_api/sp.appcontextsite(#target)/web/getfolderbyserverrelativeurl('{1}')/files" +
"/add(overwrite=true, url='{2}')?#target='{3}'",
appWebUrl, serverRelativeUrlToFolder, fileName, hostWebUrl);
// Send the request and return the response.
// This call returns the SharePoint file.
return jQuery.ajax({
url: fileCollectionEndpoint,
type: "POST",
data: arrayBuffer,
processData: false,
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"content-length": arrayBuffer.byteLength
}
});
}
// Get the list item that corresponds to the file by calling the file's ListItemAllFields property.
function getListItem(fileListItemUri) {
// Construct the endpoint.
// The list item URI uses the host web, but the cross-domain call is sent to the
// add-in web and specifies the host web as the context site.
fileListItemUri = fileListItemUri.replace(hostWebUrl, '{0}');
fileListItemUri = fileListItemUri.replace('_api/Web', '_api/sp.appcontextsite(#target)/web');
var listItemAllFieldsEndpoint = String.format(fileListItemUri + "?#target='{1}'",
appWebUrl, hostWebUrl);
// Send the request and return the response.
return jQuery.ajax({
url: listItemAllFieldsEndpoint,
type: "GET",
headers: { "accept": "application/json;odata=verbose" }
});
}
// Change the display name and title of the list item.
function updateListItem(itemMetadata) {
// Construct the endpoint.
// Specify the host web as the context site.
var listItemUri = itemMetadata.uri.replace('_api/Web', '_api/sp.appcontextsite(#target)/web');
var listItemEndpoint = String.format(listItemUri + "?#target='{0}'", hostWebUrl);
// Define the list item changes. Use the FileLeafRef property to change the display name.
// For simplicity, also use the name as the title.
// The example gets the list item type from the item's metadata, but you can also get it from the
// ListItemEntityTypeFullName property of the list.
var body = String.format("{{'__metadata':{{'type':'{0}'}},'FileLeafRef':'{1}','Title':'{2}'}}",
itemMetadata.type, newName, newName);
// Send the request and return the promise.
// This call does not return response content from the server.
return jQuery.ajax({
url: listItemEndpoint,
type: "POST",
data: body,
headers: {
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val(),
"content-type": "application/json;odata=verbose",
"content-length": body.length,
"IF-MATCH": itemMetadata.etag,
"X-HTTP-Method": "MERGE"
}
});
}
}
// Display error messages.
function onError(error) {
alert(error.responseText);
}
// Get parameters from the query string.
// For production purposes you may want to use a library to handle the query string.
function getQueryStringParameter(paramToRetrieve) {
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var singleParam = params[i].split("=");
if (singleParam[0] == paramToRetrieve) return singleParam[1];
}
}
Refer to: Upload a file by using the REST API and jQuery
We got a project for school were i need to create an mp3 album playlist using a premade PHP api using javascript or jquery only (Not allowed to use php).
I can enter the data using an ajax call.
I need to be able to enter more than one song with its url.
I managed to enter the data this way to the DB into a column named songs.:
[{"name":["song1","song2"],"url":["url1","url2"]}]
How do I loop through this using Javascript or jQuery and showing it as a list?
This is the ajax call I am using.
function getsongs(index, name, url){
$.ajax({
url: "api/playlist.php?type=songs&id=" + index,
method: 'GET',
data: {
"songs": [
{
"name": name,
"url": url
},
] },
success: function(response, playlist){
// Need to loop here?
},
error: function(xhr){
console.log('error')
console.log(xhr)
}
}); }
Thank you.
You can use "for" :
var arr = [{"name":["song1","song2"],"url":["url1","url2"]}];
var names = arr[0].name; // extract names from arr
var urls = arr[0].url; // extract urls from arr
for(var i=0; i< names.length && i < urls.length; i++){
console.log(names[i]);
console.log(urls[i]);
}
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);
});
}
});
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?