how to get JSON array value from internet - arrays

I want to get value of an array from JSON code in internet. from this URL : http://olympics.clearlytech.com/api/v1/medals/
after that, I want to display that array of my script without rewrite that JSON code on this URL http://olympics.clearlytech.com/api/v1/medals/
so, what code (script) that I can use?
for example, I want to display value from this array
var JSONs = {
example:['one','two','three']
};
the code is
document.write(JSONs.example[0]);
but if I want get the array value from the internet, what code/script that I can use?

Using jQuery, here is an example. In the success event, turn the resulting json text into a json object. You could also set the content type as json so you wouldn't have to call the JSON.parse().
$.ajax({
url: "http://olympics.clearlytech.com/api/v1/medals/",
success: function(data) {
var json = JSON.parse(data);
}
});
This is another way of doing the same i hope you asked how to parse through each value just try this in jsfiddle
$(document).ready(function(){
alert("here");
$.getJSON("http://olympics.clearlytech.com/api/v1/medals/",function(data){
$.each(data,function(key,value){
alert(data[key].country_name);
alert(data[key].rank);
console.log(data[key].rank));
});
});
});

public void handleResponse(String response)
{
// display("Response:"+response);
if(!response.equalsIgnoreCase(""))
{
JSONObject jso;
try {
jso = new JSONObject(response);
String status = jso.getString("status");
int valid=jso.getInt("valid");
// display("Welcome : "+UName);
if(valid>0)
{
if( status.equalsIgnoreCase("") || status==null || status.equalsIgnoreCase("Failed"))
{
invalid.setText("Invalid password");
//reset();
pwd.setText("");
}
else
{
//display(status);
intObj=new Intent(MainActivity.this,Design_Activity.class);
intObj.putExtra("Username", mUname);
startActivity(intObj);
MainActivity.this.finish();
}
}
else
{
invalid.setText("Invalid userid");
uname.setText("");
}
}
catch (JSONException e1) {
// TODO Auto-generated catch block
Log.e(TAG, e1.getLocalizedMessage(), e1);
}
catch(Exception e)
{
Log.e(TAG, e.getLocalizedMessage(), e);
}
}
else
{
display("Could not able to reach Server!");
}
}

Althought you want us to do everything, thats why your question went negative. Anyhow this is how you can do it in plain ajax
function getData(){
// Initialize the Ajax request
var xhr=new XMLHttpRequest();
xhr.open('get', 'http://olympics.clearlytech.com/api/v1/medals/');
// Track the state changes of the request
xhr.onreadystatechange=function(){
// Ready state 4 means the request is done
if(xhr.readyState === 4){
// 200 is a successful return
if(xhr.status === 200){
alert(xhr.responseText); // 'This is the returned text.'
}else{
alert('Error: '+xhr.status); // An error occurred during the request
}
}
}
// Send the request to send-ajax-data.php
xhr.send(null);
}

Related

How to return data from web api controller using angularjs?

Hi I am developing one web api with angularjs application. I am doing file upload module. I am facing problem in returning object once file upload is finished.
Below is my api code to save file related data to database and if it is succsfull I am returning object.
NCT_FileUpload obj = new NCT_FileUpload();
obj.file_path = uploadPath;
obj.user_id =9;
entityObject.NCT_FileUpload.Add(obj);
int result = entityObject.SaveChanges();
if (result == 1)
{
return Request.CreateResponse<NCT_FileUpload>(HttpStatusCode.OK, obj);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "1");
}
This is my angularjs code.
$scope.uploadFiles = function () {
$scope.uploading = true;
uploadService.uploadFiles($scope)
// then() called when uploadFiles gets back
.then(function (data) {
// promise fulfilled
$scope.uploading = false;
if (data === '') {
alert("Done!!!")
$scope.formdata = new FormData();
$scope.data = [];
$scope.countFiles = '';
$scope.$apply;
} else {
alert("Shit, What happended up there!!! " + data);
}
}, function (error) {
$scope.uploading = false;
//Server Error
alert("Shit2, What happended up there!!! " + error);
}
);
};
Below is my service code in angularjs
if (typeof response.data === 'string') {
return response.data;
} else {
return $q.reject(response.data);
}
Here i want to check with object and not as string.
I am able to save data in server, If i put below code in api controller i am able to display done. But i am returning object so my data will not be empty. Currently my error function is executing. I want to handle object returned from api in success function. Is there any way to do this? Any help would be appreciated. Thank you.
return new HttpResponseMessage(HttpStatusCode.OK) ;
I think the problem here is the generic parameter. Change this:
return Request.CreateResponse<NCT_FileUpload>(HttpStatusCode.OK, obj);
To this:
return Request.CreateResponse(HttpStatusCode.OK, obj);

Get an image of a vbhtml view as a byte array and save it to an oracle database

I need help on an mvc application in vb.net. In general terms I need to receive an image through the view and get it to work on the controller. I need to do this to convert the image to a byte array and save it to an oracle database. So my idea is to get the image and in the controller to convert it to a byte array or maybe there is some way to get the image already as a byte array and pass that array to the controller to save it to the database.
something like this its my View :
<div class="span11">
<div class="span4" id="depnac">
#Html.LabelFor(Function(m) m.DepNacPER)
#Html.DropDownListFor(Function(m) m.DepNacPER, Model.DepNacPER, New With {.class = "form-control"})
</div>
and this is my Model :
<Display(Name:="Region of birth")>
<Required(ErrorMessage:="you must select a option")>
Property DepNacPER As SelectList
I'm working on an ASP.NET Core app right now that uploads images. The image comes through to the controller via the request as a Stream. I'm then creating an Image object from that Stream but you could just read the data from it directly. That said, you might want to try to create an Image object to confirm that the data does represent a valid image.
Here's some relevant code from the view's script:
function uploadImage()
{
// This is a file upload control in a hidden div.
var image = $("#imageFile");
if (image[0].files.length > 0)
{
var formData = new FormData();
formData.append(image[0].files[0].name, image[0].files[0]);
var xhr = new XMLHttpRequest();
xhr.open("POST", "#Url.Content("~/events/uploadimage")");
xhr.send(formData);
xhr.onreadystatechange = function ()
{
if (xhr.readyState === 4 && xhr.status === 200)
{
var response = JSON.parse(xhr.responseText);
if (response.saveSuccessful)
{
// ...
} else
{
window.location.replace("#Url.Content("~/error")");
}
}
}
xhr.onerror = function(err, result)
{
alert("Error: " + err.responseText);
}
}
}
I'm in the process of replacing that code with some jQuery that does the heavy lifting but haven't got that far yet.
Here's some relevant code from the action:
[HttpPost]
public IActionResult UploadImage()
{
var requestForm = Request.Form;
StringValues tempImageFileNames;
string tempImageFileName = null;
string imageUrl = null;
var saveSuccessful = true;
var requestFiles = requestForm.Files;
if (requestFiles.Count > 0)
{
// A file has been uploaded.
var file = requestFiles[0];
using (var stream = file.OpenReadStream())
{
try
{
using (var originalImage = System.Drawing.Image.FromStream(stream))
{
// Do whatever you like with the Image here.
}
}
catch (Exception)
{
saveSuccessful = false;
}
}
}
if (saveSuccessful)
{
return Json(new {saveSuccessful, tempImageFileName, imageUrl});
}
else
{
return Json(new {saveSuccessful});
}
}
Sorry, it didn't occur to me at first that you're after VB code and this is C#. Hopefully you can still get the idea and I'll take the hit if someone dislikes the answer.

Cancel http.get request and revert data

I have a page where we upload a .csv file to the database. we call a web api method that reads the file and insert the data into a table. When we upload the file a popup appears with a cancel button. What I am trying to do is to cancel the file upload process if user press the cancel button. For doing that I have created a promise and calling it on click of cancel button and it is cancelling the http request but the problem that I am facing is the data that is already imported into the database stays there. For instance if we have 100 rows in the file and by the time I press cancel button 50 rows were already inserted to the database those rows stays there. I need some help in figuring out how to revert the data that is already inserted in the table. Here is the code that I am working with:
var requestPromise = $http({
method: 'POST',
url: mpCONFIG.apiServiceBaseUri + 'import/fileImport',
data: formData,
transformRequest: angular.identity,
timeout: canceller.promise,
headers: {
'Content-Type': undefined
}
});
return requestPromise.success(function(resp, status) {
file.progress = undefined;
if (typeof resp != 'undefined' && resp != null && resp.length > 0) {
$rootScope.caseFileId = resp[0];
listImportRows(1, resp[0]);
}
})
.error(function(data, status) {
$scope.waitOnLoadingFile(false);
file.progress = undefined;
});
};
$rootScope.cancelLoadingFile = function() {
canceller.resolve("User Cancelled");
$scope.waitOnLoadingFile(false);
$window.location.reload();
}
Edit: What I found out that it is not cancelling the request at all. The initial impression of stopping at half way was not correct and was due to some other issue. So when I press the cancel button cancelLoadinfFile is called but seems like canceller.resolve is not cancelling the request. Below is the web api method.
[Route("fileImport")]
[HttpPost]
public System.Threading.Tasks.Task<IHttpActionResult> UploadImage()
{
try
{
IEnumerable<Models.mlsp.Firm> firms = (from cs in User.Firms(db)
select cs);
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
}
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(Properties.Settings.Default.UploadTempFolder);
string user = RequestContext.Principal.Identity.Name;
System.Threading.Tasks.Task<IHttpActionResult> task = request.Content.ReadAsMultipartAsync(provider).
ContinueWith<IHttpActionResult>(o =>
{
System.Net.HttpStatusCode resultStatus = HttpStatusCode.OK;
int?[] result = new int?[provider.FileData.Count];
try
{
for (int i = 0; i < provider.FileData.Count; i++)
{
result[i] = Logic.mlsp.Case.LoadFromFile(User, db, provider.FileData[i].LocalFileName, firms);
}
return ResponseMessage(new HttpResponseMessage()
{
StatusCode = resultStatus,
Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(result))
});
}
catch (Exception ex)
{
Helpers.LogHelper.LogError(ex);
throw;
}
}
);
return task;
}
catch (Exception ex)
{
Helpers.LogHelper.LogError(ex);
throw;
}
}
According to this link, http://www.davepaquette.com/archive/2015/07/19/cancelling-long-running-queries-in-asp-net-mvc-and-web-api.aspx, you can add a CancellationToken parameter to the controller method. When the client cancels the request the token will be canceled as well. You need to pass this token along to the task or monitor the IsCancellationRequested property as necessary.

How to iterate an array before responding to user using async

I have a the following code that currently works
but...
I know it is not elegant and can be done much more efficiently.
What I am trying to do is take an array of emails, search if they exist in a corresponding db with a particular templateName, and for those that do not exist (i.e are 'new'), list them back on the returned page to the user. However, they end up waiting quite a while if there are a lot of emails to check.
This is the first time I'm using async and it may not actually be the best way to do this. Some of the below has been modified from what I am actually using currently to make it easier to read/follow.
Basically, from my handler, I call the following (where both emailArray and templateName are extracted from the request parameter passed in).
var newEmails = "";
async.eachSeries(emailArray, function(entry, cb) { // check each item in array (these are the potential new emails)
utils.emailAddressAndTemplateExists(entry.toString().toLowerCase(), templateName, function (err, emailExists, templateExists ) {
if (emailExists) {
if (templateExists) {
++existingCount;
} else if (emailExists && !templateExists) {
} else {
console.log('template does not exist');
}
} else {
++newCount;
newEmails = newEmails + entry + "</br>";
}
cb();
});
//cb();
}, function (err) {
if (err) { throw err; }
var content = utils.getHTMLHead() + newEmails + utils.getHTMLClose();
utils.writeHTMLPage(response, content);
});
The utils call does the following: (the writeHTMLPage simply adds the required html tags and sends back to response).
//checks for a single email address
var emailAddressExists = function(emailAddress, callback) {
if (emailAddressCollection == null) {
//console.log("it was null " + db_singleton + " " + dbName);
emailAddressCollection = db_singleton.collection(dbName);
}
emailAddressCollection.find( { "emailAddress" : emailAddress.toLowerCase() } ).toArray( function (err, docs) {
if (err) { console.err(err); }
if (docs.length == 0) {
callback(null, false, docs.EmailsSent);
} else {
doc = docs[0];
callback(null, true, doc.EmailsSent);
}
});
}
// check for email And template
var emailAddressAndTemplateExists = function (emailAddress, templateName, callback) {
emailAddressExists(emailAddress, function (err, returnVal, templates) {
if (returnVal) {
if (templates != null) {
callback (null, true, templates.hasOwnProperty(templateName)) // email exists, checking for templateName
} else {
callback (null, true, false); // email exists, no templates at all exist
}
} else {
callback (null, false, false); // email does not exist, templates must be false
}
});
}
//creates HTML formated respnse data
function writeHTMLPage(response, content) {
// if (err) { console.error(err); response.send("Error " + err); }
response.writeHead(200, {"Content-Type": "text/html"});
response.write(content);
response.end();
}
What are more elegant and efficient way to do this?
This looks like it's constructed according to how you'd normally see it. You can look into Promises with ES6 to get a better program flow:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
Basically, it lets you chain together functions. It's not too bad for what you're doing now, it might help out some, but if you have 4-5 callbacks nested together, that's when promises can be very helpful.
You'll just have to work through structuring your code differently to use Promises, but it'll make "callback hell" less of an issue.

Angular how to deal with unavailable URLs requested by $http.get or $http.jsonp, which are executed by $q.all()

I've the following code:
eventResourcesCall = $http.jsonp('https://apicall/to/serverA');
eventsDetailsCall = $http.get('https://apicall/to/serverB');
$q.all([eventResourcesCall, eventsDetailsCall]).then(function(values){
//process data manipulation and merging
});
The problem is that serverA and ServerB might not be available sometimes, and when one of those are unavailable, the data processing code stops and I get an error similar to the one described below:
GET https://apicall/to/serverA?jsonp=angular.callbacks._0 404 (Not Found)
Can any one point me to a documentation or describe on the answer how to properly deal with unavailable URL requested by $http and executed by $q.all()?
What I would like to be able to do is to get an indication that the URL is not accessible and then avoid the data processing code abortion.
Thanks!
I would use indirect promises:
var d1 = $q.defer(), d2 = $q.defer();
function NetworkError(reason) { this.reason = reason; }
eventResourcesCall = $http.jsonp('https://apicall/to/serverA').then(
function(response) {
d1.resolve(response);
},
function(err) {
d1.resolve(new NetworkError(err));
}
);
eventsDetailsCall = $http.get('https://apicall/to/serverB').then(
function(response) {
d2.resolve(response);
},
function(err) {
d2.resolve(new NetworkError(err));
}
);
$q.all([d1, d2]).then(function(values){
var eventResources = values[0], eventsDetails = values[1];
if( eventResources instanceof NetworkError ) {
// handle error
}
else {
// eventResources is good, use it
}
// and so on...
});
So the indirect promises are allways resolved and the all() succeeds. But the resolution value may be of the special NetworkError class which signals the actual error in this request.
This is definitely bulky, but could be improved with some utility methods, e.g.:
function makeIndirectPromise(httpPromise) {
var ret = $q.defer();
httpPromise.then(
function(response) {
ret.resolve(response);
},
function(err) {
ret.resolve(new NetworkError(err));
}
);
return ret.promise;
}
And the code above changes to:
function NetworkError(reason) { this.reason = reason; }
function makeIndirectPromise(httpPromise) { /* see above */ }
eventResourcesCall = makeIndirectPromise($http.jsonp('https://apicall/to/serverA'));
eventsDetailsCall = makeIndirectPromise($http.get('https://apicall/to/serverB'));
$q.all([eventResourcesCall, eventsDetailsCall]).then(function(values){
var eventResources = values[0], eventsDetails = values[1];
if( eventResources instanceof NetworkError ) {
// handle error
}
else {
// eventResources is good, use it
}
// and so on...
});
From Angular doc to $q: as $http returns a promise, you can catch promise rejection using either:
$q.all([eventResourcesCall, eventsDetailsCall]).then(function(values){
//process data manipulation and merging on Success
}).catch(function(errors){
//Deal with your $http errors
}).finally(function(data){
});
or
$q.all([eventResourcesCall, eventsDetailsCall]).then(function(values){
//process data manipulation and merging on Success
}, function(errors){
//Deal with your $http errors
});

Resources