First, I think my title isn't very clear and very representative of what I want to achieve, but I couldn't make it clearer ...
Ok so I have a Leaderboard, created from this ajax call:
$.ajax({
url: '/handler',
dataType: 'json',
success: function(data) {
var tb = document.getElementById('Leaderboard');
while(tb.rows.length > 1) {
tb.deleteRow(1);
};
var keys = Object.keys(data);
for( key of keys) {
var username = data[key].username;
var score = data[key].score;
var row = $('<tr id = "row' + tb.rows.length + '"><td>' + username + '</td><td>' + score + '</td></tr>');
$('#Leaderboard').append(row);
if(tb.rows.length > 11){
tb.deleteRow(tb.rows.length -1);
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('Error: ' + textStatus + ' - ' + errorThrown);
}
});
So as you can see in the Leaderboard, when clicking on a username, it opens a new page with the result of a GET request (/leaderboard/:username). My question is how can I skin this page, or even better load an html file in this page, but while keeping accessible the result of the GET request to use it inside?
That may not be clear, and that's maybe a reason why my title is not really fitting ... But anyway if you have some ideas i'll take them !!
Thanks
Related
I'm working with an API that includes validating a phone number and its information. Its works in the console log but will not display on screen itself.
in the (#info).html is suppose to be shown on screen but keeps returing as undeclared, been doing my best to change the wording without the use of dashes but hasn't helped.
Does anyone know what went wrong?
Thank you!
$.ajax({
type: "POST",
url: "https://neutrinoapi-phone-validate.p.mashape.com/phone-validate",
data: { "country-code": country, number: number },
success: function(data){ // if code works in console
console.log( data );
$('#info').html('international-number: ' + data.country + '<br>international-calling-code: ' + data.callingcode + '<br>localNumber: ' + data.localNumber + '<br>countryCode: ' + data.countryCode + '<br>is-Mobile: ' + data.mobile + '<br>type: ' + data.type); // show results on screen
}, // found a way to display code without dashes
error: function(jqXHR,textStatus){; // if code fails
console.log( jqXHR );
console.log( textStatus );
},
beforeSend: function(xhr){ // check for access key before
xhr.setRequestHeader( 'X-Mashape-Key', 'OnHOGDfyMLmshCe0o3CtIU6L4DDZp1sukFtjsn9LynwSBQbznL' );
xhr.setRequestHeader( 'Accept', 'application/json' );
xhr.setRequestHeader( 'Content-Type','application/x-www-form-urlencoded' );
}
});
});
});
There are a number of ways to solve this issue. One includes using [] to access the property names that have dashes in them like so: data['country-code'].
But I noticed you've tried to access some properties that don't exist in the data. You can over come that by using a generic loop like so:
let output = '';
for (item in data) {
output += item + ':' + data[item] + '<br>';
}
That simply builds up a string of each data element's name followed by its value and a <br> tag. Here it is in code:
let country = 'us';
let number = '8881231234';
$.ajax({
type: "POST",
url: "https://neutrinoapi-phone-validate.p.mashape.com/phone-validate",
data: {
"country-code": country,
number: number
},
success: function(data) { // if code works in console
let output = '';
for (item in data) {
output += item + ':' + data[item] + '<br>';
}
$('#info').html(output); // show results on screen
}, // found a way to display code without dashes
error: function(jqXHR, textStatus) {; // if code fails
console.log(jqXHR);
console.log(textStatus);
},
beforeSend: function(xhr) { // check for access key before
xhr.setRequestHeader('X-Mashape-Key', 'OnHOGDfyMLmshCe0o3CtIU6L4DDZp1sukFtjsn9LynwSBQbznL');
xhr.setRequestHeader('Accept', 'application/json');
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='info'></div>
I'm working on making an API call in PhoneGap. I wrote a function and calling it from a button click event, and I'm getting a response too, but I want to know how to display it. I have tried, but it's not working.
function getContactList() {
console.log("Entering getContactList()");
$.ajax({
url: "https://api.androidhive.info/contacts/",
dataType: "json",
cache: false,
error: function(xhr, ajaxOptions, thrownError) {
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success: function(json) {
console.log("====CONTACTLIST ---->", json);
$(json).find("contacts").each(function() {
var html = '<li>' + $(this).find("name").text() +
' ' + $(this).find("name").text() + '</li>';
$('#contacts').append(html);
});
}
});
}
You're receiving JSON string which is then automatically converted by jQuery to a JavaScript object, so you can interact with it directly and shouldn't convert it to a jQuery object like $(json). Change the code inside your success to this:
for (var i = 0; i < json.contacts.length; i++) {
var c = json.contacts[i];
var html = '<li>' + c.name + ' ' + c.email + '</li>';
$('#contacts').append(html);
}
Note: it seems that there is an error in your code, you're using the find("name") twice. I changed it to name & email, but you can use any property of the contacts that you're getting.
I have a GET ajax call as follows :
var changeUrl = "changePriority?newValue=" + targetValue + "&justification=" + justification
if (dataInfo == "row") {
changeUrl += "&id=" + id
}
changeUrl += "&executedConfigId=" + executedConfigId + "&currUser=" + currentUser + "&productName=" + productName + "&eventName=" + eventName + "&alertDetails=" + JSON.stringify(alertArray);
//if the selected signal is not null then we show the product names
$.ajax({
url: changeUrl,
type: "GET",
success: function (data) {
for (var index = 0; index < checkedRowList.length; index++) {
var row = checkedRowList[index]
signal.list_utils.change_priority(row, targetValue);
}
$('#change-priority-modal').modal('hide');
if (applicationName == "Signal Management") {
signal.list_utils.set_value(parent_row, 'dueIn', id, signal.list_utils.get_due_in, applicationName);
$(parentField).html(targetValue);
}
location.reload();
},
error: function (exception) {
console.log(exception);
}
});
The value of changeUrl as I get in my browser's developer console is :
http://localhost:8080/signal/singleCaseAlert/changePriority?newValue=Medium&justification=test%20justification%20first.&id=6816&executedConfigId=6704&currUser=15&productName=Wonder%20Product&eventName=1.Pyrexia&alertDetails=[{%22alertId%22:%226816%22,%22event%22:%221.Pyrexia%22,%22currentUser%22:%2215%22}]
But I get a 400 bad request status and a http header parse error in the backend. Can someone help me resolve this?
On your JSON.stringify(alertArray) you'll need to also encodeURI();
encodeURI(JSON.stringify(alertArray));
A better solution would be send your JSON in the body of a POST request if thats feasible within your design
Im trying to use Bing Translator...
Already Have a token (I think), but when try to get the translation, the same Error is always poping:
"ArgumentOutOfRangeException: 'to' must be a valid language\u000d\u000aParameter name: to : ID=5217.V2_Json.Translate.5FEAF805"
The next is the url that i am using, and I dont see where the error is...
https://api.microsofttranslator.com/V2/Ajax.svc/Translate?
&appId=Bearer%20http%3a%2f%2fschemas.xmlsoap.org%2fws%2f2005%2f05%2fidentity%2fclaims%2fnameidentifier=TranslateHelper000&http%3a%2f%2fschemas.microsoft.com%2faccesscontrolservice%2f2010%2f07%2fclaims%2fidentityprovider=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&Audience=http%3a%2f%2fapi.microsofttranslator.com&ExpiresOn=1439307776&Issuer=https%3a%2f%2fdatamarket.accesscontrol.windows.net%2f&HMACSHA256=xGQ7LMehBDHJLY2Xq7jN8PXOhRCYqs%2boUb2V4Ic4XLI%3d
&from=en
&to=pt
&text=Home
&oncomplete=mycallback
(pt is defined as language in translator... it doesn't work either with to=en...
My question are, if you could help me on this:
1. Is that a normal Token?
2. Is it is normal, what is wrong with code? (I dont have any more hair to take off...)
This is the code I use to send the url (mycallback isn't being called either):
$.ajax({
type: "POST",
url: 'getTranslatorToken',
contentType: "application/json; charset=utf-8",
dataType: "json"
}).done(function (token) {
var languageFrom = "en";
var languageTo = "pt";
var textToTranslate = "Home";
var strToken = token["access_token"];
var s = document.createElement("script");
//s.src = "http://api.microsofttranslator.com/V2/Ajax.svc/Translate?oncomplete=mycallback&appId=Bearer " + token + "&from=" + languageFrom + "&to=" + languageTo + "&text=" + $('#txtMsg').val();
s.src = "https://api.microsofttranslator.com/V2/Ajax.svc/Translate?&appId=Bearer " + strToken +
"&from=" + encodeURIComponent(languageFrom) +
"&to=" + encodeURIComponent(languageTo) +
"&text=" + encodeURIComponent(textToTranslate) +
"&oncomplete=mycallback";
document.getElementsByTagName("head")[0].appendChild(s);
console.log(s)
}).fail(function (xhr, ajaxOptions, thrownError) {
alert("Error:"+xhr.responseText);
console.log(xhr.responseText);
//$("#msg").text('Error');
});
Thank
This question is answered here (in C#):
How to translate specific content in website
Working example here (PHP): http://www.johndimm.com/FunWithSpeech/BingTranslator/
I'm experiencing a really weird behaviour. I call a function when I change to a page (jQuery Mobile event "pagebeforeshow") like so:
$("#library").on("pagebeforeshow", function(event){
player.loadFiles();
});
The function I call looks like this:
Player.prototype.loadFiles = function(dir) {
dir = dir == undefined ? 'file://~' : dir;
if(dir.indexOf(data.lastDir) != 0){
console.log("fired");
$("li.item").remove();
$.ajax({
url: 'http://' + data.ip + ":" + data.port + '/requests/browse.xml',
data: 'uri=' + encodeURIComponent(dir),
dataType: "xml",
success: function (data, status, jqXHR) {
if(dir.indexOf(data.lastDir) != 0){
var html = "";
$(data).find("element").each(function(){
html += '<li class="item">' + $(this).attr('name') + "</li>";
});
$("#filelist").append(html);
$(".item").addClass("ui-li ui-li-static ui-btn-up-a ui-first-child ui-last-child")
}
},
error: function (jqXHR, status, error) {
alert("fail")
}
});
data.lastDir = dir;
}
}
Now it works fine if I visit the page for the first time. It appends the listitems to the ul #filelist and sets the variables right. Now when I leave the page it adds them again. The "fired" is not shown in the console though. If I visit the page again, they aren't added again, but if I leave it again they are. I can't figure out, why it's behaving like this and would be thankful for any tips!
stiller_leser