Help me please. Where is my mistake ? I have many XML files on the IIS server. After click button link to XML come in JS file. JS send link to PHP file. PHP must show save dialog to save this link. See code:
JS:
function showAl(url)
{
alert(url);
var ajax = getRequest();
ajax.onreadystatechange = function()
{
if(ajax.readyState == 4)
{
...
}
}
ajax.open("POST", "/do_query.php", true);
var data = 'info='+url;
ajax.send(data);
}
PHP:
<?php
if (isset($_POST['info']))
{
$info = $_POST['info'];
header('Content-Type: application/xml;');
header('Content-Disposition: attachment; filename=file.xml;');
readfile(str_replace(" ", "%20", $info), false);
}
?>
Thank's in advance !
Three simple ways to download a file:
Good old form
<form id="the-form" action="/do_query.php" method="post">
<input type="hidden" name="info" value="test">
<input type="Submit" value="Download with regular form">
</form>
Submit good old form with JavaScript
<script type="text/javascript">
function download(){
document.getElementById("the-form").submit();
}
</script>
<input type="Submit" value="Download with JavaScript" onclick="download()">
Switch to GET (requires changes to do_query.php):
Download with link
The problem with AJAX is that it runs on current (HTML) page. It can manipulate the page HTML or redirect to another location but it cannot send a custom HTTP response.
You cannot prompt a user to save a file when you are using AJAX, you will need to direct the browser window to the URL of the file to download. This also means you will need to use the GET method instead of the POST method to transfer the file.
Try this:
JS:
function showAl(url)
{
window.location.href = '/do_query.php?info=' + url;
}
PHP:
if (isset($_GET['info']))
{
$info = $_GET['info'];
// ...
This should prompt the user to download the file.
Related
I have a html form in which I want to save all the entries of all the fields into a file using php.
If I am able to save entries successfully then I want to give popup message saying {bytes} bytes written to file.
If I am not able to write successfully then I want to give popup message saying There was an error writing this file.
And if the user doesn't have write access then it should give popup message - Write access revoked.
I call save.php file from the form action to save all the entries in a file and add do some sort of validations.
Below is my index.php file which has form in it -
<?php
declare(strict_types = 1);
session_start();
require_once 'helpers.php';
if (! check_auth()) {
redirect('login.php');
return;
}
?>
<!doctype html>
<html lang="en">
<head>
<title>Home</title>
</head>
<body>
<div>
<h1>Website Title</h1>
Logout
</div>
<div>
<p>Welcome back, <?= $_SESSION['user_id'] ?>!</p>
</div>
<form action="save.php" method="POST">
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="submit" name="submit" value="Save Data">
</form>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
</body>
</html>
And below is my save.php file -
<?php
declare(strict_types = 1);
session_start();
require_once 'helpers.php';
if (!check_auth())
{
redirect('login.php');
return;
}
if ($_SERVER['REQUEST_METHOD'] === 'POST')
{
if (!isWriteAccess())
{
echo json_encode(['success' => false, 'message' => 'Write access revoked', ]);
return;
}
// Your code here...
if (isset($_POST['field1']) && isset($_POST['field2']))
{
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
$ret = file_put_contents('mydata.txt', $data, LOCK_EX);
if ($ret === false)
{
die('There was an error writing this file');
}
else
{
echo "$ret bytes written to file";
}
}
else
{
die('no post data to process');
}
}
Problem Statement
As of now whenever I click save button on my form which is in index.php, it just prints everything on my browser as the response and also redirects to save.php but I don't want that. I want to show all messages on popup window but it should stay on same index.php file.
If I am able to write successfully to the file, then I should see some bytes written to the file as a popup but it should stay on index.php file only.
If there is a write access issue then it should show Write access revoked as a popup but it should stay on index.php file only.
How can I make sure that whenever I click save button on my form which is in index.php it should stay on the same page but still do all sorts of validations and save entries in a file?
You already have jquery connected, so use $.ajax() to submit the form like this example or this. In the 'success:' handler the data variable will contain responce from your save.php:
success: function(data) {
$('#result').html(data);
}
therefore you can pop up a window with this results. Something like that in your index.php:
<script>
$(function() {
//This submits a form
$("#idForm").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
var method = form.attr('method');
$.ajax({
type: method, // "POST"
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data) {
alert(data); // show response from the php script.
}
});
});
</script>
PS: You can easily get answer to your question by yourself, such questions was answered here a lot. All trick is to add site:stackoverflow.com to your request in Google.
I'm trying to implement the following architecture using example of finding even/odd number. I'm using client as HTML file and web server as PHP.
[ "FindEO.html" ] - The HTML file is shown below:
<!DOCTYPE html>
<html>
<body>
<h3>Check Even/ODD Number</h3>
<form method="get" action="http://192.168.0.103:81/DUNNO/eo.php">
Enter number: <input type="text" name="fname">
<input type="submit">
</form>
</body>
</html>
[ "EO.php" ] - The PHP file is as follows:
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$name = $_GET['fname'];
$num = (int)$name;
if (($num%2)==0) {
echo "$name is Even";
} else {
echo "$name is Odd!";
}
}
?>
When the HTML file is executed, it ask for input as:
After clicking on the submit button.
The PHP page is displayed rather than showing content of the PHP page inside the HTML file.
[ Currently showing (PHP file): ]
[ It should show PHP content in HTML File ]
So, the request is sent from HTML file to PHP server, and instead of getting response from PHP file to HTML file, it is showing directly the PHP file itself.
1) Is this possible to display the expected output. (PHP processed output in HTML file)?
2) Suppose I stored the current PHP code in function as:
<?php
function findeo($num){
if (($num%2)==0) {
echo "$name is Even";
} else {
echo "$name is Odd!";
}
}
if ($_SERVER["REQUEST_METHOD"] == "GET") {
$name = $_GET['fname'];
$num = (int)$name;
findeo($num);
}
?>
then how to pass parameter (10 or any number to $num variable) and call the findeo() function of the PHP page inside the HTML file?
Someone please help me to implement the client - server architecture or tell me if there as any other way where this architecture can work using HTML as client & PHP as server.
use javascript to send the form to the php file and retrieve the answer.
here is how i would have done it:
function getAnswer(e) {
e.preventDefault();
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://192.168.0.103:81/DUNNO/eo.php', true);
xhr.responseType = 'text';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
document.getElementById('answer').textContent = xhr.response;
}
}
};
xhr.onerror = function() {
document.getElementById('answer').textContent = "Error...";
}
xhr.send(null);
}
<!DOCTYPE html>
<html>
<body>
<h3>Check Even/ODD Number</h3>
<form method="get" onsubmit="getAnswer(event)">
Enter number: <input type="text" name="fname">
<input type="submit">
</form>
<div id="answer"></div>
</body>
</html>
using preventDefault() will stop the page from trying to submit the form, and allow the javascript to perform the request by itself.
also, i added a div to your HTML that will hold the respone given by your PHP file.
PHP cannot modify the content of the page after it has been served to the browser. However this would be trivial with a JavaScript Library such as jQuery. or by using AJAX to call the php script to update an element. There are examples on StackOverFlow like: Change DIV content using ajax, php and jQuery
I'm trying to upload a photo by using ajax.
My input:
<input type="file" name="defaultPhoto">
A part of my jQuery code.
var form = #insertCredentials
var defaultPhoto = $('#' + form + ' ' + '[name = "defaultPhoto"]').prop('files');
I'm sending defaultPhoto through an ajax call to my php alongside with other form inputs.
The console gives back this error below:
TypeError: 'slice' called on an object that does not implement interface Blob.
I have implemented the AJAX way of file uploading using Dropzone JS.
It will really make your life simple
Check the Dropzone.js Website
All you need to do is instantiate the dropzonejs object and set the options
Dropzone.options.myAwesomeDropzone = {
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 2, // MB
accept: function(file, done) {
if (file.name == "image.jpg") {
done("Naha, you don't.");
}
else { done(); }
}
};
you can't send file via ajax
try to use hidden iframe in form target with normal submit
<form name="" action="/your_iframe_action_url" taget="hidden_iframe_name">
<input type="file" />
<input type="submit" />
</form>
<iframe name="hidden_iframe_name" style="width:0; height:0" />
In your_iframe_action_url you can call javascript parent functions to execute event success or failure... that simulate underground upload
you can use document.getElementById('whatever').files;
to get the file
and then use
formdata
to send the files via ajax.
here is the example
you can also use File reader to show file on loaded
here is the example for filereader
I want to upload file using ajax but i dont get data in php $_FILES and I get it in $_REQUEST. How do I do it. Below is my jquery code.Ajax is not working for file uploading so is there any code so that i can merge with existing code for file uploading process.
<script>
jQuery(function($){
jQuery('#btn').click(function(){
var data = {},
ticks = [];
$('.ajax_elements').each(function(_, elem) {
data[this.id] = this.value;
});
$.ajax({
type : 'POST',
url : 'app_process.php',
data : data,
cache : false
}).done(function(result) {
alert(result);
});
});
});
</script>
<form name="frm" enctype="multipart/form-data">
<input type="text" name="bb" class="ajax_elements" id="one"/>
<input type="file" class="ajax_elements" name="passport" id="passport" />
<input type="button" name="bttn" id="btn" />
</form>
here is php file code
<?php
if($_REQUEST['passport']!=''):
$uploaddir = 'images/';
move_uploaded_file($_FILES["file"]["tmp_name"], $uploaddir . str_replace(" ","_",$_REQUEST['passport']));
endif;
?>
error message
Notice: Undefined index: file in
G:\xampp\htdocs\data_ajax\app_process.php on line 5
My advice would be to look at the XMLHttpRequest, FormData and File APIs. The Mozilla Developer Network have great documentation on all of these.
This needs testing and tweaking to be more robust in your development environment, but something along the lines of this could get you started...
<script>
$('#btn').click(function() {
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("load", function(e){
// stuff to do when upload is complete
}, false);
xhr.upload.addEventListener("progress", function(e){
// stuff here to handle progress bars, progress percentages etc.
}, false);
xhr.open('POST', 'app_process.php', true);
var formdata = new FormData();
var file = $('#passport').get(0).files[0];
formdata.append('passport', file);
xhr.send(formdata);
});
</script>
And the PHP...
<?php
if (isset($_FILES['passport'])) {
$uploaddir = 'images/';
$upload = move_uploaded_file($_FILES['passport']['tmp_name'], $uploaddir . str_replace(" ","_",$_FILES['passport']['name'])) or exit('Upload failed.');
} else {
exit('File not found');
}
?>
Any additional information you want to send with the file needs to be added to the FormData object. These will appear in the PHP $_POST variable.
formdata.append('field', 'data');
Bear in mind that these APIs are not universally supported in browsers, so best practice is to include all the usual feature detection scripts before the user reaches this point.
You could also bind the upload function to the change event of the file input instead of asking for a button click...
$('#passport').change(function() { ...
Hope that helps.
There is 2 problems :
You need to add the attribute enctype="multipart/form-data" in the form tag if you want to upload files:
replace
<form name="frm">
by
<form name="frm" enctype="multipart/form-data" >
With ajax (and jquery), you cannot send file directly. But I suggest you that jquery form plugin who can help you with that
I was trying to simulate the browser (and simulate XSS). Someone recommended me PhantomJS, however, I had some problems with executing simple JS commands.
I've created simple php website: xss.php
<form id = "myform" action="xss.php" method="POST">
<input id="x" name='x' type="text" />
<input type="submit" value="ok" />
</form>
<?php
echo $_POST['x'];
$fp = fopen("logs.txt", "a");
fwrite($fp, $_POST['x']);
fclose($fp);
?>
<script>document.getElementById('x').value='payload';
document.getElementById('myform').submit();</script>
When I run it from my browser, the form is sent (and its results its put into logs.txt. However, there is a problem, while trying to run that website via PhantomJS:
run.js:
var page = require('webpage').create();
var url = 'http://127.0.0.1/xss/xss.php';
page.open(url, function (status) {
if (status !== 'success') console.log('Network error');
else
{
var p = page.evaluate(function () {
});
console.log('DONE');
}
phantom.exit();
});
I run it via command line: ./phantomjs run.js
As far as I understand, this script should simulate the browser behavior and send the above form. However, there is nothing in logs.txt, which means, that phantomjs didn't run that script. Could you please tell me what I did wrong?
Your script puts the browser into an eternal loop, reloading the page xss.php. This will put the word 'payload' into logs.txt, until you stop javascript execution.
If you want to simulate form submition, you must explicitly send POST data to php script:
var page = require('webpage').create();
var url = 'http://127.0.0.1/xss/xss.php';
var data = 'x=phantom';
page.open(url, 'post', data, function (status) {
if (status !== 'success') console.log('Network error');
else
{
console.log('DONE');
}
phantom.exit();
});
This will feed POST data to xss.php, appending the word 'phantom' to logs.txt. But mind, that, unlike the browser, PhantomJS won't go into eternal loop and will send the request only once.