Is it possible to use js script with laravel crontab? - javascript

I am suposed to make report scheduling in Laravel. Let's say that I want to send a pdf file to a list of emails that I get from my database every morning. I have written a command that calls a function from a controller, and the function returns a view where I have written a script.
Rather than using snappy or any other php libraries, I would like to do the report in jspdf. In the script I would pass the generated data via ajax back to controller and save the file in storage.
<script type="text/javascript">
$(document).ready(function () {
var doc = new jsPDF();
doc.text('text', 80, 10);
var pdf = btoa(doc.output());
$.ajax({
method: "POST",
headers: {
'Access-Control-Allow-Headers' : '*',
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
url: url,
data: {data: pdf},
}).done(function(data){
console.log(data);
});
});
</script>
Then in the controller I would do this:
public function data(Request $request)
{
$data = base64_decode($request->data);
\Storage::put('app/public', $data);
}
Is there any way in which I could force my javascript to be loaded when my crontab is called?

I'm not a NodeJS expert but if you issue relies on a PDF, you certainly could do the same in a NodeJS script and then call this script from your cron

No, because your JavaScript is client sided, it cannot be called on the server. Not without making a Node.js script to generate your PDF.
Alternatively, you could look into some PHP PDF generation packages and then create an artisan command and setup a cron job and make your PDF be generated on the server side.

Related

AJAX sucess writing to file but file is empty

I've been working on a web page which can't use PHP so I had to look up a solution without. I now have the following jQuery code:
function writeFile() {
alert("writing file...");
$.ajax({
type: 'POST',
url: "test.txt", // url of receiver file on server
data: "test", // your data
success: alert("sucess writing the file!"), // callback when ajax request finishes
dataType: "text" // text/json
});
};
The file is where it should be and the alert() are showing up (also the success alert) but somehow the file is empty. Why?
AJAX cannot directly write to a file, because JavaScript is a client side only and not server side. What you want is a server that catches your AJAX request; server can be anything, including PHP, JAVA or NodeJS. You can only read static files using AJAX but that is all.
You can't just write to a text file on the server using client-side AJAX scripting. You will have to use Node.JS or a PHP server-side script to write to the file on the server. This example below uses a PHP script. You will want a file called test.php in the same directory as the page the AJAX is on. This will POST the string "hello world" to test.php, as the superglobal $_POST['textcontent']. It is possible, using an anonymous function in the success field, to get the output from the PHP script and show it on the page. Note that you can replace "hello world" in the example below, to a $("#my-input-area").val() variable, if you want to write user input to a file.
function writeFile() {
alert("writing file...");
$.ajax({
type: "post",
url: "test.php",
data: {
textcontent: "hello world",
},
success: function(response) {
$("#ajax-area").html(response);
}
});
};
And then your PHP will look like this.
test.php
<?php
if (!empty($_POST['textcontent'])) {
file_put_contents("test.txt", $_POST['textcontent']);
exit("<p>TXT file written successfully!</p>");
}
// This is where you write to the text file.
// The string in the exit() function will appear in your $("#ajax-area")
else {
exit("<p>No text string submitted.</p>");
}
?>
Using the above example, the PHP script will receive the string "hello world" from the AJAX call. This will write to the test.txt file in the same directory as your PHP script, which would be in the same directory as the page with the AJAX. You can put these in a different folder on the server if you want. Anything the PHP script outputs, either with echo or with exit, will be returned as the response parameter, in your success function in your AJAX call.
I hope any of this helps.

D3.request - get JSON from PHP

Have a php code selecting from SQL with "echo json_encode($array);" at the end.
Want to build a graph on D3.js, so I need to get that JSON from php.
How to make it with D3.request() or d3.json() or other? Please, help me with example.
(Here is guide, but I cant make it yet - https://github.com/d3/d3-request/blob/master/README.md#json)
AJAX request is simple:
$.ajax({
type: "GET",
url: "get_json.php",
data: "FirstName="+ name, //here is the parameter
success: function(data){
var data = $.parseJSON(data);
alert(data.Content);
}
});
In order for your javascript code to access the php script it will need to be run on a web server. A simple way to run a web server if you have PHP installed is:
Open command line
Navigate to the directory with this javascript file and your get_json.php file
Run the command php -S localhost:8080
Now your files are running on a local php web server which allows you to reach the file containing your AJAX request at: localhost:8080/[ajax js file]
var par = 23
d3.json("get_data2.php?par=" + par, function(error, json) {
if (error) return console.warn(error);
data = json;
});
solved.

Handle json object with php and push it to .js file

I have this function on the client-side
function ajaxPost(obj){
$.ajax({
type: "POST",
url: "url to the php file",//I'm not sure about this line
contentType: 'application/json',
data: JSON.stringify(obj),
dataType: 'json'
});
}
and this php on server-side
<?php
$json = file_get_contents('php://input');
?>
I'm calling ajaxPost function on button click from client side. So when i call the function php on the server puts the json object inside $json variable.
How to paste this json object to existing .js file on the server while replacing previous code inside .js file.
So the object send from the client side must replace already existing .js content.
So what im trying is to change the script inside this .js file on the server with the passed object from the client
To clearify im using this .js file on the server as an API that i call from the client side every minute but i want to be able to change its content from an admin panel

How to build a file from binary string using javascript

I am trying to use BusinessObject RESTful API to download a generated (pdf or xls) document.
I am using the following request:
$.ajax({
url: server + "/biprws/raylight/v1/documents/" + documentId,
type: "GET",
contentType: "application/xml",
dataType: "text",
headers: {"X-SAP-LogonToken": token, "Accept": "application/pdf" },
success: function(mypdf) {
// some content to execute
}
});
I receive this data as a response:
%PDF-1.7
%äãÏÒ
5 0 obj
<</Length 6 0 R/Filter/FlateDecode>>
//data
//data
//data
%%EOF
I first assumed that it was a base64 content, so in order to allow the users to download the file, I added these lines in the success function:
var uriContent = "data:application/pdf; base64," + encodeURIComponent(mypdf);
var newWindow=window.open(uriContent, 'generated');
But all I have is an ERR_INVALID_URL, or a failure while opening the generated file when I remove "base64" from the uriContent.
Does anyone have any idea how I could use data response? I went here but it wasn't helful.
Thank you!
. bjorge .
Nothing much can be done from client-side i.e. JavaScript.
The server side coding has to be changed so that a url link is generated (pointing to the pdf file) and sent as part of the response. The user can download the pdf from the url link.
You cannot create file using javascript, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least.
To achieve your functionality, you can implement click event which target to your required file and it will ask about save that file to user.

How can i receive data from external url using json?

Recently i am learning json to create apps.I have a doubt in a Json , php based chat system .
In this , the code work fine for same origin policy.But for sending and receiving data from external url, it successfully sends data to external php.But not receiving any data from server.I search in internet to solve this problem , and found jsonp as alternative. I tried jsonp , but i m not sure if am correct because i am new to ajax itself.
Please don't mis understand my question.I want to load a index.html file from localhost , when i send request to external url (anysite.com/xx/ajax.php) .It process and returns the data back to index.html.But the problem is my data is sended finely and processed on the server but it doesn't return to remote file.But it works fine for same server.
$.tzPOST = function(action,data,callback)
{
$.post('http://anysite.com/xx/ajax.php?action='+action,data,callback,'json');
}
$.tzGET = function(action,data,callback){
$.get('http://anysite.com/xx/ajax.php?action='+action,data,callback,'json');
}
please help me with a code.
You cant receive JSON from external web by JavaScript, because of the policy.
But you can do AJAX request on your PHP file and there you can get the JSON by file_get_content http://cz2.php.net/file_get_contents function.
For using(working) with jsonp, u can take ready solution jquery-jsonp
from GitHub.
Example of using (by you question):
$.tzGET = function(action,data,callback){
var url = 'http://anysite.com/xx/ajax.php?action='+action;
$.jsonp({
type: 'GET',
url: url,
callbackParameter: callback,
dataType: 'jsonp',
data: data,
timeout: 10000,
success: function(json){
alert('success')
},
error: function(){
alert('error')
}
});

Categories