I was wondering if there was any way to create something like a txt file in Ajax. I'm using this to save logs created by the user on my site, this is the link if its helpful: site. If this cannot be done with ajax can it be done with cookies? Or would the log be to big for cookies? Thanks(sorry if this is a duplicate, some I looked around and everything was about loading/reading from a file).
AJAX is just making asynchronus HTTP calls on the browser.
So, can you create a file just making an ajax call? No. You would need to setup somekind of script on the server that will handle the file creation and writing and call that script with AJAX.
The short answer is - no. You can not do this DIRECTLY with AJAX.
The longer answer is - what you are looking for should be done using a database and SQL. Not that PHP couldn't do it directly - but a good database is better able to handle this problem.
AJAX is mainly used to just send and receive messages, files, etc... It isn't for storing anything. With that being said, the steps would be to have a small PHP script that just reads and writes to a database and make that database be a log file. So your SQL database (I'd just call it log) would have two entries. These are the date the log entry went into it and the entry itself. You could also throw in last_accessed if you want or other fields you think you might need. Your PHP script, in its simplest form, would open the database and, depending upon whether you send it a "GET" or "PUT" command it would read from or write to the log file. If it writes to the log file, it sends back an ACK or NAK (meaning everything is ok or the program had a problem). If it is reading from the log file, you supply how many lines you want to read and the PHP script either sends back the lines or a NAK again to signify something went wrong. You can also replace the simple NAK with the actual error if you want but then your customers are seeing the error. Better to have just a generic "There has been a problem, we have contacted our system people and the site should be back up shortly" kind of message. Save the actual errors for you to see via e-mail.
That's it. You should be able to write this in about ten to fifteen minutes and have your log file readily available to you in no time.
Related
This is wat needs to happen:
I need to get user information out a MySql database.
But i don't want to insert the password of my database in the php file. Because that file won't be hosted on my own server. Nobody must see that password when they access the server by ftp and edit the php file.
My first solution that didn't work was opening a php file from my own host and reading the output (i made a script that connects to the database and outputs a long string) and converted the output to an array by splitting the values.
This did not work because of security reasons in php.
I can't create a extra account for my database that has read-only access because my host won't allow me. (hostinger.co.uk)
I also thought about using a iFrame and load the file on my host. And read it using javascript to read it. But again, security won't allow me to edit it.
Does someone know a way to fix this?
OPTION 1:
Since you want to make sure your buddies server doesn't have access to the MySQL server info (username, password, etc), your safest bet is to connect to the database from your server, and just communicate between the two servers what needs to be retrieved.
As Darren mentioned in the comments, an API would do this just fine. Since there are a lot of open source libraries out there that can get the job done, I will recommend you one: pheanstalk
pheanstalk is a php client that works on top of the beanstalk library, which is basically a queue.
You could set up a queue on each server, and configure the communication to happen between the 2 servers. Then you would have worker.php scripts running every second (or 10 seconds or however so often you like) looking for commands being sent from 1 server, taking those commands in, processing them, and sending back the information to the main computer.
OPTION 2:
Instead of accessing your database, you can create a copy of yours, and have his server contain a copy.
Key points of option 2:
If his server isn't capable of carrying a full fledged MySQL database, there is MySQLi, which is very similar, but the only difference is that it is basically a file that you keep in your server. That is the benefit since it is LIGHT (hence the "i" from MySQLi). The downside is that the database isn't as "powerful", some operations might be limited, though that is to be expected, but good none the less.
If your friend has a database however, then better yet since it will have all the capabilities.
Now since I am assuming you would need to keep their copy of your database up-to-date, you can create a function that would send a request to your buddies server on what was updated. This is an API since it is intercommunication between processes behind the scenes, but probably wouldn't need any root access as some other API's might require.
Though the hastle here is that you would literally have to call that function every time you do any updates... :(
Edited:
OPTION 3
After talking a bit with the OP in the comments, another possibility came up. In his particular case, he might be willing to have a file in a public directory available for his buddies user to read. For example, lets say his file was located in:
http://www.example.com/hiddenfiles/dfjios4wr238##.txt
To access what is inside that file, you would have to know the name (and the name was specifically designed to work as a password, hence even though the information isn't sensative for the OP's specific situation, it's always best practice to stay consistent and think safe xD).
To access the file, the following could be done:
$path = 'http://www.example.com/hiddenfiles/dfjios4wr238##.txt';
$fileHandle = fopen($path, "r");
while ($line = fgets($fileHandle))
{
echo "--> {$line}";
}
fclose();
I have an AJAX call that is running a long PHP script where it has 20 different results, I would like to show when each step in the script is done.
Like so 1/20 done, 2/20 done, 3/20 done.
Latest 29-12-2015 03:17.
I tried to create the JSON file as so (jsonFileName_uniqueTimeStampHere.json) by PHP, but the time taken to create the file with PHP, result in a 404 file not found error!
Because when the AJAX call is running it comes to the progress call before the file has been created, I know I can't create the file with JavaScript but is there anyway to create.
The file before the success callback from jQuery AJAX?
What would be the best way to show progress information while AJAX call is running.
The way I have it now, I have a JSON file saved on the server that gets updated with the latest state that has completed, but if multiple users is running the same script the JSON file with the state gets overwritten.
Should I save the state of each progress in DB and then receive it with multiple calls to a PHP method that get state that has been completed?
Should I keep using the current method I use and add a userID to the JSON file so it is unique on each call to the file?
How should I go about doing it the same way as Seositecheckup?
What is the best way to make a progress with AJAX and PHP?
Please tell me if you need any more information.
I have looked around and don't feel like the info or half of info, there is to find online has been enough to do this myself.
I would like to use jQuery AJAX and not XMLHttpRequest, I'm looking for something similar to seositecheckup.com, when you scan a page you can see the state update on each completed function in the console and is done with different AJAX calls. How is that possible?
Should I forget about using jQuery and keep focus on plain JavaScript instead?
Right now I have a setup with jQuery that works the problem is, that I use a JSON file to get the result from and it gets overwritten when multiple users request the same script, is it possible to store the state in db instead and receive it from there with some unique identifier?
In the future I would like to make it possible to put the script into a queue that could be run and when the script ends it should send an e-mail to the user.
The HTTP way of handling requests that may take a long time is for requests to return a 202 and the body of the response should contain the URL where the user can query for the result.
#Request
POST /some/entitities
...
#Response
HTTP/1.0 202 Accepted
/jobs/{jobId}
The user can then poll /jobs/{jobId} which can return a number to represent progress. Do you have to use this? No, but if you do, others developers can immediately recognize what is going on.
Even if you don't use the approach I recommend, you will also have to keep track of job progress in your database and have a separate AJAX call to find out the current progress.
First of all: sorry for my bad grammer. English isn't my native language, but i will try to exlpain my problem as simple as i can.
I'm working on a web-application, where user can enter a link. (Question 1) This link should be send to the server/servlet and will be progressed to other things. (Question 2) After the progression, the servlet will send a json-array (?) back to the javascript-part of my app.
I'm completly new to this kind of stuff, but its very important to me, to find out how this works or better, how i can make this work. Its actually very simple, but i used plenty of weeks and cant figure it out.
The application is using the SAP UI5-libs (Question 3), where i would also like to know, if there is any possible way, to parse JSON with the UI5 libs.
I hope, i could explain my problem good enough, so i can get some help. Thanks to all!
The 'sending' of the string to the server/servlet would happen via ajax in either POST or GET form. That is up to you.
I recommend you use a javascript plugin like jQuery (JQuery Ajax API) because the regular ajax code is a bit messy.
As for the servlet/server communicating back to the client is as simple as writing to the page. In a typical servlet context it would be something like
out.print("This is a message");
where Ajax automatically returns the content of the entire page upon callback.
So in conclusion:
Consider test.jsp your servlet. I wish to send "Hi" from the client (being the browser) via GET to the servlet and I want the servlet to say "Hello" back.
I would open an ajax request of type GET to the url "test.jsp?param=Hi". In the servlet I receive this page request and process it. The servlet discards the parameter because it is not used and outputs "Hello" to the page.
In the client the ajax will have returned "Hello" and I can use this to put it into a var or whatever and all of this happened while not refreshing and not navigating in the original document where I did the javascript.
Another way is using websockets where you basically use sockets in javascript to send and receive any kind of data.
Also please check out this possible duplicate question: How to send a string to a servlet from javascript using xmlhttprequest
I'm currently creating an image hosting script and so far so good. I've used several plugins to create the local uploading process with drag & drog + AJAX which works totally fine. Now I've moved to the part where I need to create the remote uploading process with jQuery AJAX and a PHP script to handle the whole thing.
How it's gonna work
My thought are like this: There is a big box in the middle of the page that accepts the URLs to be remote uploaded. Once valid URL(s) are passed into the text area, they will be immediately sent to the server side script via jQuery AJAX. It's bound with a keyup event.
This is how it looks like: http://i.imgur.com/NhkLKii.png.
The "HERE COME THE URLS" part is already a text area - So that part's already done.
Where I need help
The issue with this whole situation is: Once there are valid URLs pasted into the text area, those must be immediately be converted to some sort of box which also includes an uploading progress. Something that looks like this (copied from the local uploading part): http://i.imgur.com/q7RyDmb.png
It was easy implement the progress indicator for the local uploading, since it was a feature offered by the plugin I've used, but I don't know how to indicate the progress of remote uploading, which is totally being made from scratch.
So this is how I've imagined the logic to flow:
User pastes some URLs into the text area
There is a client-side check to validate the pasted URLs
Validated URLs are send to upload.php on keyup (?)
URLs are being processed
While the upload goes on, we show the users the progress in the knob (?)
PHP script finishes the process and returns back the uploaded URLs
I update the page in the AJAX success callback to display the uploaded files
So, the two process flows marked with (?) are unclear to me - I don't know how to achieve those...
What I have tried
Well, I didn't just come here and ask you to do everything for me, but I've come across a dead end and I don't know how to continue. What I've done so far is collect the URLs from the text area, and if there are multiple URLs separated by a line break (\n), I simply use split to get an array of pasted text and then use another function inside the loop to validate if they are URLs. If there is no line break detected inside the text area value, then I simply check the one line that was provided. On each case, I send the whole text area to the PHP script, because I don't know how to get rid of the invalid URLs in jQuery. I've created a function called debug() in PHP which stores anything into a debug.log file and this is what I'm getting (in one try) when I paste something into the text area:
https://www.google.com/https://www.google.com/
I paste https://www.google.com/ once in the text area, but it gets logged twice in the PHP side and I can't determine why.
This is how my jQuery looks like:
// Remote upload
var char_start = 10;
var index = 0;
var urls = $('.remote-area');
var val_ary = [];
urls.keyup(function(){
if (urls.val().length >= char_start)
{
var has_lbrs = /\r|\n/i.test(urls.val());
val_ary = urls.val().split('\n');
if (has_lbrs)
{
for (var i = 0; i < val_ary.length; i++)
{
if (!validate_url(val_ary[i]))
{
val_ary.splice(i, 1);
continue;
}
}
$.ajax({
type: 'POST',
url: 'upload.php',
data: {
upload_type: 'remote', // Used to determine the upload type in PHP
urls: val_ary, // Sending the whole array here
},
});
}
else
{
if (!validate_url(urls.val()))
{
// Display an error here
return;
}
$.ajax({
type: 'POST',
url: 'upload.php',
data: {
upload_type: 'remote', // Used to determine the upload type in PHP
urls: urls.val(), // Sending what's in the text area
},
});
}
}
});
The questions
So the final questions are:
How do I send my information correctly to the PHP script, only valid URLs and have them kind of "process-able" in my PHP script.
How do I indicate the progress of the upload?
If I was somewhere unclear during my question, please let me know, I'll try to reexplain.
Thank you.
Updates
09/12/2013
I think I have managed to solve the double-sending issue where my AJAX would send the same information twice to the PHP script. What I did was code in a delay anonymous function that sends the text area content to the PHP script after an user stops typing for 2 seconds. Once the user stops typing again, the timer resets and a new AJAX request will be made. So, I'm assuming that this issue has been solved. I'll come back to it if anything strange occurs.
Now I'm still left with the progress indicators part. I'd appreciate your thoughts on that one.
My new code: http://pastebin.com/SaFSLeE9
What you're looking for in terms of communicating progress back and forth is "pushing". That refers to the technique of server sending data to the client, rather than the other way around, which is the standard HTTP way of doing things.
You've got plenty of options available, as described in the explanatory Wikipedia article, though perhaps more relevant to this topic would be Comet. What happens is you trigger and $.ajax call just like the one you have now, but you set a very long timeout. That essentially gives the server a "channel" to send data back to the page whenever it's available.
So what you need is a .php on the server that is capable of handling long polling and will send data back to the page as the upload progress changes (probably in array form for multiple uploads). This article should get you started with some jQuery code. Just remember that this request doesn't go to upload.php. This request goes to a different script that deals solely with upload percentages and only returns data when that is available, it doesn't return immediately as all others scripts - the Ajax will happily wait for the data.
Also, don't separate your code like that with has_lbrs. One line or many are not distinct cases, one line is just an edge case of many lines. You're duplicating the code unnecessarily. What does the else case do that would break in the general case? Further, the "error handling" in the else case is misleading. The only error reporting you do is if there is only one line and it's wrong. What if you have two lines and they're both wrong? Your code will happily send an empty array to upload.php.
This is why I think you shouldn't separate your code like that, because then you'll split logic and not even notice it.
In my opinoin, the best way is to call your cURL script with ajax and use it to upload your files on remote server. You need ajax.js, curl.php, index.php (whatever name you want) on your app server. And image.php, class.image.php (whatever name you want) on your remote server.
Steps that I did for my app
1) I am going to upload an image from my index.php file. It will call curl.php file using ajax.js and the cURL file will check file's extension and all (for your app's security, make sure what you want to allow users to upload).
2) Now the curl file will upload the file to your pre defined temporary folder with the default file name.
3) Now if move_uploaded_file function (which I used in my script) run successfully, you can call your cURL function to send your data as post on your remote server, where image file will receive posts and will process further. You can keep your class in image.php or you can create two PHP files on your remote server, as you want.
4) Now in your class file, you should check file once again that it is image file (and whatever you want to allow) or not for better security. If file is good, process to rename it and add file into folder if you want to.
5) Add file's new name and folder name into your database by using remote database connection. So, cURL will show you result on the same page.
Now, why cURL? I prefer cURL because, you can add secret key or API for your communication to make it more secure, with if else conditions. Your remote server file which is going to receive all posts, will check if API == 'yourKey' then will process other wise it wont process and nobody will be able to send images on your server with bots and all.
I don't know that my answer is going to help you or not, probably my method is lengthy or not good for your app, but try to Google about cURL and you will understand what I am trying to say. Hope you like it and understood it. If any doubt, you can ask me any time.
I need to do as much as possible on the client side. In more details, I would like to use JavaScript to code an interface (which displays information to the user and which accepts and processes response from the user). I would like to use the web serve just to take a date file from there and then to send a modified data file back. In this respect I would like to know if the following is possible in JavaScript:
Can JavaScript read content of a external web page? In other words, on my local machine I run JavaScript which reads content of a given web page.
Can JavaScript process values filled in a HTML form? In other words, I use HTML and JavaScript to generate an HTML form. User is supposed to fill in the form and press a "Submit" button. Then data should be sent to the original HTML file (not to a web server). Then this data should be processed by JavaScript.
In the very end JavaScript will generate a local data-file and I want to send this file to a PHP web server. Can I do it with JavaScript?
Can I initiate an execution of a local program from JavaScript. To be more specific, the local program is written in Python.
I will appreciate any comments and answers.
It could technically, but can't in reality due to the same origin policy. This applies to both reading and writing external content. The best you can do is load an iframe with a different domain's page in it - but you can't access it programmatically. You can work around this in IE, see Andy E's answer.
Yes for the first part, mmmm not really for the second part - you can submit a form to a HTML page and read GET arguments using Javascript, but it's very limited (recommended maximum size of data around 1024 bytes). You should probably have all the intelligence on one page.
You can generate a file locally for the user to download using Downloadify. Generating a file and uploading it to a server won't be possible without user interaction. Generating data and sending it to a server as POST data should be possible, though.
This is very, very difficult. Due to security restrictions, in most browsers, it's mostly not possible without installing an extension or similar. Your best bet might be Internet Explorer's proprietary scripting languages (WScript, VBScript) in conjuction with the "security zones" model but I doubt whether the execution of local files is possible even there nowadays.
Using Internet Explorer with a local file, you can do some of what you're trying to do:
It's true that pages are limited by the same origin policy (see Pekka's link). But this can be worked around in IE using the WinHttpRequest COM interface.
As Pekka mentioned, the best you can manage is GET requests (using window.location.search). POST request variables are completely unobtainable.
You can use the COM interface for FileSystemObject to read & write local text files.
You can use the WScript.Shell interface's Exec method to execute a local program.
So just about everything you asked is attainable, if you're willing to use Internet Explorer. The COM interfaces will require explicit permission to run (a la the yellow alert bar that appears). You could also look at creating a Windows Desktop Gadget (Vista or Win 7) or a HTML Application (HTA) to achieve your goal.
Failing all that, turn your computer into a real server using XAMPP and write your pages in PHP.
see i got what you want to do
best things is do following
choose a javascript library (eg:jquery,dojo,yui etc), i use jquery.this will decrease some of your load
inspite of saving forms data in in a local file, store them in local variables process them and send them to server (for further processing like adding/updating database etc) using XMLHttp request, and when webservice returns data process that data and update dom.
i am showing you a sample
--this is dom
Name:<input type='text' id='name' />
<a href='javascript:void(0)' onClick='submit()'>Submit Form</a>
<br>
<div id='target'></div>
--this is js
function submit()
{
var _name=$('#name').val();// collect text box's data
//now validate it or do any thing you want
callWebservice(_name,_suc,_err);
//above call service fn has to be created by you where you send this data
//this function automatically do xmlHttprequest etc for you
//you have to create it ur self
}
//call this fn when data is sucessfully returned from server
function _suc(data)
{
//webservice has returned data sucessefully
//data= data from server, may be in this case= "Hello user Name"; (name = filled in input box);
//update this data in target div(manipulate dom with new data);
$('#target').html(data);
}
function _err()
{
//call this fn when error occurs on server
}
// in reality most of the work is done using json. i have shown u the basic idea of how to use js to manipulate dom and call servcies and do rest things. this way we avoid page-reloads and new data is visible to viewer
I would answer saying there's a lot you can do, but then in the comment to the OP, you say "I would like to program a group game."
And so, my answer becomes only do on the client side what you are able and willing to double check on the server side. Never Trust the Client!
And I do not want to do my job twice.
If you are going to do things on the client side, you will have to do it twice, or else be subject to rampant cheating.
We had the same question when we started our project.In the end we moved everything we could on the JS side. Here's our stack:
The backend receives and send JSON data exclusively.We use Erlang, but Python would be the same. It handles the authentication/security and the storage.
The frontend, is in HTML+CSS for visual elements and JS for the logic.A JS template engine converts the JSON into HTML. We've built PURE, but there are plenty of others available. MVC can be an overkill on the browser side, but IMO using a template engine is the least separation you can do.
The response time is amazing. Once the page and the JS/CSS are loaded(fresh or from the cache), only the data cross the network for each request.