I'm trying to generate html content based on the presence of a specific key in the local storage. The code is as follows:
// Check if the user is signed in or not
if(localStorage.getItem("token") === null) {
document.getElementById("main").innerHTML = document.getElementById("welcomeview").innerHTML;
} else {
document.getElementById("main").innerHTML = document.getElementById("profileview").innerHTML;
}
The profile view is always shown even though there is no token key set in the local storage:
localStorage
Storage { token: "undefined", length: 1 }
Why?
Edit:
The token is being set with the response value of an AJAX request:
function sign_in() {
var uri, method, formId, $form, form_data;
uri = location.protocol + '//' + location.host + "/sign_in";
method = "POST";
formId = "#signin_form_id";
$form = $(formId);
form_data = get_form_data($form);
// Set-up ajax call
var request = {
url: uri,
type: method,
contentType: "application/json",
accepts: "application/json",
cache: false,
dataType: 'json',
data: form_data
};
// Make the request
$.ajax(request).done(function(data) { // Handle the response
// Attributes are retrieved as object.attribute_name
// alert(obj.count);
if(data.successSignIn === false) {
// Login failed we show the welcome page
alert(data.message);
document.getElementById("main").innerHTML = document.getElementById("welcomeview").innerHTML;
} else {
// Login succeeded. We load the user's info, his messages and also a form in which he can type messages
// Save the token received from the server. Could also be stored as a cookie
localStorage.setItem('token', data.token);
// Go to the home page
go_home();
}
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
);
location.reload();
}
Edited: Try this for set item localStorage.setItem("token", typeof undefined === data.token ? undefined : data.token). It is avoided to be string "undefined".
I suggest that:
1) Replace to if(localStorage.getItem("token")) {...}
3) Also, you can do your example through ternary operator
var welcomeText = document.getElementById("welcomeview").innerHTML,
profileText = document.getElementById("profileview").innerHTML;
document.getElementById("main").innerHTML = (localStorage.getItem("token")) ? welcomeText : profileText
You'd never enter the if section as "undefined" === null is always false.
You'd want to check for if(localStorage.getItem("token") === "undefined") in your case.
Related
I am doing an API request with Upcloud's API server. I sent a request with postman, and it worked just fine, but when I use .ajax(), it returns a 401. I know that the problem isn't the user and pass.
function listIPS(){
var url = 'https://api.upcloud.com/1.2/servers';
function make_basic_auth(name) {
if(name === 'josh'){
var user = 'user';
var pass = 'pass';
}
if(name === 'malcolm'){
var user = 'user';
var pass = 'pass';
}
var tok = user + ':' + pass;
var hash = window.btoa(tok);
console.log("Basic " + hash);
return "Basic " + hash;
}
var auth = make_basic_auth('josh');
$.ajax({
type: "GET",
contentType: 'application/json',
url: "https://api.upcloud.com/1.2/account",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", auth)
},
success: function(data){
// console.log(data);
}
})
}
This is the error I am recieving:
OPTIONS https://api.upcloud.com/1.2/account 401 (Authorization Required)
Here is my AJAX code:
jQuery.ajax({url: url,
method: 'GET',
data: getParams,
/*success: function (json, textStatus, jqXHR) {
if(jQuery.active <= 1){
waitDialog.removeWaitDialog();
}
createProcessButtonEvent();
ajaxError = false;
returnFunction(jqXHR.responseJSON);
},*/
complete: function(jqXHR, textStatus, errorThrown) {
if(jQuery.active <= 1){
waitDialog.removeWaitDialog();
}
createProcessButtonEvent();
var response;
if (typeof jqXHR.responseJSON === 'object') {
response = jqXHR.responseJSON;
} else {
response = jqXHR.responseText;
}
if(response.errors.length == 1){ // jsonResults.message != ''
if(!warningMessage){ //hard coded for ad designer
jQuery('#alertMessageText').text(response.errors[0].message);
jQuery('#alertMessage').show();
jQuery('#waitDialog').jqmHide();
ajaxError = true;
return;
}
warningMessage.displayMessage(response.errors[0].message);
jQuery('.popup').modal('hide');
jQuery('.popup').not('.persist').remove();
}
if (response.errors.length > 1){
for(var n = 0; n < response.errors.length; n++){
if (response.errors[n].id == 1){ // 2005
window.location.href = '/login?destination=' + encodeURIComponent(window.location.pathname + window.location.search);
}
if (response.errors[n].id == 9500){
statusMessage.displayMessage(response.errors[n].message);
}
}
ajaxError = true;
//if(errorFunction){
// errorFunction(jsonResults);
//}
waitDialog.removeWaitDialog();
}
if (!ajaxError) {
returnFunction(jqXHR.responseJSON);
}
},
dataType: 'json',
contentType: 'application/json'
});
I tell it to go to http://127.0.0.1/api/parameter, where the parameter is an invalid resource. My API returns in a new tab:
{"errors":[{"id":3,"message":"GET route not defined for /api/parameter"}],data:{}}
I have it returning with a 500 status code because accessing an invalid resource is an error. When I call the actual AJAX, I get jqXHR.responseJSON is null, and jqXHR.responseText is ''.
I have tried using both success: and error: blocks, and tried the complete: because it seemed like my API was resolving the call after the error block had been called, as you can see with the comments.
So I get TypeError: response is null, because my response object is never populated, and the strangest thing is that my call to parameter?parameters=here is never available to inspect in the Network
Since I have control over the API, I changed this specific error to return with status code 501 Not Implemented, instead of 500, and it seems to work. It looks like this was a very unique edge case.
I have been using the following code to successfully read the contents of an external webpage as a string - I haven't used this program in a month or so but it has suddenly stopped working even though the code has not been changed. I suspect the YQL API has been updated but I couldn't find any documentation that I could understand on this. (I am a beginner at JS). If someone could point me to how to update my code it would be much appreciated!
Code:
function formSubmitted(raceID) {
if(raceID.length < 4 && raceID > 0){
savedRaceID = raceID;
raceUrl = "http://www.bbk-online.net/gpt/lap"+raceID+".htm";
jQuery.ajax = (function(_ajax){
var protocol = location.protocol,
hostname = location.hostname,
exRegex = RegExp(protocol + '//' + hostname),
YQL = 'http' + (/^https/.test(protocol)?'s':'') + '://query.yahooapis.com/v1/public/yql?callback=?',
query = 'select * from html where url="{URL}" and xpath="*"';
function isExternal(url) {
return !exRegex.test(url) && /:\/\//.test(url);
}
return function(o) {
var url = o.url;
if ( /get/i.test(o.type) && !/json/i.test(o.dataType) && isExternal(url) ) {
// Manipulate options so that JSONP-x request is made to YQL
o.url = YQL;
o.dataType = 'json';
o.data = {
q: query.replace(
'{URL}',
url + (o.data ?
(/\?/.test(url) ? '&' : '?') + jQuery.param(o.data)
: '')
),
format: 'xml'
};
// Since it's a JSONP request
// complete === success
if (!o.success && o.complete) {
o.success = o.complete;
delete o.complete;
}
o.success = (function(_success){
return function(data) {
if (_success) {
// Fake XHR callback.
_success.call(this, {
responseText: data.results[0].replace(/<script[^>]+?\/>|<script(.|\s)*?\/script>/gi, '')
//THE ERROR IS COMING FROM ABOVE - REPLACE IS BEING CALLED ON A NULL OBJECT??
//SUGGESTS NO DATA RETURNED?
}, 'success');
}
};
})(o.success);
}
return _ajax.apply(this, arguments);
};
})(jQuery.ajax);
$.ajax({
url: raceUrl,
type: 'GET',
success: function(res) {
processData(res.responseText);
}
});
}
else{
alert("Please enter a valid race number...");
}
}
I have highlighted where the error is coming from - it appears that the function is not returning any data?
OK so I'm working on a Facebook Group Feed that loads more results, but I'm having trouble building the initial query for it all to work.
In the first if statement below, you can see where I put the parts of the query into variables and then call the function, passing those variables. This all works fine...
if (response.status === 'connected') {
// Logged into your app and Facebook.
console.log('Welcome! Fetching your information.... ');
var path = '/',
method = 'POST',
params = {
batch: [
{method : 'GET', name : 'user', relative_url : '/me?fields=id,name,picture'},
{method: 'GET', name : 'post-ids', relative_url: '/group-id/feed?fields=fields{with field expansion}',omit_response_on_success : false}
]
};
loadFeed(path, method, params);
}
The funciton below is where I'm having trouble. The first time the function is called, I need to put those three variables together into one, and call it with FB.api. You can see the function here:
function loadFeed(path, method, params) {
console.log('------------------');
console.log(path + ', ' + method + ', ' + params);
if(path != 'undefined') {
if(method != 'undefined') {
if(params != 'undefined') { var query = '{\'' + path + '\', \'' + method + '\', ' + params + '}'; }
}
else { var query = path; }
}
$('#load-more').css('display', 'hidden');
FB.api(query, function (response) {
console.log(response);
// first time page loads, response[0] is the login, and response[1] is the feed
// each time after that, response[0] is the feed
if(response.length > 1) {
var membody = JSON.parse(response[0].body),
feed = JSON.parse(response[1].body);
} else {
var feed = JSON.parse(response);
}
if(feed.paging) {
if(feed.paging.next) {
var load_more = '<div id="load-more"><center>Load more</center></div>',
method = '',
params = '';
$('#feed').append(load_more);
$('#load-more').click( function() {
loadFeed(feed.paging.next);
});
}
}
});
}
On the first call of this function, I get this error:
error: Object
code: 2500
message: "Unknown path components: /', 'POST', [object Object]}"
type: "OAuthException"
This seems to tell me that I've basically put the query together wrong, but I've tried a few different things and none of it is working. You can see in the error message that there's a missing single quote at the beginning of the query, and I've not been able to figure out how to keep the single quote there.
Does anyone have any ideas on how I can fix this problem?
Also, if you know a better way to do all this then I'd appreciate that as well!
It seems you are building your Javascript API call with HTTP API parameters.
To query JS API for user:
FB.api(
"/me", // or "/99999999999" the user's id
function(response) {
if (response && !response.error) {
/* handle the result */
}
);
Source: https://developers.facebook.com/docs/graph-api/reference/v2.2/user
To query JS API for group:
FB.api(
"/{group-id}",
function(response) {
if (response && !response.error) {
/* handle the result */
}
}
);
Source: https://developers.facebook.com/docs/graph-api/reference/v2.2/group
So I've got a website where I want to click a button, check to see if the user has certain permissions, and if so popup a window to a new web page. On the java script I've got something like this:
function sendAjax(methodName, dataArray, success, error, category) {
var error2 = error || function () { };
$.ajax({
type: 'POST',
url: '/PermissionChecker' + methodName,
data: JSON.stringify(dataArray),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (r, s, x) { if (!success || success(r, s, x) != false) if (typeof (window.ChangeLogAdd) == 'function') { ChangeLogAdd(category); } },
error: error2
});
}
function CheckPermissions() {
sendAjax("CheckPermission", null, function (data) { var permission = eval('(' + data + ')'); if (permission == true) { alert('yay'); } else { alert('nay'); } }, null, 'Check Permission');
}
And the C# side is a simple function that does an if check and returns a bool. The function call goes through fine, but when it returns the bool I get a javascript error "Expected ']'". I assume this has something to do with my success function:
function (data) {
var permission = eval('(' + data + ')');
if (permission == true) {
alert('yay');
}
else {
alert('nay');
}
}
seeing as I didn't get this error before I tried what I'm doing there, so I was wondering how I would go about getting the data back from the ajax call to make pass the permission == true if/else check
Don't use eval for this purpose. It's unsafe and the source of many bugs. Just make the server respond with JSON and use $.getJSON.