javascript not running when logging in with different username - javascript

so i have a website made in ASP.NET that uses JS to generate some DOM elements after getting settings from the users account.
problem is that after i sign out and log in with a different user name i get the generated elements from the previous user and i don't know why. the code that generates the elements is as follows:
$.ajax({
url: '#Url.Content("~")' + 'Ticket/GetTvrtke',
async: false,
success: function (data) {
document.getElementById("header_tvrtka_holder").innerHTML = data;
}
});
and a little afterward its is used as such:
var tvrtke = document.getElementById("header_tvrtka_holder").innerHTML.split(", ");
$.each(tvrtke, function (index, value) {
$("#KlijentMultiSelect").append("<option value=\"" + value + "\" id=\"" + index + "\" >" + value + "</option>");
});
now when i log off and sign in as a different user the ajax code above doesn't trigger the getTvrtke URL that gets the settings wich generate the elements and i don't know why.

Ajax by default caches the response of the calls. YOu can set it to false so that there is a fresh request every single time by using the below at the top of your application.
$.ajaxSetup({cache: false});

Related

Website not reading the correct local json

I have made a HTML site that reads a .json with javascript/jQuery and writes to it with PHP.
I then have a c++ backend that writes and reads to the same .json.
I want to be able to send what button is selected by the players to the c++.
The .json that javascript reads isn't always the .json that I have modified with PHP or C++.
It won't always have the updated data, the time to get the updated data can be instant, a few seconds or e few minutes.
I have tried to remove caching and I have checked that the file gets updated
To load the .json on the website I use:
var $JSONList = $('#JSONList');
$.getJSON("json/playerMode.json", function(json) {
console.log(json); // this will show the info it in firebug console
var stringed = JSON.stringify(json);
var response = JSON.parse(stringed);
console.log(response); // this will show the info it in firebug console
$.each(response, function(i, itt){
$JSONList.append( "</br>" + itt.Name + " has pressed: " + itt.Button + " :(())");
})
});
This is called by a <button>
Since this sometimes won't load the updated .json, is there some way that I can force javascript to load the local .json again?
First, let's make the assumption this url works - except the caching issue and address that and other things as noted.
Change from the shortcut "json/playerMode.json" to $ajax
Force to NOT cache the results
Added a fail just in case
fixed syntax for "<br />"
removed unneeded code as the JSON would be parsed already as long as it is valid. IF it is not valid JSON and it only returns "a string, that looks like JSON", you should use dataType: "text json" to force jQuery conversion/parse
or consider using a converter (see below)
MIGHT need header('Content-Type: application/json') for PHP
if you are NOT returning a true JSON string, use a converter to make it into one, see Using Converters here: https://api.jquery.com/jQuery.ajax/
This from https://api.jquery.com/jquery.ajax/
Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET
parameters.
$.ajax({
type: "GET",
url: "json/playerMode.json",
cache: false,
data: "",
dataType: "json" // force automatic parse of the JSON string returned
}).done(function(json) {
console.log(json); // this will show the info it in firebug console
// should not need
// var stringed = JSON.stringify(json);
// not needed, see above
// var response = JSON.parse(json);
//console.log(response); // this will show the info it in firebug console
//$JSONList - what is this? it should be in here somewhere...so I did that
let $JSONList = $('#JSONList');
// should be parsed already, so changed to that
$.each(json, function(i, itt) {
$JSONList.append("<br />" + itt.Name + " has pressed: " + itt.Button + " :(())");
}).fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<div id="JSONList"></div>

Output html from ajax/jsonp request using jQuery

I'm trying to output html using an ajax request from a jsonp file . When using console.log I'm seeing the data looping fine, however when using a variable to grab the loop and output in html, I'm only seeing one result. What am I missing?
$.ajax({
url: "http://sitedotcom/blog/json",
dataType: "jsonp",
jsonpCallback: "jsonpCallback",
success: jsonpCallback
});
function jsonpCallback(data) {
for (var key in data) {
if (data.hasOwnProperty(key)) {
console.log(data[key]["title"] + ", " + data[key]["entry_id"]);
rssData = '<h2>' + data[key]["title"] + "</h2><p>" + data[key]["blog_summary"] + "</p>";
}
$('#blog-content').html(rssData);
}
}
You have $('#blog-content').html(rssData); inside the loop....so only the last result will show since html() replaces all content.
Try using append() instead or concatenate rssData each iteration and set html() after loop completes
It looks like rssData is out of scope when you are adding it to your #blog-content. Also you are outputting different data when doing your console log and setting your rssData variable.
If you could provide the json layout and also the html layout you are trying to append to.

Ajax call isn't returning anything

I'm pretty much a complete beginner at javascript and jQuery, so please bear with me.
I have a Spark-API running, and a web front-end that uses it through ajax calls.
I'm trying to call this function
function getSpotifyURL(ms, name) {
$.ajax({
url: "http://localhost:8081/playlist?ms=" + ms + "&name=" + name,
dataType: "json",
})
.done(function( data ) {
console.log(data);
})
}
The method is placed outside of:
$(document).ready(function() {
The reason it's outside is that I get an error upon calling it saying it's "undefined" if it's within $(document).ready.
The Spark-method is supposed to return a String (and it does when you try it directly through the browser).
The way I'm calling the getSpotifyURL-method is through a html button's "onclick". Like this:
<a href='#' onclick='getSpotifyURL(" + data[i].duration + ",\"" + data[i].destination + "\")'>Create Spotify playlist for this trip</a>"
The problem:
The .done-block does nothing in my code. Nothing is printed to console.
What I've tried:
Using "success" within the ajax part instead of .done
Placing the function with $(document).ready(function() { ... }
I understand that you might need more information to be able to help me, but I'm not sure what else information to provide right now. So if there's something you need to know, just ask.
Ideas?
SOLVED!
I'm a dumb person and forgot to remove dataType: "json", as the Spark-server in this instance returned a String, not a json object. Anyway, thanks for your input everybody. Much appreciated.
I think the problem is when you bind your function onclick. There is a syntax error, as you can see on the browser console
function getSpotifyURL(ms, name) {
console.log("http://localhost:8081/playlist?ms=" + ms + "&name=" + name);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href='#' onclick='getSpotifyURL(" + data[i].duration + ",\"" + data[i].destination + "\")'>Create Spotify playlist for this trip</a>"
I guess data is a variable, so you should call it without brackets
<a href='#' onclick='getSpotifyURL(data[i].duration, data[i].destination)'>Create Spotify playlist for this trip</a>
The reason you are getting undefined method when you are placing the function inside the $(document).ready(function() { ... }); call is because you are using the onclick attribute to call the function. $(document).ready(...) is not in global context as to where you onclick attribute is, and would therefore not recognize it from within the document.ready resulting in your undefined method error.
When sending your Ajax request, you also need to specify a type of request (GET or POST) that you are making. I would also suggest restructuring your ajax call to look more like #Moe's answer.
If you want to get it inside the DOM, consider doing the following:
HTML
<!-- I gave the link a class name and removed the onclick= attribute -->
Create Spotify playlist for this trip
JavaScript
$(document).ready(function() {
// I gave the <a> link a click handler
$(".create-spotify-playist").on("click", function(e) {
e.preventDefault(); // prevents link from requesting
var ms = ?? //I'm not sure where you're getting your parameters from,
var name = ?? //so you will probably have to figure out how to get those in here yourself
$.ajax({
type: "GET",
url: "http://localhost:8081/playlist",
data: { ms: ms, name: name },
success: function(data) {
console.log("Success: " + data);
},
error: function(data) {
console.log("Error: " + data);
}
});
});
});
I gave the link a click handler and placed it inside the $(document).ready, and by removing the onclick attribute from earlier, it can now be triggered from inside $(document).ready.

How to update background of page dynamically with Flickr API

Edit: Static source urls can be constructed for Flickr images. Explanation:
https://www.flickr.com/services/api/misc.urls.html
I am making an ajax request to grab photos and I would like to parse this information in order to update the background of the page.
This is rough code:
$.ajax({
url: 'https://api.flickr.com/services/rest/?method=flickr.photos.search&api_key=[API_KEY]&safe_search=&lat=' + geoLat + '&lon=' + geoLong + '&format=json&nojsoncallback=1',
error: function() {
console.log('FlickerAPI Error');
},
success: function(data) {
var photoID = data.photos.photo[0].id;
var ownerID = data.photos.photo[0].owner;
var backgroundImageUrl = 'http://www.flickr.com/photos/' + ownerID + '/' + photoID + '/';
$('body').css('background-image','url(backgroundImageUrl)');
},
always: function() {
console.log('finished flicker');
}
});
When I log to the console this info, I get this error:
GET http://localhost:4567/backgroundImageUrl 404 (Not Found).
But when I log out the backgroundImageUrl I get: http://www.flickr.com/photos/[the right photo id]/[the right user id]/ which if I follow the link, takes me to the page that I want.
I've searched the docs, and it looks like they don't pass a url attribute.
Is this a problem with using localhost? Is there a better way to update the background with an image? Thanks
You are using the string literal backgroundImageUrl rather than using the contents of the variable (the actual url). Because that string doesn't contain a host or protocol it thinks it is relative to the current request.
You need to append the value of the variable when making the url instead.
$('body').css('background-image','url(' + backgroundImageUrl + ')');

Ajax/Jquery calling a webmethod/service every 'interval' seconds

I have a ASP.Net web app with jquery implemented on the client side. The client side jquery script makes an asynchronous call to a web method in the server side code. The call returns the status open record(active/inactive) which jquery uses to update the user. The goal is to have jquery repeatedly call the server, once open record is inactive, then we need to display message to user so that you're no longer associated to this record..I set up the TimeInterval in one off the HiddenFieldValues and passing to the Jquery/ajax Function.
This function is written In a separate JavaScript file and it has been referred in my ASPX page Script Manager. I have to pass 'interval' from the server side, which is configured in the .config file.
function myWebServiceFunction(val1, val2, val3, interval) {
$.ajax({
type: "POST",
url: "/Application/WebServices/MyService.asmx/CheckFunction",
data: "{'val1':'" + val1 + "','val2':'" + val2 + "','val3':'" + val3 + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
success: function (msg) {
debugger;
var obj = function callbackfunction() {
myWebServiceFunction(HealthCarrierShortName, authID, networkID, interval)
}
if (!msg.d) {
window.setTimeout(obj, interval);
}
else {
// Still need to implement how to display to user if the record is not long associated to that user. help me in this too
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert('AJAX failure');
}
});
}
In my Server Side, I Used RegisterStartUpScript at the end of Page_load method and calling that JQuery Function
ScriptManager.RegisterStartupScript(Me.Page, Page.GetType(), "AuthLockPolling", " myWebServiceFunction('" + val1HiddenField.Value + "','" + val2HiddenField.Value + "','" + val3HiddenField.value+ "','" + val4HiddenField.value+ ");", True)
But it is not working properly(Don't know exactly the reasons). My Jquery function is not being called at all. I testing by placing debugger into my script and it is not been hit.
Still need to implement how to display message to user if the that record is not long associated to that user like in a alert window/pop-up window. Please help me in this part too.
Please Advise me what went Wrong and How to solve this. Thanks In advance!
How to solve this:
RegisterStartupScript can be confusing (ask me how I know!). Are you using this on a page that uses partial-page updates (i.e., has UpdatePanel controls)? If not, you should use the method in the ClientScriptManager (instead of ScriptManager) class.
If it is used on a page with partial-page updates for a control that's inside an UpdatePanel, the first parameter should be a control within the UpdatePanel, rather than the Page.
And a debugging tip: Test by passing in JavaScript code that's drop-dead simple, like alert('Hello, World!');. This can help you tell if the problem is in the RegisterStartupScript call or in your myWebServiceFunction function.
Finally, here's the Microsoft documentation: https://msdn.microsoft.com/en-us/library/bb310408(v=vs.110).aspx. Because there are methods of the same name in different classes, read the documentation verwy, verwy, carefulwee.

Categories

Resources