ajax to run php file - php

I have this script in a .html file on my page and im trying to just run the getip.php file from here rather than to rename the file to .php. I tried this ajax call but its not working and not logging the ip in the logfile.txt. Please let me know what I am doing wrong.
Ajax in the head of the .html file:
<script>
$(document).ready(function() {
$.ajax({
type: "GET",
url: "getip.php",
}); // Ajax Call
}); //event handler
</script>
Code from getip.php:
<?php
// location of the text file that will log all the ip adresses
$file = 'logfile.txt';
// ip address of the visitor
$ipadress = $_SERVER['REMOTE_ADDR'];
// date of the visit that will be formated this way: 29/May/2011 12:20:03
$date = date('d/F/Y h:i:s');
// name of the page that was visited
$webpage = $_SERVER['SCRIPT_NAME'];
// visitor's browser information
$browser = $_SERVER['HTTP_USER_AGENT'];
// Opening the text file and writing the visitor's data
$fp = fopen($file, 'a');
fwrite($fp, $ipadress.' - ['.$date.'] '.$webpage.' '.$browser."\r\n");
fclose($fp);
?>

Have you tried $.post() function instead? Example:
<script>
$(document).ready(function() {
$.post('getip.php'); // Ajax Call
}); //event handler
</script>
You can also add a callback as a second parameter.

I would use the full URL for the ajax call. Depending on your framework you might not be hitting the intended endpoint. You could try echo 'test'; in your php file and adding a done handler to your ajax call to make sure you're hitting the php file in the first place:
.done(function( data ) {
alert(data);
});

Related

Read PDF from external URL, and automatically download when the button was triggered

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

jquery call php function that performs a download

I want to achieve:
in a html-form put in some data (e.g. -wahl- and -id- )
after klicking -submit- call the javascript function -machExport-
this function validates the values and passes them (-wahl- and -id-) to the php-File -makeExport.php-
the -php-Funktion gets these values, gets some data from a mysql database, creates output-data,
writes these data into a file -data.txt- and download this file instantly to the users download-folder.
Everything works quite well, but:
after creating the data, this data is stored into the file but there is no downloading.
So, what's wrong.
(If I execute the -php-file directly by passing some values to the php-function, it works quite well,
so only if there ist the javascript function between the html- and the php-function, ist doesn't work )
Part of the code within my -html- document
<form name="form" action="" method="post" onsubmit="return machExport()" onreset="abbruch()">
Javascript-Code:
function machExport(){
var wahl = $("input[name='rd1']:checked").val();
var id = $("#id").val();
// verify these values and give an error message, if necessary
...
// if everything is ok, pass values to the -php- function
var ajxFile = 'makeExport.php';
var param = wahl + "#" + id;
$.ajax({
type: "POST",
url: ajxFile,
data: param
// if I put here a -success: function -statement,
// then the data having been created within my php-function
// is not beeing written into the requested file
// but is displayed in my html-document.
}
});
return false;
}
PHP-File -makeExport.php-
<?php
// get the values for -wahl- and -id-
...
// create data to write into file
$data = ...
// write data to file and download this file instantly
$file = "data.txt";
$fOK = file_put_contents ( $file , $data );
// up to here, it works
// but the next 3 lines are not excecuted
header("Content-Type: text/plain");
header("Content-Disposition: attachment; filename=\"$file\"");
readfile($file);
?>

ajax post request to php $_POST vars empty

I have a nginx rewrite rule that redirects an img src attribute to a php page. Within this php page I'm trying make a GET request, which on success makes a POST request to the same page, sending the data returned from the GET request as the data. Why is the $_POST data empty in the php script? If I hardcode $name = "http://path/to/my/img.png" in the php script the image renders correctly.
<?php
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
var_dump($_REQUEST);
//if(isset($_POST['val'])) {
// open the file in a binary mode
$name = $_POST['val']; // ALWAYS EMPTY
$fp = fopen($name, 'rb');
// send the right headers
header("Content-Type: image/png");
header("Content-Length: " . filesize($name));
// dump the picture and stop the script
//echo fpassthru($fp);
header("Location: $name");
exit;
//}
?>
<html>
<head>
<script type='text/javascript' src='/steal/steal.js'></script>
<script type="text/javascript" src="/plugins/jquery/json2.js"></script>
<script type="text/javascript">
steal('jquery/dom/fixture').then(function(){
$.fixture("GET /event/{code}", function(original, settings, headers){
return [200, "success", { "img_url":"http://path/to/my/img.png" }, {} ]
})
var strObj = <?php echo json_encode($_REQUEST); ?>;
var str = strObj.q;
var eventCode = str.split('/')[1];
$.ajax({
url: "/event/"+eventCode,
success: function(data) {
var imgUrl = data.img_url
$.ajax({
type: 'POST',
contentType: 'json',
data: {val:imgUrl},
success: function(data){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(textStatus);
}
});
}
});
});
</script>
</head>
<body>
</body>
</html>
Alright, you've taken things a few steps beyond what is possible.
When the user hits this image in their email, a request is sent to your server asking for that image. None of that javascript is going to make it back to the user because the <img> tag is expecting an image, not an html document. You can tack things on to the outgoing request via something like
<img src="http://yourwebsite.com/tracker.php?val=someimage.png">
and your script will be able to get val out of $_GET but you won't be able to make a POST request for this image from inside an email.
All that $_REQUEST data you're getting at the top there? That's where you get all your email tracking data from. Everything you can get out of there and $_GET is all you're getting.
Afterwards, you need to give them back an image. So heres how you do that.
$val = $_GET['val']; // assuming val contains an image
header('Content-Type: image/png');
readfile('/path/to/your/images/'. $val);
Please be super aware that you need to sanity check $val to make sure its only containing images that you want to be able to see. A potentially malicious user could see this and put something like tracker.php?val=/etc/passwd or something similar and then you've got PHP trying to read your password file. Making sure that images exist and can even be read can be done with the is_readable() function.

Run javascript function then post for download

So I have a page where the user will hit the "export" button and I want to run a javascript function and get the data I need for the export and then call a php script to get the data from my database and force a download. Right now the problem is, I can run the javascript and then I call a post to my script, but nothing is downloaded. I am assuming it is because I am not actually moving the window to the php file, I am simply calling the script. can anyone help me out?
javascript: ids is an array that I need to pass to get the information. This is inside the function taht I call when the user hits the "export" button.
$.ajax({
type: "POST",
url: "exportLeads.php",
data: { 'idArray' : ids }
});
php: I used this Export to CSV via PHP quetsion. The function are implemented properly and I get no errors. There is just no file that is prompted for download.
$data = mysql_query($query) or die($query.mysql_error());
$results = array();
while($line = mysql_fetch_array($data, MYSQL_ASSOC)){
$results[] = $line;
}
download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($results);
die();
You cannot download files with ajax. You can use window.location.href to redirect user to the file location, but whatever, i suggest you to read this, someone has a better answer for you :)
Download a file by jQuery.Ajax
or you can also use something like this
in your javascript
$.post( "exportLeads.php", { 'idArray' : ids }, function( response ) {
if ( response.error === 0 ) {
window.location.href = response.location;
}
}, "json" );
and in your php file
<?php
if ( $has_error ) {
echo json_encode( array( "error" => 1 ) );
}
else {
echo json_encode( array(
"error" => 0,
"location" => "link_to_file"
) );
}
?>
Got no time to write code, but in few words, you need:
Execute JS to call server side via ajax.
Generate file, put it to the server drive with some random name. Remember that name to session. Send some response to client.
When client gets response, redirect user with JS to some page where PHP code checks if there is some filename in session, and if there is, reads this file, deletes it and its name from session.
You could go for window.location.href in your success function:
$.ajax({
type: "POST",
dataType: "json",
url: "exportLeads.php",
data: { 'idArray' : ids },
success: function(data) {
if (data.success) window.location.href = "/link-to-your-download-script";
}
});
You would have to change the response to json_encode and split the functionality into two scripts, one for the export and one for the download script (with a unique id or sth.)

ajax send data to "test.php", and then open "test.php" directly to show the result

I want to send an array from javascript to php via ajax function.
And I don't want show the result as callback, but immediately open the target php file and show the images.
I mean, I want open the php file directly on the server side.
I think this is quite simple, but I just have no idea.
My javascript looks like:
var stringArray = new Array("/images/1.jpg", "/images/2.jpg", "/images/3.jpg");
$.ajax({
url: 'test.php',
data: {stringArray:stringArray},
success: function() {
window.open('test.php'); // It opens test.php in a window but shows nothing!
},
});
the test.php file:
$stringArray = $_GET['stringArray'];
foreach($stringArray as $value) {
echo "<img src=" . $value . "></img>";
}
Thanks for any help!
Likely the window.open command is being called without the POST data needed.
Now, I don't know what you want to do here but, why send an Ajax request when you don't really want to make use of it?.
Edit: just to make it a bit clearer, you seem to be calling the php file with no data trough POST. There is no clean way of opening a window in JS with POST data, just try GET for no critical information. Let is know how it goes.
As I can see, You are sending data by post method and accessing in test.php
but when u open file via window.location it doesn't get POST data hence no data get populated
You can achieve it via $_SESSION.
in test.php
session_start();
if(!empty($_POST['stringArray'])) {
$_SESSION['stringArray'] = $_POST['stringArray'];
}
$stringArray = (isset($_SESSION['stringArray']) && $_SESSION['stringArray'] != '') ? $_SESSION['stringArray'] : $_POST['stringArray'];
foreach($stringArray as $value) {
echo "<h3>" . $value . "</h3>";
}
Hope this will work for you...
you should write
var stringArray = new Array("apple", "banana", "orange");
$.ajax({
type: 'post',
url: 'test.php',
data: {stringArray:stringArray},
success: function(message) {
window.open(message); // It will open a window with contents.
},
});
I doesn't show the output because when you open the page on the callback you are not sending anything through to the test page through the post variable. Why you would want to do this I don't know. Send the information through the url, get.

Categories