Form gives error when trying to append after question mark - javascript

I'm trying to send visitors to http://www.facebook.com/plugins/comments.php?href=http://google.com?c
Gives the error
The comments plugin requires an href parameter.
This part is rendered correctly: http://www.facebook.com/plugins/comments.php
but the stuff after the question mark fails to be included
<script>
function go(){
var uri = 'http://www.facebook.com/plugins/comments.php'
+ encodeURI('?href=http://google.com?c');
window.frames[0].document.body.innerHTML =
'<form target="_parent" method="get" action="'
+ uri
+ '"></form>';
window.frames[0].document.forms[0].submit();
}
</script>
<iframe onload="window.setTimeout('go()', 99)" src="about:blank" style="visibility:hidden"> </iframe>?

Change to:
var uri = 'http://www.facebook.com/plugins/comments.php?'
+ encodeURIComponent('href=http://google.com?c');
If you encode the first ? it no longer serves to separate the URL from its parameters.

Only the keys and value of the query should be encoded, not the ?,& or = as these are the characters that structure the query.
var uri = 'http://www.facebook.com/plugins/comments.php?href='
+ encodeURIComponent('http://google.com?c');

Related

how to transfer values between html pages?

I'm opening new page from anothe like this:
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
the second html page looks like this:
<div class="row contractor_data__item">
<label for="code">Номер</label>
<input type="text" name="code" id="code" disabled/>
<input type="hidden" name="documentId" id="documentId">
<input type="hidden" name="actId" id="actId">
<input type="hidden" name="actCode" id="actCode">
</div>
on the page opening in the new window I have a few fields to fill. For example, I've filled "code" field on the first page and need to fill the "code" field in the page opened. How to do this?
the second part of question is that I've filled some fields on the page opened, like documentId and need to pass it to the first page I've called this one from on close, for example or on the field filled. How to perfrorm this?
In HTML5 you can use session to pass object from page to another:
// Save data to sessionStorage
sessionStorage.setItem('key', 'value');
// Get saved data from sessionStorage
var data = sessionStorage.getItem('key');
// Remove saved data from sessionStorage
sessionStorage.removeItem('key')
For further reference you can check here
Edit:
Sample Code:
Page1.html
<!DOCTYPE html>
<html>
<head>
<title>Page1</title>
<script type="text/javascript">
sessionStorage.setItem("name","ShishirMax");
var fName = sessionStorage.getItem("name");
console.log(fName);
function myFunction(){
window.open("page2.html");
}
</script>
</head>
<body>
This is Page 1
</br>
<button onclick="myFunction()">SendThis</button>
</body>
</html>
Page2.html
<!DOCTYPE html>
<html>
<head>
<title>Page 2</title>
</head>
<body>
This is Page 2</br>
<input type="text" name="txtName" id="txtName" value="">
<script type="text/javascript">
var fName = sessionStorage.getItem("name");
console.log(fName);
document.getElementById("txtName").value = fName;
</script>
</body>
</html>
Try the following code for the test purpose.
hi if you want transfer data in some page you can use localStorage our sessionStorage in js
difference between sessionStorage clear when you close browser and localstorage will be clear only if you ask it
go refer to documentation for sintax e.g :
you value is stak in 'data' variable in this e.g
var data;
sessionStorage.setItem('nameyourvar', data);
after you can take on other page with :
sessionStorage.getItem('nameyourvar')
Use a query string. That's what they're for. Dont' forget to wrap your values in encodeURIcomponent in case they contain any special characters.
window.open("somewhere.html?firstname="+encodeURIComponent(firstname)+"&lastname="+encodeURIComponent(lastname)+"");
In the new window you can get the values from the query string like this
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var firstname = getParameterByName('firstname'); // "Bob"
var lastname = getParameterByName('lastname'); // "Dole"
Function is from here.
Since other people are mentioning localstorage, you should know that localstorage isn't supported in all browser. If you're interested in using something like that (you should really use query strings instead) you can check out this cross browser database Library I wrote.
Set your items to the database on the first page
jSQL.load(function(){
jSQL.createTable("UserData", [{FirstName: "Bob", LastName: "Dole"}]);
jSQL.persist(); // Save the data internally
});
Get your items from the second page
jSQL.load(function(){
var query = jSQL.query("SELECT * FROM `UserData`").execute();
var row = query.fetch("ASSOC");
var firstname = row.FirstName;
var lastname = row.LastName;
});
You can use GET parameters.
When you're opening second page, pass all the data you want to pass as GET parameters in the url, for example :
var billhref = "whatever.html?code=your_code&parameter2=parameter2_value" ;
var openedwidow = window.open(billhref, '', 'scrollbars=1,height='+Math.min(h, screen.availHeight)+',width='+Math.min(w, screen.availWidth)+',left='+Math.max(0, (screen.availWidth - w)/2)+',top='+Math.max(0, (screen.availHeight - h)/2));
Make a JS function to get parameters on the second page :
function getParams() {
var params = {},
pairs = document.URL.split('?')
.pop()
.split('&');
for (var i = 0, p; i < pairs.length; i++) {
p = pairs[i].split('=');
params[ p[0] ] = p[1];
}
return params;
}
Then use this function to get url parameters like this :
params = getParams();
for( var i in params ){
console.log( i + ' : ' + params[i] );
}
This will return output like :
code : your_code
parameter2 : parameter2_value
Using PHP will help you get around this problem with even shorter code
For example, in PHP, to get the parameters code, you'll just have to write :
$code = $_GET['code'];
And it will give you assign a variable named code the value you have passed in the url against code parameter( your_code in this example ).

Passing querystring from one page to another through javascript

I have two different pages. I want to send querystring from one to another. below is my sample code that i have tried
window.location.search = 'id='+hidposid.value;
window.location.href="editviewposition.aspx";
in another page i retrieve the value
cookie1 = HttpContext.Current.Request.QueryString("id") ' returns ""
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
<input type="button" id="btnQueryString" value="Send" />
Hope this will help u..
I think I'd rather do something like
window.location.href= 'editviewposition.aspx?id=' + hidposid.value;
Or is there a reason this is not possible?
Here you are passing query string not cookies
Get it like
window.location.search = '?id='+hidposid.value;
window.location.href="editviewposition.aspx";
and then in code behind
HttpContext.Current.Request.QueryString("id")

Extracting the source code of a facebook page with JavaScript

If I write code in the JavaScript console of Chrome, I can retrieve the whole HTML source code by entering:
var a = document.body.InnerHTML; alert(a);
For fb_dtsg on Facebook, I can easily extract it by writing:
var fb_dtsg = document.getElementsByName('fb_dtsg')[0].value;
Now, I am trying to extract the code "h=AfJSxEzzdTSrz-pS" from the Facebook Page. The h value is especially useful for Facebook reporting.
How can I get the h value for reporting? I don't know what the h value is; the h value is totally different when you communicate with different users. Without that h correct value, you can not report. Actually, the h value is AfXXXXXXXXXXX (11 character values after 'Af'), that is what I know.
Do you have any ideas for getting the value or any function to generate on Facebook page.
The Facebook Source snippet is below, you can view source on facebook profile, and search h=Af, you will get the value:
<code class="hidden_elem" id="ukftg4w44">
<!-- <div class="mtm mlm">
...
....
<span class="itemLabel fsm">Unfriend...</span></a></li>
<li class="uiMenuItem" data-label="Report/Block...">
<a class="itemAnchor" role="menuitem" tabindex="-1" href="/ajax/report/social.php?content_type=0&cid=1352686914&rid=1352686914&ref=http%3A%2F%2Fwww.facebook.com%2 F%3Fq&h=AfjSxEzzdTSrz-pS&from_gear=timeline" rel="dialog">
<span class="itemLabel fsm">Report/Block...</span></a></li></ul></div>
...
....
</div> -->
</code>
Please guide me. How can extract the value exactly?
I tried with following code, but the comment block prevent me to extract the code. How can extract the value which is inside comment block?
var a = document.getElementsByClassName('hidden_elem')[3].innerHTML;alert(a);
Here's my first attempt, assuming you aren't afraid of a little jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var html = $('.hidden_elem')[0].innerHTML.replace('<!--', '').replace('-->', '');
var href = $(html).find('.itemAnchor').attr('href');
var fbId = getParameterByName('h', href); // fbId = AfjSxEzzdTSrz-pS
Working Demo
EDIT: A way without jQuery:
// http://stackoverflow.com/a/5158301/74757
function getParameterByName(name, path) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(path);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
var hiddenElHtml = document.getElementsByClassName('hidden_elem')[0]
.innerHTML.replace('<!--', '').replace('-->', '');
var divObj = document.createElement('div');
divObj.innerHTML = hiddenElHtml;
var itemAnchor = divObj.getElementsByClassName('itemAnchor')[0];
var href = itemAnchor.getAttribute('href');
var fbId = getParameterByName('h', href);
Working Demo
I'd really like to offer a different solution for "uncommenting" the HTML, but I stink at regex :)

delay javascript function until after file has been uploaded on asp page

Can someone please tell me how to delay the resetting of a div background-image until a file upload has completed? All the parts individually work, however
I have to delay the setting of the background by having an alert pop up and then leave a while before clicking ok - I can't have since a user will not know how long to leave before pressing...
Any help appreciated though I should say that I briefly looked at jquery/ajax but found that it would only work in IE once before requiing a page refresh
Html...
<iframe id="MyFrame" name="MyFrame" style="display:none;"></iframe>
<form id="browseform" method="post" action="disp_photosave.asp" enctype="multipart/form-data" target="MyFrame">
<p>Please select your photo...</p>
<img src="Images/button_browse.gif">
<input type="hidden" name="tab" value="0">
<input type="file" id="upload" name="filesent" onchange="this.form.submit(); load_bk_photo()">
<input type="hidden" name="tempid" value="<%=(TId)%>">
<input type="hidden" name="side" value="<%=(strSide)%>">
<input type="hidden" name="varid" value="<%=(Request.querystring("varid"))%>">
<input type="hidden" name="prodid" value="<%=(Request.querystring("prodid"))%>">
</form>
javascript...
function load_bk_photo(){
var activeId = '<%=(activeTempStoreId)%>'
var redStr_id = "side1"
d = new Date();
time_temp = d.getTime();
photoUrl = "photos/merged_"+activeId+"_"+redStr_id+".png?"+d.getTime()
alert ("timebbb = "+time_temp )
$('#resizable-img').css('background-image','url("' + photoUrl + '")');
$('#resizable-img').css('display','block');
}
vbscript on disp_photosave.asp...
<%
Set Upload = Server.CreateObject("csASPUpload.Process")
Set Image = Server.CreateObject("csImageFile.Manage")
prodid = prodSet.Fields.Item("id").Value
redStr = "side1"
fieldPrefix = "front_"
If Upload.FileQty > 0 Then
Image.ReadVariant Upload.FileData(0)
Image.WriteFile Server.MapPath("this works ok"
Image.ResizeFit scale_width, scale_height
Image.WriteFile Server.MapPath("this works ok"
storeHeight = Image.Height
storeWidth = Image.Width
Set MyConn=Server.CreateObject("ADODB.Connection")
MyConn.Open "dsn=xxx;uid=xxx;password=xxx;"
SQLString = "this works ok"
MyConn.Execute(SQLString)
MyConn.Close
Set MyConn = Nothing
End if
%>
I also need to return the value storeHeight and storeWidth to the main page to use later so if anyone can advise me on that too.
Thanks in advance for any help.
Your load_bk_photo function has some issues (missing semi-colons, creating global variables), try changing to this:
function load_bk_photo(){
//we can use the `var` keyword once and separate each variable declaration by a comma, then finish all the declarations with a semi-colon
var activeId = '<%=(activeTempStoreId)%>',
redStr_id = "side1",
d = new Date(),
time_temp = d.getTime(),
photoUrl = "photos/merged_" + activeId + "_" + redStr_id+".png?" + time_temp;
alert ("timebbb = " + time_temp );
//you can use one `.css()` function call to do both operations
$('#resizable-img').css({
'background-image' : 'url("' + photoUrl + '")',
display : 'block'
});
}
You were creating global variables which is only necessary if you are changing the value of variables outside the scope of this function.
Onto your main question, you can set a load event handler for the <iframe> element as a callback function on your upload:
$('#MyFrame').on('load', function () {
//The iframe has loaded and you can do what you want, including get the contents of the iframe (server-response)
var response = $(this).contents().find('body').text();
});
Make sure to set this binding before the source of the <iframe> is changed.
Note that .on() is new in jQuery 1.7 and in this case is the same as .bind().
.on(): http://api.jquery.com/on
UPDATE
I don't know asp classic but if you output something like storeWidth|storeHeight in your asp code then you can get that response in you JavaScript and do what you want with it:
$('#MyFrame').on('load', function () {
//The iframe has loaded and you can do what you want, including get the contents of the iframe (server-response)
var response = $(this).contents().find('body').text().split('|');
alert(response[0] + 'x' + response[1] + 'px');
});
I would use a global callback method:
JavaScript:
window.uploadComplete = function (returnData) {
$('#resizable-img').css('background-image','url("' + returnData.photoUrl + '")');
$('#resizable-img').css('display','block');
alert(returnData.storeHeight + "|" + returnData.storeWidth);
}
And in ASP, return this to the iFrame:
<script>
parent.uploadComplete({photoUrl: "urltophoto",storeHeight: "<value from asp var>", storeWidth: "<value from asp var>"});
</script>

Use jQuery to get the file input's selected filename without the path

I used this:
$('input[type=file]').val()
to get the file name selected, but it returned the full path, as in "C:\fakepath\filename.doc". The "fakepath" part was actually there - not sure if it's supposed to be, but this is my first time working with the filename of file uploads.
How can I just get the file name (filename.doc)?
var filename = $('input[type=file]').val().split('\\').pop();
or you could just do (because it's always C:\fakepath that is added for security reasons):
var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '')
You just need to do the code below. The first [0] is to access the HTML element and second [0] is to access the first file of the file upload (I included a validation in case that there is no file):
var filename = $('input[type=file]')[0].files.length ? ('input[type=file]')[0].files[0].name : "";
Get path work with all OS
var filename = $('input[type=file]').val().replace(/.*(\/|\\)/, '');
Example
C:\fakepath\filename.doc
/var/fakepath/filename.doc
Both return
filename.doc
filename.doc
Chrome returns C:\fakepath\... for security reasons - a website should not be able to obtain information about your computer such as the path to a file on your computer.
To get just the filename portion of a string, you can use split()...
var file = path.split('\\').pop();
jsFiddle.
...or a regular expression...
var file = path.match(/\\([^\\]+)$/)[1];
jsFiddle.
...or lastIndexOf()...
var file = path.substr(path.lastIndexOf('\\') + 1);
jsFiddle.
Here is how I do it, it works pretty well.
In your HTML do:
<input type="file" name="Att_AttributeID" onchange="fileSelect(event)" class="inputField" />
Then in your js file create a simple function:
function fileSelect(id, e){
console.log(e.target.files[0].name);
}
If you're doing multiple files, you should also be able to get the list by looping over this:
e.target.files[0].name
maybe some addition for avoid fakepath:
var fileName = $('input[type=file]').val();
var clean=fileName.split('\\').pop(); // clean from C:\fakepath OR C:\fake_path
alert('clean file name : '+ fileName);
How about something like this?
var pathArray = $('input[type=file]').val().split('\\');
alert(pathArray[pathArray.length - 1]);
This alternative seems the most appropriate.
$('input[type="file"]').change(function(e){
var fileName = e.target.files[0].name;
alert('The file "' + fileName + '" has been selected.');
});
Does it have to be jquery? Or can you just use JavaScript's native yourpath.split("\\") to split the string to an array?
<script type="text/javascript">
$('#upload').on('change',function(){
// output raw value of file input
$('#filename').html($(this).val().replace(/.*(\/|\\)/, ''));
// or, manipulate it further with regex etc.
var filename = $(this).val().replace(/.*(\/|\\)/, '');
// .. do your magic
$('#filename').html(filename);
});
</script>
Get the first file from the control and then get the name of the file, it will ignore the file path on Chrome, and also will make correction of path for IE browsers. On saving the file, you have to use System.io.Path.GetFileName method to get the file name only for IE browsers
var fileUpload = $("#ContentPlaceHolder1_FileUpload_mediaFile").get(0);
var files = fileUpload.files;
var mediafilename = "";
for (var i = 0; i < files.length; i++) {
mediafilename = files[i].name;
}
Here you can call like this
Let this is my Input File control
<input type="file" title="search image" id="file" name="file" onchange="show(this)" />
Now here is my Jquery which get called once you select the file
<script type="text/javascript">
function show(input) {
var fileName = input.files[0].name;
alert('The file "' + fileName + '" has been selected.');
}
</script>
var filename=location.href.substr(location.href.lastIndexOf("/")+1);
alert(filename);
We can also remove it using match
var fileName = $('input:file').val().match(/[^\\/]*$/)[0];
$('#file-name').val(fileName);

Categories