How to run html form coming from Javascript GET Request? - javascript

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>)
});

Related

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

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

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>

Huge data string passing in url

I have created a html page which has a div displaying image.I have to pass the base 64 image string into this html page in the url so that I can set the image div source on loading.
The html page can be called from any application may be java/javascript or any.But along with the url the image string has to be passed to the page. Here is the sample html application which calls my html page-
<!DOCTYPE html>
<html>
<body>
<script>
imagestring ="R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7";
</script>
<button type="button" onclick="window.open('URL?image='+imagestring)">open the html page </button>
</body>
</html>
Here URL points to the html page deployed on a server.This works fine only if the imagestring value is small.
But if the size is huge because of the limitation on several browsers it won't work.What alternate way I can approach?
My requirement is huge datastring passing in url.
You need to POST the image data.
<!DOCTYPE html>
<html>
<body>
<form action="URL" method="POST">
<input type="hidden" name="image" value="R0lGODlhEAAOALMAAOazToeHh0tLS/7LZv/0jvb29t/f3//Ub//ge8WSLf/rhf/3kdbW1mxsbP//mf///yH5BAAAAAAALAAAAAAQAA4AAARe8L1Ekyky67QZ1hLnjM5UUde0ECwLJoExKcppV0aCcGCmTIHEIUEqjgaORCMxIC6e0CcguWw6aFjsVMkkIr7g77ZKPJjPZqIyd7sJAgVGoEGv2xsBxqNgYPj/gAwXEQA7"/>
<button type="submit">open the html page</button>
</form>
</body>
</html>
Standard URLs which use GET method by default have a limit of about 8KB in length.
If you want to send large data to the server, you must use POST method. In this case, URL remains short, and actual data will be sent to server as parameters in your submit form.
You can also POST data using ajax, like this.
You are using GET method to passing your data. you can't pass huge data by GET method. check this out: HTTP URI GET limit
Use POST method.

jquery get method doesn't do anything, but doing it as a form does (java servlet)

I have a file called index.jsp which is where a user is directed to upon loading my website.
I want to send a get request to one of my servlets upon loading the page.
So my URL at the beginning is:
localhost:8080/Test/
The servlet will do something when the URL is:
localhost:8080/Test/MyServlet?action=fetchdata
I can get the servlet to perform fetchdata if in the html body i put this:
<form name="fetchdata" action="MyServlet" method="get">
<input type='hidden' name='action' value='fetchdata' />
</form>
and then run a script:
<script type="text/javascript">
document.fetchdata.submit();
var testresult = '${result}';
document.write(testresult);
</script>
However this does not look nice and it is also in the HTML body which seems very unprofessional. So I tried implementing the same function in JQuery by putting this in
the HTML head:
window.onload = function() {
$.get("MyServlet", { action : "fetchdata"});
};
and nothing happens when I load the page. I have tested to see that jQuery is working. Any idea on what is wrong? Thanks
Try this instead:
$("form[name='fetchdata']").trigger('submit');

How to pass id value from JSP to select query as input before submit?

How to get ID value in scriptlet before submit?.
My actual scenario is --- I created one JSP page, in which employee ID is the input. Now on blur, I want to get this ID and pass it to a SQL query for validation. Is it possible to send the ID value to SQL before submitting the form? If so, please guide me accordingly with example. If I use, request.getParameter the ID value is coming as null.
Send an ajax request. jQuery is extremely helpful in this. Kickoff example:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
$("#id").blur(function() {
$.getJSON("validateId", $(this).serialize(), function(data) {
$("#id_message").text(data.valid ? '' : 'invalid!');
});
});
});
</script>
<style>
.error { color: red; }
</style>
</head>
<body>
<form action="someservlet" method="post">
<label for="id">id</label>
<input id="id" name="id" />
<span id="id_message" class="error"></span>
<br/>
<input type="submit">
</form>
</body>
</html>
With a servlet which is mapped on an URL pattern of /validateId and does the following in doGet() method:
boolean valid = validateId(request.getParameter("id"));
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("{valid:" + valid "}");
That's it. The validateId() method example should of course do the DB job and return true or false depending on the outcome.
Note that you still need to perform the same validation in the server side in the servlet behind URL someservlet. JavaScript is namely disableable/spoofable/hackable. When the server side validation fails, just put the message in a map in the request scope, let the servlet redisplay the JSP and let the JSP display the message using EL.
<span id="id_message" class="error">${messages.id}</span>
... yes, through use of javascript, your ajax call will have to talk to the server, no sample here but you should be able to find lots of examples with a little 'googling'

Categories

Resources