PHP - Use API That Only Offers HTML + JS With PHP Script - javascript

I have a conversion (HTML2PNG) I need to automate in a PHP script using a REST API. However, the only example provided on the website was via HTML and JavaScript where one can only upload the HTML file to be converted in a form.
My PHP script already generates HTML files in a loop, thus, I'd like to simply pass these generated HTML files to the API which then returns the download URL of the converted PNG file which I know I can use wget to retrieve. This is the code as offered by the service.
<form action="#" method="post" enctype="multipart/form-data" name="conversionform" id="conversionform">
<p>Local file: <input id="file" name="file" type="file" /></p>
<p>Target format:
<select name="targetformat" id="targetformat"">
<option value="png">PNG</option>
</select>
</p>
<p><input type="button" value="Convert" onclick="convertpdfform()" /></p>
<p><span id="resulttext">Conversion Results: </span></p>
</form>
<script src="https://www.aconvert.com/js/jquery.min.js"></script>
<script src="https://www.aconvert.com/js/jquery.form.js"></script>
<script type="text/javascript">
$(document).ready(function() {
});
function showResponse(responseText, statusText, xhr, $form) {
resulttext.innerHTML=responseText;
}
function showError(responseText, statusText, xhr, $form) {
}
function convertpdfform() {
options = {
success: showResponse,
error: showError,
url: "https://s2.aconvert.com/convert/api-win.php",
};
$('#conversionform').ajaxForm(options);
$('#conversionform').ajaxSubmit(options);
return false;
}
</script>
What I've Tried
Emailed them to ask for PHP examples and I got 'there are no PHP examples' as response.
I know value="png" is what the API gets to determine the output file.
How can I simply pass the file without using a web browser and still get the download URL of the converted file?
P:S - I'm not only using the site because of html2png, they offer tons of other conversion services.

maybe you can create a file based on the HTML code produced by your PHP script and try to emulate the uploading on the form it self. like how web scraping works but simulating the clicks and upload too.
you can definitely do it by looking at the web request. Use Chrome to see the actual request from beginning to end

Related

How to run html form coming from Javascript GET Request?

I have tried to call some API, and the API gives a html response whose content is an auto submit form by onload. so the question is How to submit the form obtained from the response API?
jquery function :
$.get( "example.html", function( data ) {
//response is html
});
response from APi (example.html) :
<!DOCTYPE html>
<html>
<head></head>
<body onload="submitOnLoad.submit();">
<form id="submitOnLoad" method="POST" action="example.com/save">
<input type="hidden" name="name" value="john" />
<input type="hidden" name="birthday" value="23-03-2003" />
</form>
</body>
</html>
Edit :
I'm sorry I was not clear. I need other solution.
First, jQuery is just a library of functions to make coding easier, especially the short hand for browser api's.
Second, you wouldn't want to get an html page via ajax, because the browsers can anyways handle the request over a webserver.
Ajax is mostly used with Restful Server end points for Data exchange, rather than getting entire HTML files.
However, if you are only playing around to learn, try this snippet. be sure to pass the html string.
$.get( "example.html", function( data ) {
$('body').html(<response html string>)
});

Download file returned after uploading a file : An AJAX file converter

I'm programming a PHP function that encrypts a file using a specific key. I want the user to upload his file using the "browse..." window then get the "save as" window as a result after the php encrypting.
I'm working in full AJAX so my upload method uses a hidden form and a hidden iframe to handle the upload request.
Javascript Part :
<script>
$("#encryptFileButton").button().click(clickEncryptFile);
function clickEncryptFile() {
if (!jQuery.browser.msie) {
$("#encryptFileBrowse").click();
} else {... not the matter of the question ...}
}
function encryptFileBrowseChange() {
$("#uploadAttachmentForm").submit();
}
</script>
The nice visible button
<button id="encryptFileButton" type="button" class="ui-..." role="button">Encrypt Now</button>
The hidden part
<form action="https://web.com/encryptPHP" id="uploadAttachmentForm" target="uploadTarget" style="display:none" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="encryptFileBrowse" id="encryptFileBrowse" onchange="encryptFileBrowseChange()">
</form>
<iframe id="uploadTarget" name="uploadTarget" src=""></iframe>
Now on the server side, the encryptPHP does the job and returns the encrypted file with all the required HTTP headers. But the browser does not open the "save as window"
Here is the Chrome inspector of the request
Can you help me to fill the download part of this problem ?
I wouldn't like using a temporary file on the server to be stateless and prevent orphan files when browser is interrupted. I'd really like to make this with only one query.
In the server response, Content-disposition is inline, it must be content-disposition: attachment to get the "save as " popup.
I don't delete my question as the code example is pretty and usefull.
Uploading and downloading in only one request is nice.

How to post multiple files to server one by one (due to server side restriction) using javascript from html input type file control

I have some server side restriction.
I want to read file to server one by one using javascript, in such a way that second file will post only after the response from previous file is received.
I have a multiple file upload in my webform as below:
<form id="frmSearchByC2V" method="post" enctype="multipart/form-data">
<input class="file" style="width:50px" type="file" name="c2vFile" id="txtSearchC2V" disabled onchange="locateFiles();" />
</form>
In my javascript i have code something like
<script>
function locateFiles()
{
var fileChooserControl = document.getElementById("txtSearchC2V");
var selectedFileLength = fileChooserControl.files!=null?fileChooserControl.files.length:1;
for(var i=0; i < selectedFileLength; i++)
{
document.forms["frmSearchByC2V"].action="locateFiles.html;
//Ajax call to submit the form
AIM.submit(document.getElementById("frmSearchByC2V"), {'onStart' : function(){return true;}, 'onComplete' : function(response){
loadSearchTargetGrid(response);
}});
document.getElementById("frmSearchByC2V").submit();
}
}
function loadSearchTargetGrid(response)
{
alert(response);
}
</script>
My problem is that whenever i post multiple file using window browser button. Everytime a received the same file to server. eg i choose file.txt,file2.txt,file3.txt and submit the form via javascript, i receive file3.txt in every request i made to the server.
Please provide the solution to fix this issue
If you're using YUI, you can use the Uploader utility. Uploader will upload each file in its own POST request and additionally you can set its simLimit attribute to 1 so that it only makes one request at a time. See: http://yuilibrary.com/yui/docs/uploader/.

Upload files without refreshing the page by using ajax post

I have a page file-upload.jsp with the code snippet below:
<form action="" id="frmupload" name="frmupload" method="post" enctype="multipart/form-data">
<input type="file" id="upload_file" name="upload_file" multiple="" />
<input type="submit" value="Update" />
</form>
I have 2 questions:
The moment I select some files, i.e the onchange event of the input type file, the file(s) should get uploaded.
I have a Java page that receives multipart request parameter and uploads the file to the said location. My problem is the form submission onchange, so that the Java file can proceed with further operations.
I googled and went through lot of articles. Some say it's not possible to upload files directly via Ajax, some say submit the form to an iframe via Ajax/jQuery.
I tried a lot of code from internet, such as this:
$(document).ready(function(){
$('upload_file').change(function(){
var data = new FormData();
data.append('file', $(this[0].files[0]));
$.ajax({
url: 'photo.jsp',
type: 'post',
contentType: attr('enctype', "multipart/form-data"),
data: data,
success: function(data){
alert(data);
}
})
});
});
but could not get the expected results.
I also need a progress bar for the upload operation.
Look at this example using an IFrame, is in PHP but changing the action should do the trick
Ajax Style File Uploading Using Hidden IFrame
Since you're already using jQuery, I would definitely go for the jQuery Form Plugin, which allows you to do form uploads via AJAX, even if the form contains a file input.
There is an example on its website available that shows how to display a progress bar.
Look at this example it is exact as you want
http://www.asp.net/ajaxlibrary/ajaxcontroltoolkitsamplesite/asyncfileupload/asyncfileupload.aspx

How do I use ajax to upload a text field and a file?

I'm new at AJAX and am working on an implementation of a form that will upload a name and a file to a php file that processes the data and sends it to a database for insertion using mysqli. I've tested the php file and it does work. My problem is in the AJAX code. I've tried an implementation using XMLHTTP and using jQuery. Both leave the page and open the PHP file in the browser. As a disclamer, I posted this question to another coding site, a fight ensued between two posters, and so I'm trying here to hopefully get a reasoned and calm response with productive suggestions.
I realize that currently "get" is being sent to the PHP file rather than "post", but PHPStorm tells me that "post" is not available in that form. What's my alternative? Am I on the right track or is there another direction I should go? How do I refresh only the form and keep the PHP page from loading?
Here's the relevant snippet of my code,
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="jquery.validate.js"></script>
<script>
$(document).ready(function() {
$('#addForm').validate({
submitHandler: function (form) {
$('input[name="usingAJAX"]', this).val('true');
var url = $(form).prop('action');
var dataToSend = $(form).serialize();
var callback = function(dataReceived) {
$(form).hide();
//result message
$('body').append(dataReceived)
};
var typeOfDataToReceive = 'html';
$.get(url, dataToSend, callback, typeOfDataToReceive),
return false;
}
});
});
</script>
</head>
<body>
<form id="addForm" action="addInfo.php" enctype="multipart/form-data">
<input type="hidden" name="usingAJAX" value="false"/>
<label for="aname">Name: </label>
<input type="text" name="aname" id="aname" class=required/>
<label for="aimage">Photo: </label>
<input id="aimage" type="file" name="aimage" class="required">
<input type="submit" value="ADD"/>
</form>
</body>
</html>
Until recently you could not upload files with ajax.
You still cannot upload the file directly with ajax, but you can do it programatically with HTML5 File API.
Still, if you are looking for simple solutions, try traditional IFrame approach.
If you want bleading edge technology, use File API. Here is some tutorial how to read files with javascript.
The steps to upload with ajax:
Read file with javascript FileReader API.
Post the content of the file, encoded to base64 or something, to the server.
Serverside, decode the contents of the file programatically.
When using this approach, the file will not be handled as a file upload by the server. It will be just another request field with text inside. It is up to you to decode it on the server side.
The filereader API allows you to read the file portion by portion and upload fragments of file, so it would be possible to upload huge files in chunks, but you need to handle it yourself.
Try using plugin jQuery form.js http://www.malsup.com/jquery/form/#file-upload You can upload files with ajax and jQuery. It is easy to use, just need to give #form-id in ajaxSubmit function.
<script>
$(document).ready(function() {
$('#addForm').validate({
submitHandler: function (form) {
$('input[name="usingAJAX"]', this).val('true');
var options = {
url : $(form).prop('action'),
dataToSend : $(form).serialize(),
callback : function(dataReceived) {
$(form).hide();
//result message
$('body').append(dataReceived) },
typeOfDataToReceive = 'html';
//your options here
};
$('#yourFormid').ajaxSubmit(options);
return false;
}
});
});
</script>

Categories

Resources