Best way to handle ajax call with port in MVC - javascript

I can't find any better solution in Google.
I have an MVC application.
When I use Visual studio the URL is
http://localhost:12345/NewApp - This works
When I deploy this to my local webserver the URL is
http://win2k12/NewApp - This works
I have a port forward on my router to port 8878 to point to the win2k12 server. I have a domain name (e.g. http://mydomain.uk) which is set to point to my actual IP xxx.xxx.xxx.xxx address. so when I want to access my MVC app externally I use this url
http://mydomain.uk:8878/NewApp - this works but only for the first level. When I call an Action through ajax like this
From the image above, the baseUrl only returns http://mydomain.uk/NewApp (without the port) which cause an error. My current workaround is to hardcode the port which is not Ideal.
I used baseUrl because If I don't the Virtual Directory doesn't get recognize. I'm sure this is just a workaround and I'm just wondering if there is a proper way of doing it.
<script>
$(document).ready(function () {
var baseUrl = '#HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority)#Url.Content("~/")';
$("a").click(function (e) {
if ($(this).attr("action") == "Edit") {
$("#dlgCode").empty()
.load(baseUrl + "/Codes/Edit?id=" + $(this).attr("code_id") + "&timestamp=" + new Date().getTime());
setTimeout(function () {
$("#dlgCode").css("display", "");
$("#dlgCode").dialog({
width: "25%",
maxWidth: "768px",
title: "Edit Code"
});
}, 1000);
} else if ($(this).attr("action") == "Delete") {
$("#dlgCode").empty()
.load(baseUrl + "/Codes/Delete?id=" + $(this).attr("code_id") + "&timestamp=" + new Date().getTime());
setTimeout(function () {
$("#dlgCode").css("display", "");
$("#dlgCode").dialog({
width: "25%",
maxWidth: "768px",
title: "Delete Code"
});
}, 1000);
} else if ($(this).attr("action") == "Add") {
$("#dlgCode").empty()
.load(baseUrl + "/Codes/Add?id=" + $(this).attr("group_id") + "&timestamp=" + new Date().getTime());
setTimeout(function () {
$("#dlgCode").css("display", "");
$("#dlgCode").dialog({
width: "25%",
maxWidth: "768px",
title: "Add Code"
});
}, 1000);
}
else if ($(this).attr("action") == "Cancel") {
$("#dlgCode").dialog('close');
}
//console.log($("#dlgCode").html());
//alert($(this).attr("code_id"));
});
});
UPDATE:
I tried outputting the port from the view and re-deploy and access it externally but the port that gets recognize was 80.
alert('#HttpContext.Current.Request.Url.Port');

Related

Proxy Chrome Storage

I am trying to get my proxy chrome extention to keep on/off after closing using chrome.local.storage. This does not seem to work, can anyone give some examples on how to get this kind of code working?
Right now my pac proxy works and turns on and off. The local storage does not seem to work at all, but I followed all the examples on the developer.chrome website. That does not work.
var channels;
var ny;
function endvpn() {
// turn off vpn
var config = {
mode: "pac_script",
pacScript: {
data: "function FindProxyForURL(url, host) {\n" +
" if (host == 'google.com /*')\n" +
" return 'PROXY blackhole:80';\n" +
" return 'DIRECT';\n" +
"}"
}
};
chrome.storage.local.set({ny: false});
// change vpn button
document.getElementById("vpnbtn").innerHTML = "Start Vpn";
// turn off event lisner for endvpn and start event listner to go back to startvpn
document.getElementById('vpnbtn').removeEventListener('click', endvpn, false);
document.getElementById("vpnbtn").addEventListener("click", startvpn);
}
function startvpn() {
// turn on vpn
var config = {
mode: "pac_script",
pacScript: {
data: "function FindProxyForURL(url, host) {\n" +
" if (host == 'google.com /*')\n" +
" return 'PROXY blackhole:80';\n" +
" return 'PROXY 209.127.191.180:80';\n" +
"}"
}
};
chrome.storage.local.set({ny: true});
// change vpn button
document.getElementById("vpnbtn").innerHTML = "Stop Vpn";
// turn off event lisner for startvpn and start event listner to go back to endvpn
document.getElementById('vpnbtn').removeEventListener('click', startvpn, false);
document.getElementById("vpnbtn").addEventListener("click", endvpn);
}
var rez = chrome.storage.local.get(ny);
alert(rez);
// start at startvpn
document.getElementById("vpnbtn").addEventListener("click", startvpn);
Most apis within Chrome extensions are asyncronous. See the documentation here. You can provide a callback as the second argument to the 'get' function where you can use the variable:
chrome.storage.local.get('ny', function(result){
alert(result.ny);
});

Change client URL without requesting route to Node JS

My router.js, which is in public directory works the following way:
First, listens to the event of clicking an 'a' tag
Then, prevents following the link and passes the href value to this function
function loadPage(targetUrl) {
if (targetUrl == "/") {
loadHome(); //Loads Home Page
} else {
if (isSpanish()) {
var direction = "/pages/es" + targetUrl + ".html";
} else {
var direction = "/pages/en" + targetUrl + ".html";
}
var subDirections = direction.split("/");
$('#content').load(direction, function (response, status, xhr) { //Loads content
if (status == "error") {
$("#error-popup").slideDown();
$("#error-popup-wrapper").fadeIn();
document.title = "404" + titleAddon;
} else {
document.title = document.getElementById("title").innerHTML + titleAddon;
window.history.pushState({ url: "" + targetUrl + "" }, null, targetUrl);
}
});
window.scrollTo(0, 0);
}
};
But I believe is conflicting with my index.js which controlls the only route I have:
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '/views/index.html'));
});
Everytime I click on a link, I believe the client is requesting the server for the route, and my router.js loads it correctly, but I don't want the page to reload.
How could I solve this?
P.D. Sometimes the page doesn't reload, generally when clicking the menu links. Not sure why.
The website I'm uploading this code to is: https://testing.fsupv2017.webs.upv.es

Connection has not been fully initialized

In my application the following console error occurs when I navigate to another page.
Uncaught Error: SignalR: Connection has not been fully initialized. Use .start().done() or .start().fail() to run logic after the connection has started.
In layout page the scripts are in the following order.
#Styles.Render("~/Content/themes/base/jqueryUi")
#Styles.Render("~/Content/customCss")
#Scripts.Render("~/Scripts/jQuery")
#Scripts.Render("~/Scripts/customScripts")
<script src="/signalr/hubs"></script>
var progressHub = $.connection.parallelProcessing;
var flagDownload = true;
$(function() {
progressHub.client.updateProgresssBar = function(progressPercentage, downloadedSize, totalFileSize) {
debugger
downloadProgress("", "", "");
$("#downloading-progress").dialog("open");
var progressObj = $("#progressBar").data("ejProgressBar");
progressObj.option("text", progressPercentage + " %");
progressObj.option("percentage", progressPercentage);
$(".received").html("(" + downloadedSize + " ");
$(".total-size").html("of " + totalFileSize + ")");
flagDownload = true;
if (progressPercentage == 100)
$("#downloading-progress").dialog("close");
};
progressHub.client.noNetConnection = function() {
if (flagDownload) {
flagDownload = false;
showalertdownload("#Message.Nointernetconnection");
}
};
progressHub.client.closeProgressDialog = function() {
$("#downloading-progress").dialog("close");
enableEvents();
};
$.connection.hub.start().done(function () {
});
});
function updateConnectionID() {
progressHub.server.updateConnectionID();
}
Please let me know is ther any solution to resolve this issue.Thanks in advance.
Basing my answer on your error message, it seems you are trying to access your connection or hub without waiting for it to be initialized.
Taken from the ASP.NET SignalR Github wiki:
// This callback will only run once
connection.start().done(function() {
console.log("connection started!");
});
A more complete and detailed example to be found on ASP.NET website

Open itunes window inside ios cordova application

i`m using apache cordova to build ios applications from some html, css and js. At this time i need to open other application inside opened application, for this purposes i use startapp plugin. Everything is ok, but i want opening itunes window inside app with link on application that need to open if application not installed. Here is function that i wrote, but it not give me the result that i want:
function appToApp(identifier, iTunesUrl, success, fail) {
var app;
// Init app starter
if(device.platform === 'iOS') {
app = startApp.set(identifier);
} else if(device.platform === 'Android') {
app = startApp.set({
"package": identifier
});
}
console.log('Checking ' + identifier + ' application existence...');
app.check(function(values) {
console.log('ok, application installed!');
console.log(values);
// Run application
console.log('Running ' + identifier + ' application...');
// Start application
app.start(function() {
console.log('App with identifier = ' + identifier + ' opened!');
if (typeof(success) == 'function') {
success.call();
}
}, function(error) {
console.log('Can not open app with identifier = ' + identifier + '!');
if (typeof(fail) == 'function') {
fail.call();
}
console.warn(error);
});
}, function(error) {
console.warn('Something wrong with application, checking failed!');
// Open iTunes
var iTunes = startApp.set('itunes://');
iTunes.start(function() {
console.log('iTunes opened!');
}, function(error) {
console.warn('Can not open iTunes!');
});
console.warn(error);
});
}
Thanks in advance
As a result i have used this cordova plugins Custom-URL-scheme, AppAvailability.
First of all i attached custom scheme to app that need launch form another app:
cordova plugin add cordova-plugin-customurlscheme --variable URL_SCHEME=mycoolapp
Function that open app:
/**
* Run app from other app
* Dependencies:
* https://github.com/EddyVerbruggen/Custom-URL-scheme
* https://github.com/ohh2ahh/AppAvailability
*
* #param {string} scheme - scheme part of url
* #param {string} url - custom application url
* #param {string} iTunesUrl - url on application that located on iTunes
*/
function appToApp(scheme, url, iTunesUrl) {
appAvailability.check(
// URI Scheme or Package Name
scheme,
function() {
// Success callback
console.log(scheme + ' is available :)');
// Open application
window.open(url, '_system');
},
function() {
// Error callback
console.log(scheme + ' is not available :(');
if (iTunesUrl) {
console.log('Installing app from iTunes');
window.open(iTunesUrl, '_system');
} else {
alert("Application " + scheme + " is not available on this device, please install application first");
}
}
);
}

Uploadify and flash issue uploading to remote server

I'm trying to use uploadify to upload images to a remote server. I've have done everything I can think of for the cross scripting issue or whatever.
Here is what i've done.
scriptAccess to 'Always' in the uploadify function.
I have a crossdomain.xml on my ww2 server with uploadify.swf in the root as well.
I have uploaded my javascript jquery lib file to the remote ww2 server and put it in the header
I put the jquery.uploadify.js and the swfobject.js in the root directory as well.
If I try to click the X to cancel a file I get the error: Error calling method on NPObject
Or uploads don't work either.
If anyone can help with this that would be great. If there are any other good flash based or non flash based multi uploaders that will do remote files with no issue please let me know.
Thanks
I managed to figure it out on my own. I will answer it just incase someone else might have this issue because there is very little help even on the authors site for it.
I decided to leave the Flash file on the same server(Web server) because it didnt seem to work putting it on the media server with the javscript files. The js wouldn't work.
So my main server has the uploadify folder still on the server and I only put the php files(uploader.php) I needed to process my images on the media server AND the crossdomain.xml in the root of that server.
Then told uploadify in the parameter settings to point to my uploader.php script on that server.
Everything worked like a charm after that. I took quite a while to figure it out and get passed the errors. Now I can load balance my media.
Hope this helps someone else. Uploadify is a really nice multi file uploader.
You need to change code in your uploadify.js:
/* Original code */
uploadifyCancel:function(ID) {
jQuery(this).each(function() {
document.getElementById(jQuery(this).attr('id') + 'Uploader').cancelFileUpload(ID, true, true, false);
});
},
/*New code */
uploadifyCancel:function(ID){
jQuery(this).each(function(){
document.getElementById(jQuery(this).attr("id")+"Uploader").cancelFileUpload(ID,true,false)
});
},
/*Original code */
jQuery(this).bind("uploadifyComplete", {
'action': settings.onComplete
}, function(event, ID, fileObj, response, data) {
if (event.data.action(event, ID, fileObj, unescape(response), data) !== false) {
jQuery("#" + jQuery(this).attr('id') + ID).find('.percentage').text(' - Completed');
if (settings.removeCompleted) {
jQuery("#" + jQuery(event.target).attr('id') + ID).fadeOut(250,function() {
jQuery(this).remove()
});
}
jQuery("#" + jQuery(event.target).attr('id') + ID).addClass('completed');
}
});
/* New code */
jQuery(this).bind("uploadifyProgress", {
'action': settings.onProgress,
'toDisplay': settings.displayData
}, function(event, ID, fileObj, data) {
if (event.data.action(event, ID, fileObj, data) !== false) {
jQuery("#" + jQuery(this).attr('id') + ID + "ProgressBar").animate({
'width': data.percentage + '%'
},250,function() {
if (data.percentage == 100) {
jQuery(this).closest('.uploadifyProgress').fadeOut(250,function() {
jQuery(this).remove()
});
}
});
if (event.data.toDisplay == 'percentage') displayData = ' - ' + data.percentage + '%';
if (event.data.toDisplay == 'speed') displayData = ' - ' + data.speed + 'KB/s';
if (event.data.toDisplay == null) displayData = ' ';
jQuery("#" + jQuery(this).attr('id') + ID).find('.percentage').text(displayData);
}
});

Categories