I am loading my table on document.ready() from a json file as follows
document load....
$(document).ready(function () {
getSummaryData(function (data1) {
var dataarray=new Array();
dataarray.push(data1);
$('#summaryTable').DataTable({
data: dataarray,
"columns": [
---
---
and retrieving the data from a file as follows
function getSummaryData(cb_func1) {
$.ajax({
url: "data/summary.json",
success: cb_func1
});
console.log(cb_func1)
}
This was essentially loading dummy data so i could I could figure out how to load the table correctly etc. This works fine.
It does following
1. page loads
2. reads data from file
3. populates table
In reality, the data will not be loaded from file but will be returned from xhr response but I am unable to figure out
how to wire it all together. The use case is
POST a file via XMLHttpRequest
Get response
populate table (same data format as file)
I will post the file as follows...
<script>
var form = document.getElementById('form');
var fileSelect = document.getElementById('select');
var uploadButton = document.getElementById('upload');
---
form.onsubmit = function(event) {
event.preventDefault();
---
---
var xhr = new XMLHttpRequest();
// Open the connection.
xhr.open('POST', 'localhost/uploader', true);
// handler on response
xhr.onload = function () {
if (xhr.status === 200) {
console.log("resp: "+xhr);
console.log("resptxt: "+xhr.responseText);
//somehow load table with xhr.responseText
} else {
alert('ooops');
}
};
// Send the Data.
xhr.send(formData);
So ideally I need one empty row in the table or similar until someone uploads a file and then the table gets populated with the response.
Any help much appreciated.
var xhr1 = new XMLHttpRequest();
xhr1.open('POST', "youruploadserver.com/whatever", true);
xhr1.onreadystatechange = function() {
if (this.status == 200 && this.readyState == 4) {
console.log(this.responseText);
dostuff = this.responseText;
};//end onreadystate
xhr1.send();
It looks mostly correct, You want the this.readyState == 4 in there. what is your question, how to populate a table from the response?
That also depends on how you are going to send the data and how the server is going to parse the data, looks like you want to use a json format which is smart. JSON.stringify(formdata) before you send it and then make sure your server parses it as a json object Using body-parser depending on what server you are using. and then you JSON.stringify() the object to send it back.
Related
I have configured my TinyMCE to use images_upload_url and images_upload_handler to post to a selected image to a server-side page which saves the image to a location on my server. In addition, this server-side page also saves the filename of the image as a record within a database.
I then have another server-side page which reads the database and constructs a JSON list of the images that have been uploaded. This JSON data is then pulled into my Tinymce instance using image_list, so that I can easily reuse previously uploaded images as opposed to having to reupload the same image more than once.
The specific lines of my tiny.init() are:
image_list: 'processes/image-list.php',
image_class_list: [
{title: 'None', value: ''},
{title: 'Full width image', value: 'img-responsive'}
],
images_upload_url: 'processes/upload-image.php',
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'processes/upload-image-free.asp');
xhr.onload = function() {
var json;
if (xhr.status != 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
if (!json || typeof json.location != 'string') {
failure('Invalid JSON: ' + xhr.responseText);
return;
}
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
xhr.send(formData);
},
image_dimensions: false,
All of this works as expected.
What I would like to do is also save a description of the image to the database so this can be outputted as the title within the JSON data of previously uploaded images.
As the upload feature only allows an image to be selected from a file system I cannot utilise the upload feature:
So I thought I could utilise the alternate description field of the image feature/modal but this would have to be done via a JavaScript triggered event that is triggered upon submitting the image feature/modal, that takes the content in the alternative description input field and POST this to a serverside page that can update the database.
Unless there is another way does anybody know how I can target the 'click' on the 'save' button within the image feature to extract the alternate description before the image feature/modal disappears and extract the input field content?
From there I should be able to work out how to get this to a server-side page to update the database.
Many thanks in advance
I have managed to resolve this so posting a solution to help others - though this is more than a hack.
Firstly on my form page after the tiny.init is loaded I am using the following:
document.addEventListener('keyup', logKey);
function logKey(e) {
labels = document.querySelectorAll(".tox-label");
for (i = 0; i < labels.length; ++i) {
if (labels[i].textContent == "Alternative description"){
imageDescription = document.getElementById(labels[i].htmlFor).value;
}
}
};
This loops through all the elements (labels in this case) which have a class of .toxlabel and if the textContent matches "Alternative description" then to capture the value in in a variable called 'imageDescription'.
Then within my tiny.init I have the following:
editor.on('ExecCommand', function(e) {
if (e.command == "mceUpdateImage"){
var http = new XMLHttpRequest();
var params = encodeURI('desc=' + imageDescription);
http.open('POST', 'processes/upload-image-description.asp', true);
http.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(params);
}
});
This code is actioned upon the mceUpdateImage modal closing, it takes the value stored within the imageDescription variable and posts it to a server-side page which updates the database.
I am sure there are cleaner ways but they would require more of a TinyMce understanding.
I'm recently working on a website project. Therefor I have a website.php with all html code, a function.php and saveArray.js . In website.php I'm printing a html table with a button at the bottom. Through the button click I'm getting to the saveArray.js, where I save all the table data in an array.
With this code
var arrString = JSON.stringify(tableData);
var request = new XMLHttpRequest();
request.open('post', 'function.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-
urlencoded');
request.send('daten=' + arrString);
I post the JS array to function.php. In function.php I do something with the array and in an if statement I want to show a modal.
The modal itself works, but I want to show it on website.php page. Which doesn't happends, because I'm currently on function.php .
How can I solve this ?
EDIT: In my array is an ID and I want to check if this ID is already in my database or not. Depending on this result I want to show the modal and upload the data if necessary. All the checking is happening in function.php
I suppose you want to inject the string returned (the modal PHP code) by your function in function.php in your current page ('website.php').
To do this, you'll have to inject the response given by the XMLHttpRequest when the request is finished.
Let's suppose we want to add all the contents within
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
See, You are not handling the response of the request.So handle the response.and restuern the status of the request from function.php and if data is saved the open the model. You need not go to the function.php page. See the code
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// this is response of the request //now check it
//Suppose you returned " data saved" as response from function.php
if(this.responseText='data saved'){
//Open model here
}
}
};
xhttp.open("POST", "function.php", true);
xhttp.send();
I am making a Pokedex API as a side project and I can not display the data needed to display in the different text boxes. I am using a GET request to request the height, weight, type, and ability.
<script>
$("button").click( function(){
var pokemonName = $('pokemon').val(pokemon);
event.preventDefault();
getPokemonData(pokemonName);
})
function getPokemonData(pokemonName){
var request = new XMLHttpRequest()
//GET request with link
request.open('GET','https://pokeapi.co/api/v2/pokemon/' + pokemonName, true);
// request for data
request.onload =function(){
var data = JSON.parse(this.response)
if(request.status >= 200 && request.status <= 400)
{
// outputs data
$(pokemonheight).val(response.height)
$(pokemonweight).val(response.weight)
$(pokemonAblity).val(response.ability)
$(pokemonType).val(response.type)
}
else
{
alert ("Error");
}
request.send();
}
}
</script>
</html>
I have tried setting a variable that would be equal to the response JSON element and then input that into the value of the textbox.
I do not have anything returned as expected or input displayed in the console if declared.
Issue(s)
There were a few issues with your code:
var pokemonName = $('pokemon').val(pokemon); you are setting the value of some element named pokemon (not valid) here
var data = JSON.parse(this.response); where is this.response being set? Shouldn't we be receiving response in the callback?
request.send(); is inside of the onload event, so the request never gets sent
Critiques
My main critique here is that you included a fairly large library (jQuery), and didn't utilize it to make the request. $.ajax is well documented and cleans up a lot of the intricacies of XMLHttpRequest.
The solution
$("button").click(function() {
var pokemonName = $('#pokemon').val();
//event.preventDefault();
getPokemonData(pokemonName);
})
function getPokemonData(pokemonName) {
var request = new XMLHttpRequest()
//GET request with link
request.open('GET', 'https://pokeapi.co/api/v2/pokemon/' + pokemonName, true);
// request for data
request.onload = function(response) {
var data = JSON.parse(response.currentTarget.response)
if (request.status >= 200 && request.status <= 400) {
// outputs data
console.log(data)
} else {
alert("Error");
}
}
request.send();
}
<input id="pokemon" value="12" />
<button>search</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Taking all the above issues into account, I was able to get a working example of what it should ultimately look like.
Hope this helps!
I have a webpage that echoes out a list of files(pdfs) that i have uploaded in a MYSQL database. When i upload a new file, i would like to automatically update this list to include the new file that i have uploaded without having to refresh the entire webpage.
This is my HTML code that displays the updated list through the variable $mypdf_list :
<div id="listwrapper_hook">
<div id="dynamic_listwrapper"><hr>
<!--DYNAMIC PDF LIST CONTENT GOES HERE-->
<?php echo $mypdf_list; ?>
</div>
</div>
I have tried the to swap out the 'dynamic_listwrapper' div and then replace it with a new one through javascript in the hope that the displayed 'mypdf_list' variable is refreshed. But this has not worked.
MY javascript code:
//UPDATE 'Recently Uploaded Files'
var wrapper_hook = document.getElementById('listwrapper_hook');
var list_wrap = document.getElementById('dynamic_listwrapper');
wrapper_hook.removeChild(list_wrap);
//Add child again to update the '$mypdf_list'
wrapper_hook.appendChild(list_wrap);
Thanks for all the advice everyone. Ajax call was the way. Here is my solution (which works) in javascript:
// GET REFRESHED '$mypdf_list'
// AJAX CALL
var formdata = new FormData();
formdata.append("update",'refresh');
// create XMLHttpREquest object
var xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
// HANDLE RESPONSE HERE
document.getElementById('dynamic_listwrapper').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "getMypdf_list.php");
xmlhttp.send(formdata);
}
Use ajax for it.
The code will look slightly like this:
setInterval(function () {
var url_to_fetch_pdfs = "www.yourdomain.com/fetch_pdfs.php";
$.ajax({
type: "POST",
url: url_to_fetch_pdfs,
cache: false,
success: function(result){
$("#dynamic_listwrapper").html("<hr>"+result);
}
});
}, 60000); // 1 Minute
In your PHP file you will fetch all the pdf downloads, the result in the ajax variable will be the echo in your PHP fetch file.
Ajax Documentation
I am attempting to process a user-uploaded file in javascript and then upload the file to the server. Once the processing is complete, I want the upload to work as it would have if I had not interrupted it with javascript. That is, I want to send a POST request to something like "receive_file.php" where the form validation, move_uploaded_file(), and a "successful upload" message to the user will occur. I have tried this in jquery, and I get an UPLOAD_ERR_NO_FILE from php:
function upload(file) {
var form = $("<form/>", {
enctype: "multipart/form-data",
method: "POST",
action: "/path/to/recieve_file.php"
});
form.append($("<input/>", {
type: "file",
name: "audio_file",
value: file
}));
form.submit();
}
As far as I can tell, its not possible to write to an input type="file", only read from it. Still haven't found a great answer for this one, but what I have settled on is overwriting the current document with the response from an ajax request like so:
var fd = new FormData();
fd.append("audio_file", file);
var xhr = new XMLHttpRequest();
xhr.open('POST', 'recieve.php', true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
document.open();
document.write(xhr.response); // just overwrite the whole current document with "recieve.php"
document.close();
}
};
xhr.send(fd);