Create a log file from jquery to txt file on server - php

I can't find on the web so I'm asking some help over here.
I'd like to create a log file, when someone press on a button it will a text to a log.txt file.
I'm just looking for the the base code based on Jquery ajax and PHP
Thanks

there is no base code for jquery logging to sever
first of, you have to decide how many times you want to call the server,
each log entry will be too much load on server,
append all to js array and post on session ending? when doe's session ends? and what if user closes browser? all the log gone? (see my suggestion bellow)
you'll have to make an endpoint on server to get log entries and append them to file, then you should think of storage, and how to organize log enries from multiple clients
I would recomend using log4javascript library with AjaxAppender, see example here, you can then use setBatchSize to send in batches or setTimed to send with time intervals, see documentation here, also you can setSendAllOnUnload to don't lose messages on browser close (in most cases).
in the server i would use log4php with LoggerAppenderRollingFile see here

I don't have to time to code it for you but here is the basic logic. You can look up how to do each item individually.
You need to add an event listener with jquery for the click event and bind it to the button.
Inside that, have an ajax request to some endpoint or script on your server that will update the log file.
When that script is executed (via the ajax call), you can have PHP open the file and append a line to it that has whatever data you want.
JavaScript:
$('button').on('click', function() {
$.ajax({
// do ajax request here
});
});
PHP:
$file = fopen("log.txt","rw");
$fileContents = fread($file, filesize("log.txt"));
fwrite($file, $fileContents."Someone clicked button\r\n");
fclose($file);
Something like that. Sorry for not giving a full explanation but I hope it helps.

Related

how to export and then download a excel file with ajax call in background in php

I have to export large file in excel format and download it. i am using php excel. File is very large so it is taking much time in export. so i am using async ajax call and on server side, i am using session_write_close. Through this i can send concurrent calls.this is working fine if i stay on the same page...
but when i send ajax call to export and download file and after that i redirect to a new page before the completion of that ajax call then that ajax call got cancelled and unable to download file. how can i export a file and then download it even after user has been redirected to a new URL.
There are several ways to perform download action on same page. Use of async may cause issues, your application may feel lagging between ajax operation.
As per my opinion you can do your ajax request in this way.
Upon creation of file use command-line approach if its possible. Or you can simply use system command with curl or elinks command and pass the url which is being used to generate the excel file.
curl http://mysite/generate/excel?id=123
or
elinks http://mysite/generate/excel?id=123
By using ajax ( sync ) you can make a request with keep alive option and check inside your code if file is created with some interval. your code will be like this
while (!file_exists("path/to/excel_file.xlsx")) {
usleep(2000);
}
echo json_encode(["status" => true, "file_url" => "http://mysite/url/to/excel_file.xlsx"]);
Once you get response from ajax, On success function call below function with file url to download file through iframe on the same page.
downloadAttachment(response.file_url)
/* Amazing download management with error handling */
var downloadAttachment = function(link){
var iframe = document.createElement("iframe"), iframeWindow;
iframe.src = link;
document.body.appendChild(iframe);
iframe.onload = function(){
response = JSON.parse($(iframe).contents().text())
if(!response.status)
{
alert(response.message);
$(iframe).remove();
}
}
setTimeout(function(){
$(iframe).remove();
},10000)
}
This is logical flow of how to download big files if it is taking long time to generate.

How to read a log file live that is constantly updating in server to web textbox

the log file will be in notepad format the values will be like this 11.23445646,56.3456578954
10.23445646,26.3456578954
16.23445646,-46.3456578954
I'm planning to get the data from server to website textbox, of first value which I marked as italic the values will change after few seconds the updated value will come first. I tried some PHP example but not getting it in the below text box the values I need to get.. for example: x=11.23445646, y=56.3456578954, pls guide me
Longtitude <input id="x" type="number" value = "" onkeyup="updateMarker('x')">
Latitude <input id="y" type="number"value = "" onkeyup="updateMarker('y')">
Updated Answer
You can do this now using Web Socketing. Here is a guide and hello-wrold example of a php websocket server:
http://socketo.me/docs/hello-world
And to see how to implement client side javascript of websocket, you can see the bottom of the link put above, which shows you this snippet:
var conn = new WebSocket('ws://localhost:8080');
conn.onopen = function(e) {
console.log("Connection established!");
};
conn.onmessage = function(e) {
console.log(e.data);
};
Old
PHP does not support live connections generally in the way you expect, you have to simulate it via repeated AJAX request. How? For instance on each second, or each two seconds.
You first have to write an ajax in your HTML with jQuery library:
Sending a request each second:
var url = "url_to_you_file";
var textarea_id = "#textarea";
setInterval(function(){
$.ajax({
url : "site.com/get-file-logs.php",
type : "POST",
success : function(data){
$(".textarea").html(data);
}
});
}, 1000);
Then in PHP file you would write this:
$file_path = "path_to_your_file";
$file_content = file_get_contents($file_path);
echo $file_content;
The above example gets the file content and sends it back to your browser. You may want to process it in a certain way; that then changes your approach a little bit. Because you must always stick to JSON format when you try to get data back from server to be manipulated by Javascript.
PHP doesn't really do "live" page updates since normally when a web browser (or other user agent) loads a web page once it's done downloading the page then PHP is already finished and can't touch what's already on the client.
Best way to do this would probably be to use a JavaScript AJAX call to periodically load the updated values from a PHP script and then update the values on the page.
Or if it's a really small page (in byte size) you could just make it automatically reload the whole page (with updated values) if that is not a problem for you.
In any case every time the PHP script is called it would just open the file in read mode and only read the latest values from the beginning of the file and return those. See fread(). Or maybe file_get_contents() or file() would be easier and just read the first line.
AJAX is a bit larger topic and I don't currently have the time to explain the whole process of updating the page using JavaScript. Google is your friend.

Correct or best process for loading PHP files and displaying the status using jQuery/Ajax/JS

So i'm working on a project that will be using PHP to download files with CURL and update them on the server. I've already gotten that part taken care of and now i'm working on a front end gui that will display the progress to the user.
So my original thought method was to use the code in this manner:
$('#startupgrade').click(function() {
$('#upgradeprogress').css({"width": "0%"});
$('#upgradestatus').append('<p>Starting Upgrade...</p>');
$('#upgradeprogress').css({"width": "10%"});
$('#currentstep').load('upgrade.php #statusreturn', 'step=1');
$('#upgradestatus').append('<p>Step 1 Complete...</p>');
$('#upgradeprogress').css({"width": "20%"});
})
The thought behind this was to load the PHP page and pull a "status message" from the page which PHP generates in the ID #statusreturn which would then be appended to the current page if that step fails or is successful. In the example above I kept it simple and just went ahead and appended Step 1 Complete but i would add some type of standard JS in there to check if the first step was completed or not.
I've very new to JS and jQuery and I feel like there should be an easier or more correct way of doing this. Maybe running some standard JS using an if statement based on the number of steps?
Does anybody have any suggestions or recommendations on how this could be done with less code or in an easier manner? I want to make sure the method I end up using and learning will be correct and hopefully i'm not making newbie mistake and using more code than is necessary.
I appreciate any input and thanks for your help in advance.
The #upgradeprogress is using Twitter Bootstrap progress bar which is controlled by the width. The #upgradestatus is a Bootstrap well that will display the output almost similar to a terminal.
The load function is an asynchronous function. That means it will directly continue and not wait for the load. In order to wait for the load place your update of progress bar into the success callback handler:
http://api.jquery.com/load/
$('#result').load('steps/step1.php', function() {
$('#upgradeprogress').css({"width": "10%"}); //update your status bar here
$('#currentstep').load('upgrade.php #statusreturn', function() {
$('#upgradeprogress').css({"width": "20%"});
//add more steps here if required
});
});
Only when that success function( ) is executed you can be sure the request was finished.

How to query database using javascript?

Another question by a newbie. I have a php variable that queries the database for a value. It is stored in the variable $publish and its value will change (in the database) when a user clicks on a hyperlink.
if ($publish == '') {
Link to publish.html
} else {
Link to edit.html
}
What is happening in the background is i am querying a database table for some data that i stored in the $publish variable. If the $publish is empty, it will add a link for publish.html in a popup. The popup will process a form and will add the data to the database and which means that the $publish is no more empty. What i would like to achieve is that as soon as the form is processed in the popup and a data has been added to the database, the link should change to edit.html. This can happen when the page will re-query the database but it should happen without page refresh.
How can it be donw using javascript, jquery or ajax?? Please assist.
Javascript by itself cannot be used to deal with database. That is done using php (Or the server side language of your choice). Ajax is used to send a request to your php script using javascript which will in turn communicate with the db. And it doesn't require a page refresh.
So what you are trying to do can be easily achieved using ajax. Since you mentioned jquery, you can check out the $.ajax or $.post methods in jquery which make the process even more simple.
You need to process the form using ajax. The ajax request is sent to a php script which will make the necessary changes in the database and send the new link (link to edit.html) in the response. Upon getting the response, just replace the current anchor element with the new one ..
for eg..
$.post(url, formdataobject , function (resp) {
$("a.youra").text('edit').attr('href', resp);
});
url - where the php script is located
formdataobject - a javascript object that will have the form data as key value pairs
the third parameter is an anonymous function also known as callback function since it will be invoked only when the response is received from the server. This is because ajax requests are asynchronous.
Inside the callback function, jquery is used to change the text inside the anchor element to edit and the href attribute is changed to value that came in the response.
$.post means we are using the post method. so the parameters can be accessed as elements of $_POST array in php.
After updating the db, you can simply echo out the new link and it will be received in the response.
Also, there are other formats in which you can get the response for eg. xml, json.
I'll try to leave the technical jargon aside and give a more generic response since I think you might be confused with client-side and server-side scripting.
Think of javascript as a language that can only instruct your WEB BROWSER how to act. Javascript executes after the server has already finished processing your web page.
PHP on the other hand runs on your web server and has the ability to communicate with your database. If you want to get information from your database using javascript, you'll need to have javascript ask PHP to query the database through an AJAX call to a PHP script.
For example, you could have javascript call a script like:
http://www.myserver.com/ajax_function.php?do=queryTheDatabase
In summary: Javascript can't connect to the database but it can ask PHP to do so. I hope that helps.
Let me try, you want to change the link in a page from a pop-up that handles a form processing. Try to give your link a container:
<div id="publish_link">Publish</div>
As for the form submission use Ajax to submit data to the server to do an update and get a response back to change the link to edit or something:
$.post("submit.php", { some_field: "some_value"}, function(response) {
if(response.isPublished)
$('#publish_link', window.opener.document).html('Edit');
});
Basically your publish link is contained in a div with an ID publish_link so you change its content later after data processing without reloading the page. In the pop-up where you would do the form processing it is done using jQuery Ajax POST method to submit the data. Your script then accepts that data, update the database and if successful returns a response. jQuery POST function receives that response and there's a check there if isPublished is true, get the pop-up's opener window (your main window) and update the link to Edit. Just an idea, may not be the best out there.
It cannot be made with javascript, jquery or ajax. only server side script can query a database. with ajax request you can get the script output. ajax requests can be sent either with pure javascript or jquery.
Well, i think i understand your quaestion, but you have to get a starting point, try to understand this:
try to understand what are client variables and server variables.
javascript does not comunicate with database.
you can use javascript to retrieve data to a specific "Object variable".
Using ajax methods of jquery you can post that data do other page, that will execute the
proper actions
you can ;)
at first you must create php file to query database and return something like true or flase and then with file url check the function and get answer
function find_published(folder_id) {
var aj_url = "{{server_path}}/ajax/url"
var list;
$.getJSON(aj_url+"?callback=?&",
function(data) {
//here is your data... true false ... do every thing you want
}
);
};
this app for node.js does mysql queries https://github.com/felixge/node-mysql
You need to use AJAX for this, like .post() or .get() or JSON.

Displaying POST Data with jQuery?

I'm using a flash webcam to take a picture. It works great and spits back a URL via POST.
I'm coding in PHP and would like to display this POST data once it is recieved, the problem is that I dont re-load the page.
I've looked around and I'm not sure to dynamically load this array of data.
Where should I be looking? jQuery?
Ah, Figured it out. The Flash thing I have has a built in callback function, so I just have to append the data from there!
jQuery is not able to read any sort of request data other than that which appears in the URL (GET). You will need to use PHP (or some other server-side language) to handle the response created by the FLash application.
Due to the fact that you're using Flash for the process you are at somewhat of a disadvantage because unless the Flash application has some sort of JavaScript "PhotoUploaded" event notification, your page won't be notified that Flash has just submitted a picture to your server which needs to be retrieved and inserted. If you can modify the Flash application to make an external JavaScript event then you can proceed as Frankie has described in his answer; otherwise, if modifying the Flash application is not an option, then another solution would be to have your page send a request to the server every so often (5-10 seconds or so maybe), to check if there is a photo for it to display yet.
The simplest way to setup polling with your server in this fashion would be to make sure that each photo upload from Flash has a unique, pre-determined identifier that your page knows at initial load. You would then simply ping your server every few seconds with an AJAX request and pass it that unique identifier in order to find the right image should one exist.
Basic example:
function GetPhoto() {
$.get('/getphoto.php?ID=1541XJ55A6', function(response) {
if(response.ImageUrl !== "") {
$(".profile-image").attr("src", response.ImageUrl);
if(getPhotoTimer !== undefined) {
clearInterval(getPhotoTimer);
}
}
});
}
$(document).ready(function() {
var getPhotoTimer = setInterval("GetPhoto()", 10000); // every 10 seconds
});
Flash calls javascript each time it spits back the URL.
Javascript contacts server (php) and gets content
Javascript injects content onto page
Like this (flex code):
// attach a function to the completeHandler
private function completeHandler(evt:Event):void {
javascriptComplete();
}
// declare the function that will call the javascript function
private function javascriptComplete():void {
var javascriptFunction:String = "galeryUploadComplete("+Application.application.parameters.opt+")";
ExternalInterface.call(javascriptFunction);
}

Categories