I have a webpage with a HTML button. The webpage is located in /var/www/html and is named index.php. In the same folder I have a file called "running.php". The contents of running.php is below:
#!/usr/bin/php
<?php
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'test' : test();
break;
}
}
function test(){
exec("/usr/sapint/outgoing/ihprocess",$output);
print_r($output);
}
?>
when I run the file from command line on the server as ./running.php the file executes perfectly. I want to be able to execute this file from the HTML webpage.
I have played around with all the options such as exec, permissions etc but nothing seems to work.
I currently have in my index.php file
<a id="run" class="btn btn-primary" onclick="ajaxcall()">Process Files </a>
function ajaxcall() {
$.ajax({ url: 'running.php',
data: {action: 'test'},
type: 'post',
success: function(output) {
alert(output);
}
});
}
any help would be appreciated.
Related
I would like to download a pdf from my external URL, store it in my server and download it when the button was triggered by click by the user.
I have tried to store it to my server and its success, but then I don't know how to automatically download the pdf as the user wants after they click the button.
My view:
<button id=\"appPrintbutton\" name=\"appPrintbutton\" style=\"cursor:pointer;padding: 3px; margin: 2px;float:left;\" title=\"Cetak Dokumen\"><i class=\"fas fa-check fa-lg fa-fw\"></i>Cetak</button>
<script type="text/javascript">
$("#appPrintbutton").on('click', function() {
var selectedId=[];
selectedId.push(document.getElementById("txtNO_DOK").value);
$.ajax({
url: "<?php echo base_url().'index.php/finance/M_approve/DOWNLOAD_FILE_NILAI'?>",
type: 'POST',
data: {json: JSON.stringify(selectedId)},
dataType: 'json',
success: function (data) {
window.location.href = "<?php echo base_url().'index.php/finance/M_approve/';?>";
},
error: function (data) {
console.log('error');
}
});
return false;
});
</script>
And my Controller was:
public function DOWNLOAD_FILE_NILAI()
{
$msg="";
$status="";
$rptName="";
$pathdir="/wwwroot/php/download/";
$ieselon="ALL";
$data=$this->input->post('json');
$nodok=substr($data, 1, 9);
if($nodok!="" )
{
$randfname = Date("Y_m_d");
$fname = $nodok."_nilai".$randfname.".pdf";
$rptName="\wfinance\kas_cetak.rpt";
$strParamName= "&promptex-no_dok=".$nodok;
$strParamName.= "&promptex-terbilang=".$nodok;
$exportType="PDF";
$serverLink = "http://11.5.1.44:12000/ReCrystallizeServer/ViewReport.aspx?report=".$rptName;
$fullLink=$serverLink.$strParamName."&exportfmt=$exportType";
$fdata = file_get_contents($fullLink);
$fSaveAs=fopen($pathdir."$fname","w");
fwrite($fSaveAs, $fdata);
fclose($fSaveAs);
$status="OK";
}
$dataStatus[] = array(
'Status'=>$status,
'url'=>base_url(),
'fname'=>$fname,
'Msg'=>$msg
);
print_r(json_encode($dataStatus,JSON_PRETTY_PRINT));
}
My desired output:
Automatically download the pdf
Is it any way to do that?
You can use file_put_contents() function in PHP to read and write remote files to the server's directory.
$remote_file = 'http://example.com/path/to/pdffile.pdf';
$local_file = '/documents/new_file.pdf';
file_put_contents($local_file, file_get_contents($remote_file));
Update
If you are unable to write file directly, you can use two step way. First create blank file and after that write to it.
$local_file = fopen("/documents/new_file.pdf", "w")
This will create a file so other functions could write to it.
this way you can display files either from external/internal URL. And in case of downloading, you can provide local URL of /documents/new_file.pdf
So when the user clicks button you can hit ajax which triggers a server-side script which executes the code above.
Make sure your local directory /documents/ is writable by PHP process.
Read: https://www.php.net/manual/en/function.file-put-contents.php
I have create a backend plugin for my website and I would like it to work with AJAX. But all I am getting from the AJAX response is readyState: 4 and responseText: 0.
script.js
jQuery(document).ready(function($){
$.ajax({
url: ajaxurl,
type: "POST",
data: {
action: 'my_action',
param: 'st1'
},
error : function(response){
console.log(response);
},
success : function(response){
console.log(response);
}
});
});
members_loop.php
add_action('wp_ajax_my_action', 'my_ajax_action_function');
add_action('wp_ajax_nopriv_my_action', 'my_ajax_action_function');
function my_ajax_action_function(){
$reponse = array();
if(!empty($_POST['param'])){
$response['response'] = "I've get the param a its value is ".$_POST['param'].' and the plugin url is '.plugins_url();
} else {
$response['response'] = "You didn't send the param";
}
header( "Content-Type: application/json" );
echo json_encode($response);
wp_die();
}
I am using three files inside my plugin to do this, I have my plugin.php file where I declare my plugin and enqueue my script.js file. Then I have a templates file with two folders inside it one being members_loop.php and the other index.php (The "homepage" for the plugin). Then I have an assets file with my script.js file. Not sure if this information is needed but I don't think my ajax call is wrong so I'm wondering what is going wrong.
Issue Update
I just cut and paste the my_ajax_my_action funciton and the actions to the plugin.php file where I declare the plugin and now it works. So how do I get it to work in an external file? do I have to require the members_loop.php file inside the plugin.php file?
If your file path is "/wp-content/plugins/your_plugin/members_loop.php", so inside file "plugin.php" add require_once plugin_dir_path( __FILE__ ) . 'members_loop.php'; or require_once dirname(__FILE__) . '/members_loop.php';
I have a page from which I am trying to make an AJAX call, but it isn't working, and I'm stumped as to why. My call is:
$.ajax({
type: "GET",
url: "<relative URL>/index.php?action=x",
dataType: "JSON"
}).success(function(person) {
alert(person.name) //alerts naem
});
return false;
});
and the PHP is:
<?
if($_GET["action"] == "x"){
$person = array("name"=>"Jon Doe","Reputation"=>"Good");
header("Content-Type: application/json");
echo json_encode($person);
}
?>
I don't THINK the issue is a faulty URL, since it is a c/p of working calls. It seems to me (but I'm not sure) that it chooses to reuse the old 'action-values' from when the source page was loaded originally. For some reason it completely ignores my action-value…?
Any ideas?
Try moving the PHP into its own file rather than the index.php, which I assume is your main PHP file.
$.ajax({
type: "GET",
url: "/ajax.php?action=x",
dataType: "JSON",
success: function (person) {
console.log(person.name);
}
});
This should be a separate file. Call it ajax.php for an example.
<?
// ajax.php
if($_GET["action"] == "x"){
$person = array("name"=>"Jon Doe","Reputation"=>"Good");
die(json_encode($person));
}
?>
Just make sure ajax.php is in the route of your project and this should work. Check the console.log if it doesn't.
Try moving the variable into 'data':
$.ajax({
type: "GET",
url: "<relative URL>/index.php",
data: "action=x",
success: function (person) {
console.log(person.name);
}
});
Since you are calling index.php with a get parameter, you might be echoing the json_encode and then continuing to output everything else after the if statement.
Try this?
<?
if($_GET["action"] == "x"){
$person = array("name"=>"Jon Doe","Reputation"=>"Good");
header("Content-Type: application/json");
echo json_encode($person);
exit;
}
?>
I'm assuming you have more content in the index.php below that if statement. If so, the exit; statement would be needed so that you only echo the json and not anything after the if statement.
The ajax response can be viewed in Google Chrome's Dev Tools, under the Network tab.
Let's say you had no exit; statement:
<?
if($_GET["action"] == "x"){
$person = array("name"=>"Jon Doe","Reputation"=>"Good");
header("Content-Type: application/json");
echo json_encode($person);
}
?>
<html>
<head></head>
<body>
...etc, etc
The ajax response under Dev tools would look something like this:
{"name":"Jon Doe","Reputation":"Good"}<html><head></head><body>... and so on
which would then try to be parsed by the $.ajax into a JSON object.
But this is not possible because <html><head></head><body>... is not valid JSON.
Hope this helps!
I have a main page in my app called index.php where i want to show some photos. Code in that file is:
<div id="main" name="main">
<input type="button" value="Photos" onclick="showIm()">
</div>
File function.php contains a function to show photos on the screen:
function showPhotos()
{
global $link;
$result = pg_query_params($link, 'SELECT photo_name FROM photos');
while($photos_row = pg_fetch_row($result))
{
echo '<a href="photos/'.$photos_row[0].'">
<img src="photos/'.$photos_row[0].'"></a>';
}
}
My last file is function.js where i try to call showPhotos using ajax
function showIm()
{
$.ajax({
url: "functions.php"
})
}
So inside the last function I want to call showPhotos() to get the results. I think that my implementation is a little complicated but I would like to know if anyone could help.
Well, you have to do something with that result! Add a success method and declare a return dataType
function showIm()
{
$.ajax({
url: "functions.php",
dataType: "html",
success: function(html) {
//do something with the response here
//the "html" variable will contain your PHP response
}
})
}
I'm creating a module for the shopping cart PrestaShop so I have to follow a set framework of rules when creating a module that will work in their system, and I want to submit forms via AJAX without reloading the page.
Here is a trimmed version of the module page which builds and determines what is displayed:
<?php
class mymodule extends Module
{
private $_html = '';
// Module information
function __construct()
{
// Get shop version
$versionMask = explode('.', _PS_VERSION_, 3);
$versionTest = $versionMask[0] > 0 && $versionMask[1] > 3;
// Module info
$this->name = 'MyModule';
$this->tab = $versionTest ? 'administration' : 'Administration';
if ($versionTest) { $this->author = 'JD'; }
$this->version = '0';
parent::__construct();
$this->displayName = $this->l('MyModule');
$this->description = $this->l('Description...');
}
// Display content
public function getContent()
{
$this->_displayForm();
return $this->_html;
}
// Build the display
private function _displayForm()
{
$this->_html .= '<script src="../modules/mymodule/scripts.js" type="text/javascript"></script>
<form name="formName" id="formName" method="get">
<input type="submit" name="submitModule" value="Continue" />
</form>';
}
}
?>
Normally there is a private _postProcess function which processes form data which then calls the function getContent on page reload where you can then check to see if it should show the form or the results etc.
But since I want to do this with AJAX, I've removed the _postProcess function as it's not needed, linked to my scripts.js which has the following:
$(document).ready(function() {
$('#formName').submit(function(e)
{
e.preventDefault();
$.ajax({
url: "ajax.php",
type: "GET",
dataType: "json",
success: function(data)
{
if (data.response == 1)
{
alert('true');
}
else
{
alert('false');
}
}
});
});
});
And the ajax.php file itself which I've really trimmed down so it's forced to show a result:
<?php
$json['response'] = 1;
echo json_encode($json);
exit();
?>
But I always get the error Uncaught TypeError: Cannot read property 'response' of null, which is obviously telling me the data.response isn't being sent through properly as it doesn't know what response is.
If I test the pages manually, everything works fine, so it leads me to believe either it has something to with the fact it could be in a class perhaps? And that I have to do something different to usual to get it to send the data through?
Or PrestaShop doesn't allow modules to run via AJAX, yet the only thing I can find on their site which relates to this is someone asking the same question in their forum and it has no replies/fixes.
I'd also like to note the AJAX is working to an extent, that if in the success function I put alert("hello"); the alert popup is shown.
Does anyone have any ideas where I might be going wrong?
Uncaught TypeError: Cannot read property 'response' of null scripts.js:132
$.ajax.success scripts.js:132
o jquery-1.7.2.min.js:2
p.fireWith jquery-1.7.2.min.js:2
w jquery-1.7.2.min.js:4
d
scripts.js:132 refers to the line: if (data.response == 1)
Also I've taken it out of the class and put it on a normal page/seperate directory and have the same code, just not inside the class/functions:
index.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="scripts.js" type="text/javascript"></script>
<form name="formName" id="formName" method="get">
<input type="submit" name="submitModule" value="Continue" />
</form>
scripts.js
$(document).ready(function() {
$('#formName').submit(function(e)
{
e.preventDefault();
$.ajax({
url: "ajax.php",
type: "GET",
dataType: "json",
success: function(data)
{
if (data.response == 1)
{
alert('true');
}
else
{
alert('false');
}
}
});
});
});
ajax.php
<?php
$json['response'] = 1;
echo json_encode($json);
exit();
?>
And when I submit the page I get the alert true and if I view ajax.php I get {"response":1}. So that code itself is ok, it's just integrating it with their class/functions.
It appears the path to the ajax.php file in the scripts.js file was causing the problem.
It's to do with the structure of the folders in prestashop, all modules are placed in /prestashop/modules/ directory but the modules are viewed from /prestashop/admin/. So changing them to the full paths fixed the problem.
Thanks to the guys that helped on here though, it's still appreciated!
I think your result is being sent ok, but not interpreted as JSON, a bit of the jquerys fault - I dare to say.
header('Content-Type: text/javascript; charset=utf8');
Putting this in the PHP script should do the trick and force the correct interpretation of the json the data.
If the previous suggestion didn't get you anywhere also try using $.parseJson(); as in jQuery docs:
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );