I've been trying to fix this for two hours straight and I can't figure it out.
onclick = "location='exceltest.asp?vanjaar=<%=vanjaar%>&vanmaand=<%=vanmaand%>&vandag=<%=vandag%>&totjaar=<%=totjaar%>&totmaand=<%=totmaand%>&totdag=<%=totdag%>'"
That line of code is in an < input type="button" /> attribute. The button links to a page where an Excel download should be triggered. The values in the URL are from- and to-date-parts. (year, month, day)
this:
onclick = "location='exceltest.asp?fromdate=<%=fromdate%>&todate=<%=todate%>'" />
does not work, because somehow IE7 reads the date (eg. 2008/1/1) wrong. Something to do with the slashes I think.
But when I try to click the button in IE and thus download the generated file, Internet explorer tries do download the file
exceltest.asp?vanjaar=2008vanmaand=1vandag=1totjaar=2008totmaand=2totdag=1
instead of the excel file I want.
FF offers to download the excelfile, but gives (in that excelfile) an overview of an htmlpage with an errormessage telling me my query is wrong (Item cannot be found in the collection corresponding to the requested name or ordinal.) But that CAN'T be, I'm using that exact same query elsewhere, using the same (but restarted) connection.
This is the bit of code I use to instantiate the download of the file:
Response.Buffer = TRUE
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "content-disposition", "attachment; filename=overicht.xls"
There might actually being to things going on here, but I am most insterested in why IE wants to download the asp page and FF offers the right download.
The & inside onclick="" should be html-encoded to &
If fromdate contains slashes you're probably safest to url-encode that as well (though you seem to contradict that with your example URL).
Something that might help: Server.URLEncode
fromdate=<%=Server.URLEncode(fromdate)%>
But, your Excel file error -- Item cannot be found in the collection corresponding to the requested name or ordinal. -- is from Recordset.Fields(). You're trying to grab a field that isn't available -- either a column name that isn't in your query or an index that's beyond your column count.
Related
I'm trying to display the results of a FileContentResult MVC Action in an object tag. I can easily display files that have a preview option; .txt, .pdf, .jpg, etc. The problem comes in when there are files that don't have a preview option. My problem isn't figuring out which type of files work, my problem is figuring out how to stop them from downloading (or trying to download).I've tried making an ajax call to grab the file, which I can do, but I don't know how to display it after that. Any tips or ideas? This is the object I get back from the jquery call.
It's essentially just the mimetype, the name, and the byte array. Here's a snap of the object in MVC:This doesn't seem like it should be as hard as it seems. Am I just missing something obvious? Thanks!
I realized what I could do in order to get around this problem, I won't submit this as the answer in case other people actually do have ideas on how to work around this. I think my solution is pretty self-explanatory, but I'll go into a little detail.
public ActionResult GetFile()
{
HBSFile file = new Common.Business.FileIO.FileIO(Server.MapPath("~/Content/Images"), "testdoc.docx").Read();
if (file.CanBePreviewed)
{
return File(file.Stream, file.ContentType);//, file.FileName + "." + file.Extension);
}
return null;
//return Json(new Test(File(file.Stream, file.ContentType, file.FileName + "." + file.Extension), file.CanBePreviewed), JsonRequestBehavior.AllowGet);
}
The HBSFile object is simply the properties of the file. file.Stream is a byte array. To get around my problem, I simply check to see if the file can be previewed or not. If it can be, I'll return a FileContentResult.
Background:
I am making a simple game in PHP, JavaScript and HTML for the web. A player control movements of a box on the screen, and see others fly around with their boxes.
I have the following files, that I upload to my domain via a hosting company:
index.html: a file with some buttons (eg. to start the game) and frames (for putting boxes in).
server.php: PHP script that receives messages from client, performs reads/writes to a database, echoes (using echo) boxes from database to the client. Does not echo the box of the player the message came from.
database.txt: a JSON text file containing data of players and the next free ID number. When empty it looks like this: {"players":[], "id": 1}. players contain objects with values such as ID, position and rotation.
script.js: JavaScript file with script to send/receive messages, display data from messages etc. Linked to index.html. Moves your box.
A screenshot, two players in movement:
Problem: The game crashes, always. Sooner or later. This is what happens:
Client recevies player data from server.php, everything is fine. This could be for 10 seconds or up to some minutes.
The data starts to falter, the message sometimes is null instead of actual data.
The data recevied is always null. The database file is now {"players":null,"id":5}. (The "id" could be any number, does not have to be 5).
Picture of data flow, printing of players from database. Two players. Before this screenshot lots of rows with valid data. Then as seen two null messages. Then after a while null forever.
I am not completely sure where the problem is, but I am guessing it has to do with my read/write in server.php. I feels like a lot of player movement makes the program more likely to crash. Also how often the program sends data affetcs.
Code Piece 1: This is code from server.php, that writes to the database. I have some sort of semaphore (the flock( ... ) ) to prevent clients from reading/writing at the same time (causing errors). I have an other function, read, which is very similar to this. Possible problems here:
The semaphore is incorrect.
The mode for fopen() is incorrect. See PHP docs. The mode w is for write. The tag b is for "If you do not specify the 'b' flag when working with binary files, you may experience strange problems with your data ...".
Something weird happening because I use read() in my writing function?
Code:
// Write $val to $obj in database JSON
function write($obj,$val){
$content = read();
$json = json_decode($content);
$json->{$obj} = $val; // eg. $json->{'id'} = 5;
$myfile = fopen("database.txt", "wb") or die("Unable to open file!");
if(flock($myfile, LOCK_EX|LOCK_NB)) {
fwrite($myfile,json_encode($json));
flock($myfile, LOCK_UN);
}
fclose($myfile);
}
Code Piece 2: This is my code to send data. It is called via a setInterval(). In script.js:
// Send message to server.php, call callback with answer
function communicate(messageFunc,callback){
var message = messageFunc();
if (window.XMLHttpRequest) {
var xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange= function() {
if (this.readyState==4 && this.status==200) {
callback(this.responseText);
}
}
xmlhttp.open("GET","server.php?msg="+message,true);
xmlhttp.send();
}
This is my code to receive data, in server.php: $receive = $_GET["msg"].
My current work of solving
This is what I have done so far, but nothing has changed:
Added mode b to fopen().
Added flock() to read/write functions in server.php.
Much reworking on script.js, I would say it looks/works very clean.
Check memory_get_peak_usage(), and check with the hosting company for memory limits. Should be no problem at all.
Looked at PHP garbage collecting and gc_enable() (I don't know why that would change anything).
Lots of testing, looking at the data flow.
Crying.
Conclusion: Is this type of application what PHP is for? What do you think is wrong? If you want more code/info I provide. Thank you very much.
Here is the root of your problem:
$myfile = fopen("database.txt", "wb") or die("Unable to open file!");
Note the behavior of the w open mode (emphasis mine):
Open for writing only; place the file pointer at the beginning of the file and truncate the file to zero length. If the file does not exist, attempt to create it.
This happens before you lock the file. What's happening is that between this fopen() call and the following flock() call, the file's content is zero length, and a reader is coming along during that time and reading the empty file.
Why doesn't this cause an error in PHP when you parse the empty string as JSON? Because json_decode() is defective, and returns null when the input is not valid JSON rather than throwing an exception. Nevermind that the string "null" is valid JSON -- json_decode() gives you no way to differentiate between the cases of valid input representing the null value and invalid input. If json_decode() actually threw an exception or triggered a PHP error (don't ask me why two error-signalling mechanisms are necessary in PHP), you would have a fantastic point to start debugging to figure out why the file is empty, and you might have solved this problem by now!
... sigh ...
PHP's "design" gives me headaches. But I digress.
To fix this whole problem, change the open mode to "cb" and ftruncate($myfile, 0) after you successfully acquire the lock.
Note the behavior of the c mode, which actually specifically mentions the approach you are using (emphasis mine):
Open the file for writing only. If the file does not exist, it is created. If it exists, it is neither truncated (as opposed to 'w'), nor the call to this function fails (as is the case with 'x'). The file pointer is positioned on the beginning of the file. This may be useful if it's desired to get an advisory lock (see flock()) before attempting to modify the file, as using 'w' could truncate the file before the lock was obtained (if truncation is desired, ftruncate() can be used after the lock is requested).
I have a html page with some buttons, one of my buttons is as following:
<input class="contentLink" type="button" value="Questionnaire" onclick="validate(<?php urlencode('/my-site/Tools/Learning_Strategies/Questionnaire.php'); ?>)"/>
Essentially when this button is clicked, it passes the urlencoded-string literal '/my-site/Tools/Learning_Strategies/Questionnaire.php' into the javascript method validate:
function validate(url){
alert(url);
location.href="/my-site/Session/redirectMe.php?loc="+url;
}
What I am trying to do is get '/my-site/Session/Questionnaire.php' from the html page accessible from the redirectMe.php. This is being setup in the
location.href="/my-site/Session/redirectMe.php?loc="+url;
which leads to my redirectMe.php file:
<?php
require "SessionAuthenticator.php";
Session_start();
if(validateSession()===true){//validateSession() is defined inside SessionAuthenticator.php
echo $_GET["loc"];
//header("Location: ".$_GET["loc"]);
}else{
header("Location: /my-site/LoginPage/index.php");
}
?>
The issue is during both of the alert and echo, the encoded string literal came out as "undefined", which means the following line:
header("Location: ".$_GET["loc"]);
will really look like this:
header("Location: undefined");
And therefore look for 'undefined' in the current directory and break the website.
This all works perfectly if there is no encoding as following:
<input class="contentLink" type="button" value="Questionnaire" onclick="validate('/my-site/Tools/Learning_Strategies/Questionnaire.php')"/>
But... No encoding is bad right?
If you are wondering why you don't see a decode method being used...
The webserver will arrange for $_GET to have been urldecoded once already by the time it reaches you! - Matt Johnson ¶ # http://php.net/manual/en/function.urldecode.php#48481
Require and include will not work, as redirectMe.php would be executed before the user even sees the page. This should only happen when the user clicks the button. That is why I am using a javascript function to start redirectMe.php.
I've tried ajax, however this didn't work. After talking with an experienced programmer who I know personally, I've been told that ajax can't help me here. This because Ajax would be redirected to '/my-site/Tools/Learning_Strategies/Questionnaire.php', but not the client (User).
To clearly state my question:
Why is the urlencoded coming up as 'undefined' when echo-ed/alert-ed? How do I fix this?
As for programs/web servers/etc I am using...
Sublime 3 (text editor)
Wamp (64BIT)(all-in-one package) # http://www.wampserver.com/en/
Apache 2.4.17
PHP 7
MySQL 5.7.9
I am open to other means of getting what I am trying to do done.
However, I am not open to changing web servers/programs etc (except sublime 3 since it is just a text editor.... but why would that need to be required?).
Furthermore, whatever means of getting this done needs to support the browsers/platforms as stated below.
The website must support:
(Browsers)
IE 8 and up, and latest versions of Microsoft Edge, Firefox, Chrome and Safari.
Cross-Platform:
Windows 7 and up, and the latest versions of Mac OS, IOS and Android
Why is the urlencoded coming up as 'undefined' when echo-ed/alert-ed?
Because the PHP doesn't output anything.
<input class="contentLink" type="button" value="Questionnaire" onclick="validate(<?php urlencode('/my-site/Tools/Learning_Strategies/Questionnaire.php'); ?>)"/>
Gives you:
<input class="contentLink" type="button" value="Questionnaire" onclick="validate()"/>
… once you run it through a PHP parser.
You need to:
echo the result so something appears there
wrap it in quotes (with json_encode so any escaping needed is also taken care of) so that it will be treated as a string and not a variable name.
This topis is already present in other posts but none of the solutions mentioned worked for me so here I am, hoping someone can point me in the right direction.
Basically, I have an application with Primefaces 3.5 with 2 commandButtons that execute backing bean methods to generate two different reports as an output stream (no GET available). One of this report is generated as attachment while the other one should be displayed in another tab. Both in the same form.
My problem comes with the report generated in a separate tab: since the reports share the same form, I cannot use target=blank in the form definition and since I have to do validations in my backing bean, I must show possible error messages in the main tab, opening the new one only in case everything goes smoothly.
I tried the following js in the form page:
function test() {
document.getElementById("formRep3_1").target = '_blank';
}
called by the bean with
RequestContext.getCurrentInstance().execute("test()");
after validation successful. But it doesn't work.
I also tried setting an oncomplete="test()" on report button, slightly modifying the js like this:
function test() {
var v = '<h:outputText value="#{repReqStatus.resultCheck}" />';
if (v.value == "success") {
document.getElementById("formRep3_1").target = '_blank';
}
else {
alert('no');
}
}
but it seems the oncomplete doesn't get called at all! Not even if I do another check like
oncomplete="if (!args.validationFailed){test()}"
So yeah, I'm lost. Any help is really appreciated.
Thanks!
You can't change the link's target during invoking the link's action. It's too late.
Your best bet is to keep out the target="_blank" and instead invoke a JavaScript window.open() on the desired URL. You can store the PDF report in session, or prepare request parameters for the URL so that it can generate the desired PDF report based on those request parameters.
I'm trying to make a field similar to the facebook share box where you can enter a url and it gives you data about the page, title, pictures, etc. I have set up a server side service to get the html from the page as a string and am trying to just get the page title. I tried this:
function getLinkData(link) {
link = '/Home/GetStringFromURL?url=' + link;
$.ajax({
url: link,
success: function (data) {
$('#result').html($(data).find('title').html());
$('#result').fadeIn('slow');
}
});
}
which doesn't work, however the following does:
$(data).appendTo('#result')
var title = $('#result').find('title').html();
$('#result').html(title);
$('#result').fadeIn('slow');
but I don't want to write all the HTML to the page as in some case it redirects and does all sorts of nasty things. Any ideas?
Thanks
Ben
Try using filter rather than find:
$('#result').html($(data).filter('title').html());
To do this with jQuery, .filter is what you need (as lonesomeday pointed out):
$("#result").text($(data).filter("title").text());
However do not insert the HTML of the foreign document into your page. This will leave your site open to XSS attacks.
As has been pointed out, this depends on the browser's innerHTML implementation, so it does not work consistently.
Even better is to do all the relevant HTML processing on the server. Sending only the relevant information to your JS will make the client code vastly simpler and faster. You can whitelist safe/desired tags/attributes without ever worrying about dangerous ish getting sent to your users. Processing the HTML on the server will not slow down your site. Your language already has excellent HTML parsers, why not use them?.
When you place an entire HTML document into a jQuery object, all but the content of the <body> gets stripped away.
If all you need is the content of the <title>, you could try a simple regex:
var title = /<title>([^<]+)<\/title>/.exec(dat)[ 1 ];
alert(title);
Or using .split():
var title = dat.split( '<title>' )[1].split( '</title>' )[0];
alert(title);
The alternative is to look for the title yourself. Fortunately, unlike most parse your own html questions, finding the title is very easy because it doesn;t allow any nested elements. Look in the string for something like <title>(.*)</title> and you should be set.
(yes yes yes I know never use regex on html, but this is an exceptionally simple case)