aspx page open a hyperlink via a button - javascript

I've read a few answers, and tried a bit of different code from them, but haven't been able to solve this. I am a newbie at this and it seems like quite a simple thing to do, apologies if the answer is really obvious, just need it to work really..
So far, I have an aspx page in Visual Studio 2010 / it was created by someone else, and has both JavaScript and cSharp code behind it.
What I would like to happen is that, an 'Edit' button appears on the page in a table in the correct place, and as a result of pressing it, another page is called allowing the editing (of contacts - it's an internal website).
I can get the link working OK as a 'normal' hyperlink, using this line of code:
var editcontact = '<td align = "right" colspan = "40" class =
"contactBorder"><a href="WebForm1.aspx?supplier_id=' +
dataRow.supplier_id + '">Open Contact(s) For Edit</a></td>';
edit contact then gets put in a table like structure (maybe it's "form" given the HTML tags):
finishedcontacts += openrow + contactid + contactname +
contactjobtitle + contactlocation + contacttelephone +
contactemail+ editcontact + '</form></tr>';
That's OK but it's not very 'nice', what I would like is an actual edit button, I can get the button to appear, but the last time I tried it pressing it does nothing:
var editcontact = '<asp:button id = "editImage4" runat="server"
Text="Click me"
OnClientClick="window.open(\'WebForm1.aspx\\?supplier_id=\' + dataRow.supplier_id + \', \'WebForm1\');" />';
Any ideas on how to get this working OK from a button?
Here is some other code I tried, which was to separate out the generation of the url from the calling code, but none of them seemed to work:
//var url = string.Format("{0}?supplier_id={1}", "../WebForm1.aspx", dataRow.supplier_id);
//var url = string.Format("{0}?supplier_id={1}", #"../WebForm1.aspx", dataRow.supplier_id);
//var url = 'string.Format("{0} supplier_id={1}", "WebForm1.aspx",'+ dataRow.supplier_id +')';
var url = 'WebForm1.aspx?supplier_id= '+ dataRow.supplier_id +'';
var supplierid1 = dataRow.supplier_id;
Any ideas what be greatly appreciated. This is my first ever post..

Use Response.Redirect(url) if you want to redirect using your button and this button must be a server side control.

In the end, a colleague helped me out with this.
As other posters identified there was some problems with the URL, and especially with the escapes.
Anyway below is the code in the unlikely event anyone needs something similar.
buttoncode = '';
var editcontact = '' + buttoncode + '';
And we added a function (which should probably be called a method or whatever):
function OpenContactForEdit(supplier_id)
{
window.location = "WebForm1.aspx?supplier_id=" + supplier_id;
}
Comments:
This bit is very important:
onClick="OpenContactForEdit(\'' + dataRow.supplier_id + '\')"
Note exactly how we needed to escape (and 'end escape') the single quotes.
I believe that was quite a big part of why, what I was doing was not working.

Related

How do I use a varible url for that uses a html to populate the webpage?

so my web page is http://localhost:7777/newdev/art.html which points to my html art.html doc. I wanna acces that html using a different utl like: http://localhost:7777/newdev/data/. I would just like a verrry simple way to go to that url and pull up the art.html.
I have tried adding the html at the end and also changing the rest service to look for the http://localhost:7777/newdev/art.html.
$scope.done = function(){
$scope.major = "";
$scope.picked = document.getElementsByClassName("math").value + "," + document.getElementsByClassName("Science").value + "," + document.getElementsByClassName("Music").value + "," + document.getElementsByClassName("Art").value+ "," + document.getElementsByClassName("ss").value;
var url= 'done.html/';
url+= '?id='+$scope.picked;
window.open(url);
};
Expected results: I will go to http://localhost:7777/newdev/data/ and it will pull up my html document.
Actual result: The rest service doesn't get called or the html doesn't open
Things to think about: This is not for a large website, its for just a side project that is going to stay on my machine and only be ran locally for learning purposes. I am looking for the simple most basic why to do this so it'll give me a platform to grow a learn from.

Implementing links in realtime chat

So I'm making a realtime chat with socket.io and node.js, and I have the chat and everything working, but if somebody links a website in the chat, I want it to be an hyperlink automatically.
I'm using autolinker.js to do this, and it's making the links as I want, but my problem is the way I output messages to avoid HTML injections.
for(var x = data.length - 1; x >= 0; x--) {
var autolinker = new Autolinker();
var linkedText = autolinker.link(data[x].message);
var message = document.createElement('div');
var linkOfMessage;
message.setAttribute('class', 'chat-message');
//message.textContent = data[x].name + ': ';
message.innerHTML = data[x].name + ': ' + linkedText;
// Append
messages.insertBefore(message, messages.firstChild);
messages.appendChild(message);
messages.scrollTop = messages.scrollHeight;
}
So the message is getting handled correctly, but with innerHTML, they can basically use scripts inside my chat, which is bad. But
message.textContent = data[x].name + ': ' + linkedText;
Will just display my hyperlink in plain text without it being clickable, is there anyway to do this without setting the site at risk?
I've spent a couple of hours looking around and couldn't fint anything related to this.
Thanks in advance!
You should always sanitize user input. You want links, so you have to allow some html tags in messages, but you want to filter out most of them (some are dangerous, like script, and some could "damage" your chat visuals). Try experimenting with packages such as
https://www.npmjs.com/package/sanitize-html
It's not a good idea to roll your own sanitizer. Packages like this allow to specify which tags to allow, which to remove and have various other, helpful options.

Updating <div> text with value from the previous page

I'm redirecting the user from another page when they click the "Edit" button using the code below.
$('#editListButton').click(function(){
window.location.href = "http://localhost/yyy.php"; //redirect
// Changes that need to be made
$('#defaultText').remove();
$('#orderList').append('<p' + 'message' + '</p>');
});
The page redirects to the predefined link, after which I need update a html <div> tag with text. But the code coming from the other page does nothing. How can change the text in the div tag?
Pass it in the url.
$('#editListButton').click(function(){
window.location.href = "http://localhost/yyy.php?message"; //redirect
});
Then on the other page
var url = window.location.href.split('?');
var msg = url[1];
$('#defaultText').remove();
$('#orderList').append('<p>' + msg + '</p>');
Once you've triggered an operation that's going to reload the entire page, browsers (not all, but it seems like most) will just quit doing anything to the current page, essentially ignoring any DOM updates from the event loop.
To get around this, it generally works to delay the redirect with a short timeout:
setTimeout(function() {
window.location.href = "http://localhost/yyy.php";
}, 1);
Now the browser doesn't know that the page is to be reloaded, so it'll obey your DOM update request.
edit — If what you're expecting (and it's not really clear from the OP, but it's hinted at in a comment below) is that the code after updating the location should affect the new page, well that's just not how things work. You can put that code in the new page (and pass parameters via the URL you're loading, if necessary) and have it run there, or else you can change the architecture completely and load your new code via ajax.
There are many ways to pass information from one page to another. To give an idea of the concept, somewhat in relation to the question posted, here's one:
Page A:
$('#editListButton').click(function(){
window.location.href = "http://localhost/yyy.php?action=remove&value=" +
encodeURIComponent('ashdahjsgfgasfas');
});
Page B:
var action = /(?:\?|&)action=([^&$]+)/.exec(location.search)
if ( 'remove' === action[1] ) {
var value = /(?:\?|&)value=([^&$]+)/.exec(location.search)
$('#defaultText').remove();
$('#orderList').append('<p>' + value[1] + '</p>');
}

MOSS 07 editform.aspx fails to commit and goes to blank html page

Found solution from Microsoft Blog... see below
OK, to start I don't like the word random but I cannot find any correlation in test cases for this problem so I am going to use random to describe parts of this problem.
The setup: I have a list where i have crated a customized UI for the EditForm.aspx and NewForm.aspx. I use the same JS file and JavaScript between the two of them. I have added in a google map to help illustrate the location selection. I have added extra code to the "OK" button for some dynamic validation. I have done a lot of dynamic menu things as well. All users use IE 9 and the site is on a MOSS 2007 server.
The problem: Only on the EditForm.aspx, clicking OK "Randomly" results in an immediate white screen. The form is not saved and when viewing the source code of the white screen i find a blank html page.
What I have tried to find this problem:
- I tried to narrow down the user and computer this happens on and found that it happens for everyone on every computer(once again "Randomly").
- I tried disabling the code that is pre-pended to the "OK" button
- I tried following the code with the IE9's external script debugged and found no errors
I can provide the code but it is a bit long and I really do not know where to begin. So i can provide it if needed.
Thanks for the help ahead of time.
Edit:
This is the code re-wiring my OK button(i reset the value to "Save" earlier)
var okBtns = $('input[value="Save"]')
$.each(okBtns, function(index,value){
okFunction=$(value).attr('onclick');
$(value).attr('onclick','return false;')
$(value).bind('click', function(){
if ($('#'+StatusBox).val()=='Draft') {$('#'+StatusBox).val('New Request')}
var err = clickOKbutton();
if(err==0) {okFunction()};
});
});
This is the clickOKbutton function witch is th code prepended to the orgianal sharepoint operations:
function clickOKbutton()
{
//all of the imput validation i could ever wish for!!!!
var NoteVal = ''
var NameAry = $('#'+PersonnelBox).parent().children(":first").children("SPAN").children("SPAN");
$.each(NameAry, function(index,value){
var $n=$(value).html();
if(NoteVal.length==0) {NoteVal=$n} else {NoteVal=NoteVal+';'+$n};
});
//$('#'+AddNotes).val(NoteVal);
var plh = $('#'+PersonnelBox).parent().html()
userNameTx = $('#zz8_Menu').text();
userNameTx = userNameTx.replace('Welcome ','');
$.each(OICUsers, function(i,v){
if(plh.indexOf(v) > -1 && st=='New Request'){
$('#'+StatusBox).val('OIC Bypassed')
$('#'+CommentsBox).val('OIC is travling on this TDY/TAD and cannot approve. So this request is bypassing the "OIC Approval" step')
}
});
/*userNameTx = $('#zz8_Menu').text();
userNameTx = userNameTx.replace('Welcome ','')
$('#' + ModBox).closest('TR').show();*/
var message=''
message = detectFieldChanges(AllFieldsArray,AllOrgValArray,"Draft,New Request,Modified")
if(message.length>0){
$('#'+ModBox).val(message);
AutoResizeTextarea(ModBox);
}
message = detectFieldChanges(ValFieldsArray,OrgValuesArray,"Draft,New Request,Modified,OIC Approved,OIC Bypassed,Pending RFI,Ready for COS")
userNameTx = $('#zz8_Menu').text();
userNameTx = userNameTx.replace('Welcome ','');
if(message.length>0&&$.inArray(userNameTx,COSUsers)==-1){
$('#'+StatusBox).val('Modified').change;
$('#'+StatusLongBox).val('Modified').change;
}
//Subject box
var pb = NoteVal;
var ep = $('#'+ExtPersonnel).val();
var ab = $('#'+AddressBox).val();
var sd = $('#'+sDateBox).val();
var ed = $('#'+eDateBox).val();
var st = $('#'+StatusBox).val();
var p = pb+';'+ep;
var p = p.replace(/mossaspnetmembershipprovider:/g,'');
var p = p.slice(0,-1);
var ad = ab+' '+sd+' to '+ed;
var s = 'eTDY | '+st+' - '+p+' - '+ad;
if(s.length>255){
var l = s.length-255;
p = p.substring(0,p.length-l);
s = 'eTDY | '+p+' - '+ad;
}
$('#'+Subject).val(s);
//check Lat/Lng value
if($('#'+LatBox).val()=='' || $('#'+LngBox).val()==''){
//alert("Cannot continue unless the Lat Lng has a vallid coordinate");
if($('#LatLngError').length==0){
errorHTML='<br><span class="ms-error" id="LatLngError">You must specify a value for Lat and Lng</span>'
$('#'+AddressBox).closest('TD').append(errorHTML)
}
return -1
}
return 0
};
It is messy but hopefully you can make sense of it.
Edit 2:
I think I have tracked the randomness down... I completely turned off all custom code and still have the problem. I then tried comparing a working record with a non working record. Everything looked normal until i got to the field with a multiple people picker. If i have more than 2 people in that field it will save normal but when i go to make a modification on that record with more than 2 people in the people picker field is causes this problem. I am going to do some more research and will post my results.
Edit 3:
http://blogs.msdn.com/b/jorman/archive/2009/12/22/mystery-of-the-sharepoint-white-screens.aspx
This problem all boils down to IIS configuration and the Impersonation Level. Apparently our server admins decided to change it without telling anyone.
Usually, when you get [seemingly random] behavior from a web page (especially in MOSS), it means that you have ambiguous events defined on the page. Usually, I get this when I add some kind of JScript to a button or form on_submit.
Without seeing your code, I can't really narrow it down further than that. I recommend: look for JavaScript events on your HTML form or on your button click events or look for anchor [a] tags that point to nowhere (href=#) but have javascript. Then decide to do it (strictly) the HTML way (forms, submit buttons) or the javascript way, (no forms, no asp:button) and un-wire the other.
This problem all boils down to IIS configuration and the Impersonation Level. Apparently our server admins decided to change it without telling anyone.
http://blogs.msdn.com/b/jorman/archive/2009/12/22/mystery-of-the-sharepoint-white-screens.aspx

Ok, I've got the bit.ly link, but now the asynchronicity of jQuery is getting in the way

function dlLink(title, currentArray, currentIndex, currentOpts)
{
var img = new Image();
img.src = 'Gallery/Wallpapers/' + title;
html = img.width + ' x ' + img.height + '<br />'
+ '<a class = "nav" href = "Gallery/Wallpapers/' + title + '" target = "_blank">Download</a><br />http://';
// set up default options
var defaults = {
login: '*************',
apiKey: '*******************************',
longUrl: 'http%3A%2F%2Fschnell.dreamhosters.com%2Fwallpapers.php%3Fwp=' + title
};
// Build the URL to query
var daurl = "http://api.bit.ly/v3/shorten?"
+ "&login=" + defaults.login
+ "&apiKey=" + defaults.apiKey
+ "&longUrl=" + defaults.longUrl
+ "&format=json&callback=?";
// Utilize the bit.ly API
$.getJSON(daurl, function(results) {
$('#fancybox-title').append(results.data["url"].substr(7));
});
if(img.complete)
return html;
}
Ok, the point of this function is that it's a callback to a Fancybox that puts HTML content into it's 'title' section. In this section I put the image's resolution, a download link and a bit.ly link for coming back to the image at this website - http://schnell.dreamhosters.com/wallpapers.php?page=12 Originally I was having XMLHTTPRequest problems with the bit.ly URL, but I seem to have resolved those.
The problem now, though, is that I need the variable 'html' to have all the html content that's going into the fancybox before the return statement comes up. While it may look like everything happens before the return statement, jQuery is doing the $.getJSON() function asynchronosly and so it's not garaunteed that 'html' will have stuff in it before dlLink ends. I need a way to make it so that the order of things happens as its shown in the code, so that the $.getJSON request and the subsequent callback function will always finish what they're doing before going onto the return statement.
Edit - I figured out what to do and the code above correctly does as I wanted. See my answer below.
Ok, so I finally solved this after realizing a few things.
1 - You're kinda supposed to do all the work you can with the JSON data while in the callback function of $.getJSON().
2 - The area I was trying to put the link in had the id 'fancybox-title', so I just went ahead and said $('#fancybox-title').append(stuff);
3 - Fancybox's title (when shown on the inside at least) will only size itself for lines of text that are already there by the time the function formatting the title has finished. Anything appended to it after won't be accounted for in size and so the title area will remain the same and you'll see lines of text creep up into the picture (found this out the hard way). To get around this I made sure to add a 3rd line of text to my 'html' variable - <br />http:// This made Fancybox size its title area for 3 lines of text. Then in the callback function I used substr to take the bit.ly link starting from after http:// and to the end.

Categories