In shared folder of ASP.NET C#, I create a .cshtml which defines a button that can GET data from an API. I would like to generate an url and use it to update an iframe of a viewer.
function callAPI(searchText) {
$.ajax({
url: '/Home/CallAPI',
data: { Text: searchText },
type: "GET",
success: function (result) {
var data = JSON.stringify(result); // server response
found_data = data;
$(result).each(function () {
if (this.status == "found") {
alert("Found!" + data);
var frameElement = document.getElementById("SearchingMap");
lon = result.results[0].lon;
lat = result.results[0].lat;
new_searching_url = "http://xx.xxx.xxx.xxx:8080/styles/osm-bright-tw/#17/" + lat.toString() + "/" + lon.toString();
console.log(frameElement.src); // undefined
frameElement.src = new_searching_url;
console.log(frameElement.src); // "http://xx.xxx.xxx.xxx:8080/styles/osm-bright-tw/#17/.../..."
}
else {
alert("Sorry! Not found");
}
});
},
error: function () {
alert("Sorry! Not found");
}
});
}
However, the iframe in the viewer, which named SearchingMap.cshtml, doesn't updated.
#{ViewBag.Title = "SearchingMap";}
<div id="SearchingMap">
<h3>Searching map</h3>
<iframe src="http://xx.xxx.xxx.xxx:8080/styles/osm-bright-tw/#10.01/25.0709/121.5008" frameborder="0" scrolling="no">Your browser doesn't support iframe.</iframe>
</div>
Why can't it work? How can I update the iframe of a viewer?
Here the iframe did not have the id SearchingMap so all javascript code fails because of this line:
var frameElement = document.getElementById("SearchingMap");
Just add this id, on your iframe
<iframe id="SearchingMap" ...
Related
I wrote this code to check if there are files with the same name "planning" in the "upload" folder, but with only pdf or html extension. I know, this syntax is not optimized but it works. I think there are shorter and simpler ways.
Does anyone have any examples to share with me?
Thanks.
<script>
function FileExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
var source = "upload/planning_11";
var pdf_file = FileExist(source+".pdf");
var html_file = FileExist(source+".html");
if (pdf_file==true && html_file==false) {
$('#exist_file_pdf').show();
$('#exist_file_html').hide();
$('#exist_file_all').hide();
} else if (pdf_file==false && html_file==true) {
$('#exist_file_html').hide();
$('#exist_file_html').show();
$('#exist_file_all').hide();
} else if (pdf_file==true && html_file==true) {
$('#exist_file_html').hide();
$('#exist_file_html').hide();
$('#exist_file_all').show();
} else if (pdf_file==false && html_file==false) {
$('#exist_file_html').hide();
$('#exist_file_html').hide();
$('#exist_file_all').hide();
}
</script>
<div id="exist_file_pdf">PDF planning file exist</div>
<div id="exist_file_html">HTML planning files exist</div>
<div id="exist_file_all">PDF and HTML planning files exists !</div>
Don't use async false
Instead you can do this
const source = "upload/planning_11";
const pdfUrl = source + ".pdf";
const htmlUrl = source + ".html";
$('#exist_file_all').hide();
$('#exist_file_html').hide();
$('#exist_file_pdf').hide();
$.ajax({
type: 'HEAD',
url: pdfUrl
success: function(msg) {
$('#exist_file_pdf').show();
$.ajax({
type: 'HEAD',
url: htmlUrl
success: function(msg) {
$('#exist_file_html').show();
if ($('#exist_file_html').is(":visible") &&
$('#exist_file_pdf').is(":visible")) {
$('#exist_file_all').show();
$('#exist_file_html').hide();
$('#exist_file_pdf').hide();
}
}
});
}
});
users can sign in to my system using google sign in so when use pressing google sign in button his account will be create in mysql database
my problem is every users account created two time when user trying to sign in by google
in other words function of create account executed two time for every user
here is my html code
<a id="gp_login" href="javascript:void(0)" onclick="javascript:googleAuth()">Login using Google</a>
this is javascript code
function gPOnLoad(){
// G+ api loaded
document.getElementById('gp_login').style.display = 'block';
}
function googleAuth() {
gapi.auth.signIn({
callback: 'gPSignInCallback',
clientid: '636950137786-j3siaftgshtf9iamovisf603pplv7jf1.apps.googleusercontent.com',
cookiepolicy: "single_host_origin",
requestvisibleactions: "http://schema.org/AddAction",
scope: "https://www.googleapis.com/auth/plus.login email https://www.googleapis.com/auth/user.phonenumbers.read https://www.googleapis.com/auth/user.birthday.read"
})
}
function gPSignInCallback(e) {
if (e["status"]["signed_in"]) {
gapi.client.load("plus", "v1", function() {
if (e["access_token"]) {
getProfile()
} else if (e["error"]) {alert(e['error'])
console.log("There was an error: " + e["error"])
}
})
} else {alert(e["error"]);
console.log("Sign-in state: " + e["error"])
}
}
function getProfile() {
//var e = googleData.getBasicProfile();
var e = gapi.client.plus.people.get({
userId: "me"
});
e.execute(function(e) {
if (e.error) {alert(e.message)
console.log(e.message);
return
} else if (e.id) {var msgs=JSON.stringify(e);
alert(e.displayName);
update_user_data(e);
// save profile data
}
})
}(function() {
var e = document.createElement("script");
e.type = "text/javascript";
e.async = true;
e.src = "https://apis.google.com/js/client:platform.js?onload=gPOnLoad";
var t = document.getElementsByTagName("script")[0];
t.parentNode.insertBefore(e, t)
})()
function update_user_data(response)
{
// var dataString = JSON.stringify(response);
var email=response.emails[0]['value'];
var displayName=response.displayName;
//ar
$.ajax({
type: "POST",
data: {email:email,displayName:displayName},
url: 'Save.php?id=check_user',
success: function(msg) {
var array = msg.split(',');
var email =array[0];alert(email);
var password = array[1];alert(password);
$('#username').val(email);$('#password').val(password);
document.getElementById("modal4c").click();
},
error: function(XMLHttpRequest,textStatus,errorThrown) {//alert(JSON.stringify(msg));
}
});
}
update_user_data() function is to insert account into mysql database but this function is called twice per user.
Not sure why you function runs twice but,
one way to ensure a function runs only once would be make some global flag like this
runOnce = false;
function gPSignInCallback(e) {
if(runOnce) return;
runOnce = true;
// ... rest of the function
}
If you want to avoid global vars you could return a closure like this
function update_user_data(e){
var runOnce = false
return function(){
if(runOnce) return;
runOnce = true;
// ... rest of the function
}
}
And call it like this update_user_data()(e)
I need only one tab accessible for my website. When he tries to open in new tab or even tries to copy and paste the url in new tab should clear the user's session and logout from the application.
There are several reasons,
When a user opens a new tab connecting to the same application - the session id is the same.
Imagine that this user has reached a page X in the application flow from the first tab.
When he opens the second tab he might be in one of the following scenarios - depending how the second tab was opened - new tab, duplicate tab (this copies the URL to the newly opened tab), or new session.
All of the above will "confuse" the server as to what the next valid state of the application is, and could override data entered in different tab, without his/her knowledge
What I want is to prevent a single user to have several tabs in the same session, i.e. only one tab/window per user, per session.
Including the below script in dashboard.php after login
<script>
$(document).ready(function()
{
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
else
{
sessionStorage.pagecount = 1;
}
}
else
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
});
Below code in other sub pages in the application
<script>
$(document).ready(function()
{
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
sessionStorage.pagecount = Number(sessionStorage.pagecount) + 1;
}
else
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
}
else
{
sessionStorage.removeItem('pagecount');
window.location='logout.php';
}
});
</script>
Added the below script after I login(say dashboard.php)
<script>
$(document).ready(function()
{
$("a").attr("target", "");
if(typeof(Storage) !== "undefined")
{
sessionStorage.pagecount = 1;
var randomVal = Math.floor((Math.random() * 10000000) + 1);
window.name = randomVal;
var url = "url to update the value in db(say random_value)";
$.post(url, function (data, url)
{
});
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>
Added the below script in Header in rest of my pages - 'random_value' is from db for that user
<script>
$(document).ready(function()
{
$("a").attr("target", "_self");
if(typeof(Storage) !== "undefined")
{
if (sessionStorage.pagecount)
{
if('<?=$random_value?>' == window.name)
{
sessionStorage.pagecount = Number(sessionStorage.pagecount) + 1;
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>
<script>
$(document).ready(function()
{
$("a").attr("target", "");
if(typeof(Storage) !== "undefined")
{
sessionStorage.pagecount = 1;
var randomVal = Math.floor((Math.random() * 10000000) + 1);
window.name = randomVal;
var url = "url to update the value in db(say random_value)";
$.post(url, function (data, url)
{
});
}
else
{
var url = "url to remove random_value";
$.post(url, function (data, url)
{
sessionStorage.removeItem('pagecount');
sessionStorage.clear();
window.location = 'logout.php';
});
}
});
</script>
I have this ajax call here in a script tag at the bottom of my page. Everything works fine! I can set a breakpoint inside the 'updatestatus' action method in my controller. My server gets posted too and the method gets called great! But when I put the javascript inside a js file the ajax call doesn't hit my server. All other code inside runs though, just not the ajax post call to the studentcontroller updatestatus method.
<script>
$(document).ready(function () {
console.log("ready!");
alert("entered student profile page");
});
var statusdropdown = document.getElementById("enumstatus");
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById("enumstatus");
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
</script>
Now I put this at the bottom of my page now.
#section Scripts {
#Scripts.Render("~/bundles/studentprofile")
}
and inside my bundle.config file it looks like this
bundles.Add(new ScriptBundle("~/bundles/studentprofile").Include(
"~/Scripts/submitstatus.js"));
and submitstatus.js looks like this. I know it enters and runs this code because it I see the alert message and the background color changes. So the code is running. Its just not posting back to my server.
$(document).ready(function () {
console.log("ready!");
alert("submit status entered");
var statusdropdown = document.getElementById('enumstatus');
statusdropdown.addEventListener("change", function (event) {
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
// do something with the returned value e.g. display a message?
// for example - if(data) { // OK } else { // Oops }
});
var e = document.getElementById('enumstatus');
if (e.selectedIndex == 0) {
document.getElementById("statusbubble").style.backgroundColor = "#3fb34f";
} else {
document.getElementById("statusbubble").style.backgroundColor = "#b23f42";
}
}, false);
});
In the console window I'm getting this error message.
POST https://localhost:44301/Student/#Url.Action(%22UpdateStatus%22,%20%22Student%22) 404 (Not Found)
Razor code is not parsed in external files so using var id = "#Model.StudentId"; in the main view will result in (say) var id = 236;, in the external script file it will result in var id = '#Model.StudentId'; (the value is not parsed)
You can either declare the variables in the main view
var id = "#Model.StudentId";
var url = '#Url.Action("UpdateStatus", "Student")';
and the external file will be able to access the values (remove the above 2 lines fro the external script file), or add them as data- attributes of the element, for example (I'm assuming enumstatus is a dropdownlist?)
#Html.DropDownListFor(m => m.enumStatus, yourSelectList, "Please select", new { data_id = Model.StudentId, data_url = Url.Action("UpdateStatus", "Student") })
which will render something like
<select id="enumStatus" name="enumStatus" data-id="236" data-url="/Student/UpdateStatus">
Then in the external file script you can access the values
var statusbubble = $('#statusbubble'); // cache this element
$('#enumStatus').change(function() {
var id = $(this).data('id');
var url = $(this).data('url');
var status = $(this).val();
$.post(url, { ID: id, Status: status }, function (data) {
....
});
// suggest you add/remove class names instead, but if you want inline styles then
if (status == someValue) { // the value of the first option?
statusbubble.css('backgroundColor', '#3fb34f');
} else {
statusbubble.css('backgroundColor', '#b23f42');
};
});
I am trying to have a button that users can click to download a file, but the file may not exist because it is a zipped file of other files and has to be generated. I am checking this with AJAX but once I recieve a proper URL I'm not sure how to have the user download it.
window.open(link, '_blank'); tries to open the window to download the file, but most browsers prevent this and treat it as a pop-up. What is the best practice for having a user download a file like this? Thanks.
Here is the JS function I am using for reference:
function getDownloadedFiles() {
var INTERVAL_TIME = 3000,
$projectView = $('#project-view'),
id = $projectView.data("project-id");
$.ajax({
type: "GET",
url: AJAX_URL + id,
success: function(data) {
if (data.success) {
var link = data.profiler.link;
window.open(link, '_blank');
} else {
setTimeout(getDownloadedFiles, INTERVAL_TIME);
}
}
});
}
In the end, the correct solution was Download File Using Javascript/jQuery and I was using the wrong URL.
I was setting the link to be data.profiler.link when really it was data.data.link and confused myself.
Here is my final code:
function getDownloadedFiles() {
var INTERVAL_TIME = 3000,
$projectView = $('#project-view'),
id = $projectView.data("project-id");
$.ajax({
type: "GET",
url: AJAX_URL + id,
success: function(data) {
if (data.success) {
var link = data.data.link,
hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = link;
} else {
setTimeout(getDownloadedFiles, INTERVAL_TIME);
}
}
});
}
Maybe you can use a hidden iframe for that matter. Try this:
var downloadURL = function downloadURL(url) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
};
Just a shameless rip of Download File Using Javascript/jQuery