jquery.get returning php code? - javascript

I am trying to use jquery's ajax $.get(...) function to send a request to my server and have it return some data. I am using the following code:
$.get("php/getRocks.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
Instead of getting the the data back, it just returns the entire php file as a string. Am I doing something wrong? Thanks for the help.

Is PHP installed on your server? This is a server issue. For some reason your .php file isn't being handled properly and it is returning the PHP code in plain text.
This is in response to:
Well, I seem to have solved the
problem, sort of. Apparently, if I
access the site localy, php doesn't
work, but if I use the domain name, it
does. Anyone know why? Or better yet,
a way to fix this?
Thanks to everyone for the help!
When working locally (and it always is a good idea to do so before uploading to a live environment) you need to setup PHP on your computer so that it can run the pages you require. A browser will not do it for you as it is a server side technology. You can download a package like Uniform Server, that will give you a full server environment for you to work with.

I have the same problem (using MAMP on mac), and while I haven't solved it, I am a step closer.
Basically, it would appear to have something to do with subdirectories/document root. If I set my url as getRocks.php (and move my script there), it works (I get content back), but if I get it as php/getRocks.php, it does not work (I get the php code back).
Perhaps MAMP is doing something add with response types within subdirectories? Am going to take a further look, but hopefully this helps lead you in the right direction.

Well, I seem to have solved the problem, sort of. Apparently, if I access the site localy, php doesn't work, but if I use the domain name, it does. Anyone know why? Or better yet, a way to fix this?
Thanks to everyone for the help!

1st. make sure you have php installed
If you are using linux / apache2 and php 5
u need to compile/install apache and load php via dso
eg:
LoadModule php5_module modules/libphp5.so
In my humble opinion it has got nothing todo with your jQuery but your web server installation/config:
If it is apache make sure you add this line in your conf file:
AddType application/x-httpd-php .php
More reading about php and apache if you are using php anad apache in linux/nix eg: http://dan.drydog.com/apache2php.html

Related

Confusion regarding Apache document root

In one of the applications that I am working on for my company, I came across a weird behaviour or maybe it's just my misunderstanding and I hope I can get some clarification.
The application is served by Apache and the root is : /company/client. For every page that I visit, for example https://11.11.11.11/index.phtml, it will actually point to the file in the server /company/client/index.phtml and so on. In one of the modules of the application, it contains a move_uploaded_file php function, and the target directory is /images/example/, when the page is run, the app is trying to go to the absolute server root /images/example/ instead of /company/client/images/example/.
Also the a new windowed opened up by window.open has an img tag having src='/images/exmaple/', this points to the server root instead of /company/client/images/example/, is this expected?
Am I missing anything, or is it something to do with Apache configuration?
Additional info:
The application is served as a virtual host in conf file, with DocumentRoot "/company/client/".
The page that is executing window.open and php function is used as an Iframe inside /company/client/index.phtml
sorry for my mistake.
Thanks for the help from the everyone especially Chris G, the problem was that the code is using a GET variable incorrectly, as a result the image name isn't passed. And I got confused because someone made a mistake in the code by moving image relative to the root folder which is incorrect. That made me think that PHP is also treating path like the client side which is a mistake. I'm guessing I can conclude that the web server document root only applies to everything client side, like the url, JS, HTML?

post not finding php file on local server.

I'm trying to use an post call to a get some data from a php file. I know the code works because I'm using it on another computer and it works fine. Every time I make a call I get this error.
HTTP404: NOT FOUND - The server has not found anything matching the requested URI (Uniform Resource Identifier).
(XHR)POST - http://localhost/PhpProject4/‪newEmptyPHP.php
This is from MS edge. The php file is in the same directory as the html file and the file making the call. I think it has to do with my xampp server. Any Ideas? Also this is all on my local machine.
Just check your .htaccess file, maybe mod_rewrite changes adress

Redirect from file based on referrer using JavaScript

Versions of this question have been posted numerous times, but none of the solutions I've found on this site have worked so far. I'm trying to redirect away from files, not web pages. I actually need to know if this is even possible, since I learned that PHP is incapable of doing this. Here's an answer from a previous question I asked:
The web server will first check if it exists and if it does, it will serve the file immediately. It does not go through any PHP code. Therefore you cannot write any PHP code that will intercept this request and block it.
We have a folder on our site with a path of /downloads/, containing files we don't want just anyone to download.
I want to put a script in our main JavaScript file that says:
If file is is /downloads/
If user comes from referrer allowed_domain.com, allow access to files in /downloads/
Else redirect to homepage or 404
My attempt (didn't work)
if (top.location.pathname === '/downloads/private.zip') {
if (document.referrer !== "http://www.allowed_domain.com") {
document.location.path = "/downloads/private.zip";
}
else {
document.location.path = "/404";
}
}
Constraints
I cannot use .htaccess. Our hosting provider is running Nginx, not Apache. I've tried using Nginx config code, but I have to send it to them to implement, and it didn't work and they won't help me.
And yes, I know that this is a super, super insecure solution for restricting access. My company is working on a more formal solution, but until then, I need to implement something temporary to deter users who lack the computer knowledge or motivation to get around the redirect, and this is pretty much my last option.
This problem is not solvable in JavaScript, even in the very limited and insecure way that you are proposing. The problem is that a request to /downloads/private.zip directly returns the contents of that file - it doesn't load any HTML page, so the browser will never see or execute that JavaScript code.
A way to solve this would be to have a PHP file that handles any request to that directory, checks whether the user has permission to see those files, and then returns the requested file or a 404. But for that you need some form of configuration, and you've already told us you can't do that either.
A third solution, one that is very silly but would work (for unsavvy users) in this very constrained situation would be to replace all links to the forbidden resources with a snippet of JavaScript that directs the user either to the file or a 404 page. However, from your question it seems very likely that you're trying to prevent access from users coming from sites outside of your control, in which case this won't work either.
Bottom line: This is not a solvable problem if you don't have the ability to configure your web server.

Why does my AJAX request give an error depending on the file extension?

I have a bit of JavaScript using jQuery that loads data with a quick $.get(url, function(response){ /* ... */}); The data is a straight up text file that is then handled by the JavaScript in that response function.
This has worked for me quite nicely, but I just ran into this problem on my machine: Using the same code, I now get an error saying:
XML Parsing Error: not well-formed Location:
moz-nullprincipal:{74091275-3d54-4959-9613-5005459421ce} Line Number
1, Column 16: image:tiles.png;
---------------^
If I load this from another server, it works perfectly. It's only when I host it on my own PC that I get this error (note that it previously worked perfectly on my own PC as well, which is running Ubuntu and serving the page with Apache). After much headbanging, I found that if I change the extension on the filename I'm loading, it works fine. The file was previously named "test.sprite", and that is when I got the error. If I renamed it to "test.txt" it loads fine.
This error ~seems~ to coincide with a recent upgrade on my system. I upgraded Ubuntu 10.something to 12.04. I'm assuming there was some sort of update in the Apache config that I didn't notice which is causing it to send different headers depending on the extension of the file (the two named here are identical - the .txt is actually just a symlink to the .sprite).
So I have a solution to my immediate problem, but I'd rather not bow to the system's idiosyncrasies. Any idea how I can fix this without renaming the file?
Please note that I'm not an apache expert, but I'll have a crack with pointing you in the right direction.
If undefined, the jQuery AJAX functions will assume the content-type is whatever header Apache has sent back. You can quite simply see what the response is by running your code in Chrome, opening developer tools (Ctrl + Shift + J) and choosing "Network". After clicking on the relevant request you will see the headers coming back, including the content-type.
In your Apache configuration the content-type for the sprite is probably not defined. You can add this with the following line:
AddType 'text/plain; charset=UTF-8' .sprite
This should be in a configuration file parsed by Apache - depending on your version this could be apache.conf, httpd.conf, or another file.
I hope this helps or at least points you in the right direction. Remember to configtest before restarting Apache!
Check out the content-type of the response header, make sure the header you received from the server and your local machine have the same content-type, i.e. same file type , same encoding, something like this: "content-type:text/html; charset=UTF-8".

Generate some xml in javascript, prompt user to save it

I'd like to make an XML document in JavaScript then have a save dialog appear.
It's OK if they have to click before the save can occur.
It's *not* OK if I *have* to use IE to achieve this (I don't even need to support it at all). However, Windows is a required platform (so Firefox or Chrome are the preferred browsers if I can only do this in one browser).
It's *not* OK if I need a web server. But conversely, I don't want to require the JavaScript to be run on a local file only, i.e. elevated privileges -- if possible. That is, I'd like to to run locally or on a *static* host. But just locally is OK.
It's OK to have to bend over backwards to do this. The file won't be very big, but internet access might either be there, be spotty or just not be a possibility at all -- see (3).
So far the only ideas I have seen are to save the XML to an iframe and save that document -- but it seems that you can only do this in IE? Also, that I could construct a data URI and place that in a link. My fear here is that it will just open the XML file in the window, rather than prompt the user to save it.
I know that if I require the JavaScript to be local, I can raise privileges and just directly save the file (or hopefully cause a save dialog box to appear). However, I'd much prefer a solution where I do not require raised privileges (even a Firefox 3.6 only solution).
I apologize if this offends anyone's sensibilities (for example, not supporting every browser). I basically want to write an offline application and Javascript/HTML/CSS seem to be the best candidate considering the complexity of the requirements and the time available. However, I have this single requirement of being able to save data that must be overcome before I can choose this line of development.
How about this downloadify script?
Which is based on Flash and jQuery, which can prompt you dialog box to save file in your computer.
Downloadify.create('downloadify',{
filename: function(){
return document.getElementById('filename').value;
},
data: function(){
return document.getElementById('data').value;
},
onComplete: function(){
alert('Your File Has Been Saved!');
},
onCancel: function(){
alert('You have cancelled the saving of this file.');
},
onError: function(){
alert('You must put something in the File Contents or there will be nothing to save!');
},
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100,
height: 30,
transparent: true,
append: false
});
Using a base64 encoded data URI, this is possible with only html & js. What you can do is encode the data that you want to save (in your case, a string of XML data) into base64, using a js library like jquery-base64 by carlo. Then put the encoded string into a link, and add your link to the DOM.
Example using the library I mentioned (as well as jquery):
<html>
<head>
<title>Example</title>
</head>
<body>
<script>
//include jquery and jquery-base64 here (or whatever library you want to use)
document.write('click to make save dialog');
</script>
</body>
</html>
...and remember to make the content-type something like application/octet-stream so the browser doesn't try to open it.
Warning: some older IE versions don't support base64, but you said that didn't matter, so this should work fine for you.
Without any more insight into your specific requirements, I would not recommend a pure Javascript/HTML solution. From a user perspective you would probably get the best results writing a native application. However if it will be faster to use Javascript/HTML, I recommend using a local application hosting a lightweight web server to serve up your content. That way you can cleanly handle the file saving server-side while focusing the bulk of your effort on the front-end application.
You can code up a web server in - for example - Python or Ruby using very few lines of code and without 3rd party libraries. For example, see:
Making a simple web server in python
WEBrick - Writing a custom servlet
python-trick-really-little-http-server - This one is really simple, and will easily let you server up all of your HTML/CSS/JS files:
"""
Serves files out of its current directory.
Doesn't handle POST requests.
"""
import SocketServer
import SimpleHTTPServer
PORT = 8080
def move():
""" sample function to be called via a URL"""
return 'hi'
class CustomHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
#Sample values in self for URL: http://localhost:8080/jsxmlrpc-0.3/
#self.path '/jsxmlrpc-0.3/'
#self.raw_requestline 'GET /jsxmlrpc-0.3/ HTTP/1.1rn'
#self.client_address ('127.0.0.1', 3727)
if self.path=='/move':
#This URL will trigger our sample function and send what it returns back to the browser
self.send_response(200)
self.send_header('Content-type','text/html')
self.end_headers()
self.wfile.write(move()) #call sample function here
return
else:
#serve files, and directory listings by following self.path from
#current working directory
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
httpd = SocketServer.ThreadingTCPServer(('localhost', PORT),CustomHandler)
print "serving at port", PORT
httpd.serve_forever()
Finally - Depending on who will be using your application, you also have the option of compiling a Python program into a Frozen Binary so the end user does not have to have Python installed on their machine.
Javascript is not allowed to write to a local machine. Your question is similar to this one.
I suggest creating a simple desktop app.
Is localhost PHP server ok? Web traditionally can't save to hard drive because of security concerns. PHP can push files though it requires a server.
Print to PDF plugins are available for available for all browsers. Install once, print to PDF forever. Then, you can use a javascript or Flash to call a Print function.
Also, if you are developing for an environment where internet access is spotty, conwider using VB.NET or some other desktop language.
EDIT:
You can use the browser's Print function.
Are you looking for something like this?
If PHP is ok, if would be much easier.
With IE you could use document.execCommand, but I note that IE is not an option.
Here's something that looks like it might help, although it will not prompt with SaveAs dialog, https://developer.mozilla.org/en/Code_snippets/File_I%2F%2FOL.
One simple but odd way to do this that doesn't require any Flash is to create an <a/> with a data URI for its href. This even has pretty good cross-browser support, although for IE it must be at least version 8 and the URI must be < 32k. It looks like someone else on SO has more to say on the topic.
Why not use a hybrid flash for client and some server solution server-side. Most people have flash so you can default to client side to conserve resources on the server.

Categories