A callback function triggers when my XMLHttpRequest has finished. I use an asynchronous JavaScript Function to load the content of a file that has been created by the PHP file_put_contents() function.
My problem is, that sometimes loading the gallery elements takes a very long time. I should rather return the html code I want to load as a string instead of writing it into a file.. but I do not know how?
This is my Javascript:
function xhr(php, form, after) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == XMLHttpRequest.DONE) {
after();
}
}
xhr.open('POST', php, true);
xhr.send(new FormData($(form)));
}
How can I get the corresponding PHP script to export a String? I would need something that puts $myExportString as parameter inside after() then I could use it like this:
xhr("../session/searchquery.php", "searchfilterterms", function( myExportString ) {
document.getElementById("someDiv").innerHTML = myExportString;
});
How can this be done?
There's no need to save a file on the server. You can just return the generated HTML string in the response to your XmlHttpRequest, and then write some Javascript to put that HTML into your page.
Otherwise a) you've got the overhead of disk I/O, and b) you're having to make 2 requests to the server (one to generate the HTML, and another to retrieve the file it's been saved to). This is not efficient at all.
In the PHP, instead of saving the generated HTML string to the disk, you can echo it, e.g. something like
echo $finalVariableWithHTMLString;
(I don't know your exact code as it's not shown in the question). If you echo it, then it becomes the contents of the response to the AJAX call. That's how you return a response to a HTTP request in PHP - you echo stuff to the output.
You can then get it from the xhr.responseText variable in the JavaScript. So you'd be able to write
after(xhr.responseText);
in your example, to pass the HTML to your after() function.
Related
I am trying to show multiple xml file into html. I able get single xml file show in html table by using xmlhttp.open("GET", "204S_2000_02_17_00_30_357.xml", true). However, I can't get multiple xml file using this function.
I had tried using xmlhttp.open("GET", "*.xml", true) but doesn't get any output.
It's any solution or method to "GET" the multiple xml file into html?
Noted: xml file will continuously generate in folder with random name.(example 204S_2000_02_XX_XX_XX_XX.xml).
code that show single xml file in html table
function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xmlhttp.open("GET", "204S_2000_02_17_00_30_357.xml", true);
xmlhttp.send();
}
function myFunction(xml) {
//coding....
}
One HTTP request gets one HTTP response.
In general, you can't get multiple files back from a single request using a wildcard.
You could, if you wrote suitable server-side code, have the server recognise a wildcard in the URL and respond by (for example) sending a zip file containing all the files that matched, or generating a new XML document containing the contents of all the files that matched.
Generally, however, you will make a separate request for each resource you want. Having determined all the URLs you wanted to request, you would probably want to use an API that supported promises (i.e. fetch instead of XMLHttpRequest) so you could feed them into Promise.all and run the next stage of the program once you had collected all the data.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhttp.open("GET", "https://zbapi.herokuapp.com/", true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
This is my code. It is returning html text but i want it to load html output.
It is returning html text but i want it to load html output.
alert expects to be passed plain text.
You need to put the HTML source code somewhere which expects HTML source code.
For example, the innerHTML of an Element object.
The URL you are requesting, however, includes relative URLs and has its own JS. It doesn't make much sense to request it with JS and then try to render it. You would also certainly be better off just triggering navigation with location = "https://zbapi.herokuapp.com/".
You need to parsing HTML page to JSON with some parser on the server and send parsed data to the client in JSON format. For example, Himalaya (in Node.js).
Official repository of Himalaya
or use html2json (NPM Repository) to parse on client
I'm making a JavaScript script that is going to essentially save an old game development sandbox website before the owners scrap it (and lose all of the games). I've created a script that downloads each game via AJAX, and would like to somehow upload it straight away, also using AJAX. How do I upload the downloaded file (that's stored in responseText, presumably) to a PHP page on another domain (that has cross origin headers enabled)?
I assume there must be a way of uploading the data from the first AJAX request, without transferring the responseText to another AJAX request (used to upload the file)? I've tried transferring the data, but as expected, it causes huge lag (and can crash the browser), as the files can be quite large.
Is there a way that an AJAX request can somehow upload individual packets as soon as they're recieved?
Thanks,
Dan.
You could use Firefox' moz-chunked-text and moz-chunked-arraybuffer response types. On the JavaScript side you can do something like this:
function downloadUpload() {
var downloadUrl = "server.com/largeFile.ext";
var uploadUrl = "receiver.net/upload.php";
var dataOffset = 0;
xhrDownload = new XMLHttpRequest();
xhrDownload.open("GET", downloadUrl, true);
xhrDownload.responseType = "moz-chunked-text"; // <- only works in Firefox
xhrDownload.onprogress = uploadData;
xhrDownload.send();
function uploadData() {
var data = {
file: downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1),
offset: dataOffset,
chunk: xhrDownload.responseText
};
xhrUpload = new XMLHttpRequest();
xhrUpload.open("POST", uploadUrl, true);
xhrUpload.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
xhrUpload.send(JSON.stringify(data));
dataOffset += xhrDownload.responseText.length;
};
}
On the PHP side you need something like this:
$in = fopen("php://input", "r");
$postContent = stream_get_contents($in);
fclose($in);
$o = json_decode($postContent);
file_put_contents($o->file . '-' . $o->offset . '.txt', $o->chunk);
These snippets will just give you the basic idea, you'll need to optimize the code yourself.
I apologize in the advance as I am a total beginner.
I have a pre-existing html form with text fields. I need to have a button that will allow me to upload a txt file (since when trying to look for answer about this, I learned javascript can't just access a file from my PC without me actively uploading it). Then I need the values from this txt file inserted into the text fields (for example, the form has: name, last name, phone etc - and the file will fill out this info).
I am going crazy trying to collect bits and pieces from other people's questions. any help would be greatly appreciated!
it depends on how you would like to have this handled, there are basically two options:
File Upload and page redirect
you could provide a file upload form to upload your textfile, redirect to the same page via form submission, handle the data on serverside (e.g. parse the file and get the values out of it) and let the server inject the values as default properties for the form file which is returned to the browser
XMLHttpRequest File Upload
in modern browsers, the native xhr object supports an upload property, so you could send the file via that upload property. it has to be sent to a serverside script that parses the file and returns the values in a fitting format, e.g. json (which would look like this: {'name':'somename', 'lastName':'someothername'}). then you have to register an eventlistener on completion of this upload (e.g. onload) and set these values on javascript side.
check this out for XMLHttpRequest upload (better solution in my opinion): https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Submitting_forms_and_uploading_files
edit:
well, the easiest solution would be just to provide a textfield and paste the content of the file into this field, hit a button and the content is parsed. then you wouldn't rely on network traffic or even a serverside handling, but could do everything with javascript, e.g. like this:
dom:
<textarea id="tf"></textarea>
<button id="parse">fill form!</button>
js:
var tf = document.getElementById("tf");
document.getElementById("parse").addEventListener("click", function(){
var formData = JSON.parse(tf.value);
//if your textfile is in json format, the formData object now has all values
});
edit: from the link i posted in the comments:
<!-- The HTML -->
<input id="the-file" name="file" type="file">
<button id="sendfile">send</button>
and
document.getElementById('sendfile').addEventListener("click", function(){
var fileInput = document.getElementById('the-file');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
var xhr = new XMLHttpRequest();
// Add any event handlers here...
xhr.open('POST', '/upload/path', true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var values = JSON.parse(xhr.responseText);
//these are your input elements you want to fill!
formNameInput.setAttribute('value', values.name);
formFirstNameInput.setAttribute('value', values.firstName);
}
}
xhr.send(formData);
});
as already said, your serverside has to parse the file and respond with json
I have a script that generates about 250 images from canvas.toDataURL().
My question is how to save them all at once (one request to server) instead of posting them individually.
I need a way to pack them in single request and then send them to PHP server for unpacking.
canvas.toDataURL() gives the byte data encoded in base64, they are safe to be used as strings and passed through HTTP.
do something like:
var images = [];
while(....) {
images.push(canvas.toDataURL());
}
var imagesJson = JSON.stringify(images);
// pseudo code of jQuery ajax, you can make use of form and a hidden field
// or any other way you'd like to query the server
$.ajax({
....
send:{images:imagesJson}
....
});
with PHP (other server side languages should almost be the same):
$images = json_decode($_POST['images'], true);
foreach($images as $image) {
$image = base64_decode($image);
file_put_contents('<path to file>', $image);
}