So the problem is: a user uplaods a file. I use е.PreventDefault(); to prevent the page from refreshing after the upload. Under the file upload form i've made a list of all the user's file names. Obviously the newly uploaded file name isn't in the list. After refreshing the page it gets in the list, but the business logic is that the file's name should go in the list withouth refreshing the page.
function showNewFileProperies() {
var xhttp;
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("results").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "../../app/Models/UserFiles.php" , true);
xhttp.send();
}
This is the request with which I thought my problem would be solved.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class UserFiles extends Model{
protected $table = 'files';
public function getUserFiles(){
$getFiles = Filecontent::where('userid', Auth::id())->get();
foreach($getFiles as $getFile) {
$result = $getFile->filename;
return $result;
}
}
}
I'm using Laravel and Dropzone.js. The js code i put in the success event of dropzone.js
Sorry for the delay in response. Here is what I used to achieve what you are describing. Sorry for the bad indenting but this editor is really bad.
Dropzone.options.documentDropzone = {
paramName: "file",
dictDefaultMessage: "Drag your document over this box to upload or click here",
maxFilesize: 100, // MB
maxFiles: 10,
addRemoveLinks: true,
dictRemoveFile: 'Remove Attachment',
accept: function(file, done) {
done();
},
init: function() {
this.on("addedfile", function(file) {
busy_uploading = true;
});
this.on('removedfile', function(file){
remove_file(file.previewElement, file.fileID);
if(this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
busy_uploading = false;
}
});
this.on("complete", function (file) {
if(this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
busy_uploading = false;
}
});
},
success: function(file, response) {
response = JSON && JSON.parse(response) || $.parseJSON(response);
if(response.error) {
var node, _i, _len, _ref, _results;
var message = response.error;
file.previewElement.classList.add("dz-error");
_ref = file.previewElement.querySelectorAll("[data-dz-errormessage]");
_results = [];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
node = _ref[_i];
_results.push(node.textContent = message);
}
return _results;
} else {
for(var i = 0; i < response.file_id.length; i++) {
file.fileID = response.file_id[i];
file.fileEXT = response.file_ext[i];
add_file_id(response.file_id[i]);
//You can add the uploaded item in your list here
}
return file.previewElement.classList.add("dz-success");
}
}
};
So this is roughly what I used. You can simply add the item on your list in the success function since that is where you will get the response from the server.
I did not include the php because it is just your basic upload script. This will work with as many files as you wish.
If you need more help just add a comment and I will try to assist you as best I can.
Actually I came up with this:
public function getCurrentFile(){
$userid = Auth::id();
$getFiles = File::where('userid', $userid)->orderBy('created_at', 'desc')->take(1)->get();
foreach($getFiles as $getFile) {
$result = $getFile;
$json = json_encode($result); //make it as json
return $json;
//echo $result;
}
}
Then I routed this model and in the js I've added:
success: function(file) {
$(function ()
{
$.ajax({
async: true,
url: "../public/currentfile",
dataType: 'json',
method:'get',
complete: function(data)
{
console.log(data.responseJSON);
var created_at = data.responseJSON['created_at'];
var filesize = data.responseJSON['filesize'];
var filename = data.responseJSON['filename'];
var fileid = data.responseJSON['fileid'];
$( "#results .tableheaders" ).after("<tr><td>" + fileid + "</td><td>" + filename + "</td><td>" + filesize + "</td><td>" + created_at + "</td></tr>");
}
});
});
if (file.previewElement) {
return file.previewElement.classList.add("dz-success");
}
}
And it seems to work...for now :D I'm not a JS guy and I don't even know how I managed to do this :D
Related
I have been working on a website incorporating the autodesk-forge viewer (more details can be seen on my past questions). I have successfully made many autodesk-forge viewer functions in a standard javascript (.js) file. These functions include displaying the viewer, and isolating to a particular part, when an external button is pressed.
Currently I have a main html/php home page where I have included my javascript file with all my forge functions using <script src="MyForgeFunctions.js"></script>
These functions are accessed through a button, which successfully displays the viewer in the html page. Attached to my main php/html page, another html/php page was added through an iframe html reference (<iframe src="URL.php"></iframe>). My home page displays the main machines we make, while the embedded php/html page displays all the stations within the machine. I have also included the MyForgeFunctions.js inside this second php/html page. Because of the way the website is set up, I need to be able to access the viewer in both web pages. However, when I attempt to access the viewer from the second html page, I get a message that the viewer is undefined. Below is my code from MyForgeFunctions.js.
var ext = '';
var dim = '';
var assemblyname = '';
function getAssemblyName(){
assemblyname = sessionStorage.getItem("assemblyName");
//var ext = partname.substr(partname.lastIndexOf('.'));
ext = assemblyname.split('.');
dim = ext[0] + ':1';
console.log(assemblyname);
console.log(dim);
if (dim !== ''){
isolateSelected();
}
}
//function to get part name from __MachineParts.php
var partname = '';
var extension = '';
var namewithoutextension = '';
function getPartName(){
partname = sessionStorage.getItem("partName");
//var ext = partname.substr(partname.lastIndexOf('.'));
extension = partname.split('.');
namewithoutextension = extension[0] + ':1'
console.log(partname);
console.log(namewithoutextension);
if (namewithoutextension !== ''){
isolateSelectedPart();
}
}
/*******************************************************************************
*
* AUTODESK FORGE VIEWER CODE (HTTP REQUESTS)
*
*******************************************************************************/
//VARIABLE DECLARATION
var code = '';
var access_token = '';
const hub = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const project ='xxxxxxxxxxxxxxxxxxxxxxxxxxx';
const folder='xxxxxxxxxxxxxxxxxxxxxxxxx';
const item = 'xxxxxxxxxxxxxxxxxxxxxxxxx';
var itemid = '';
var urn = '';
var urn2 = '';
//allow the program to view data from autodesk
function authorize(){
window.location.href = "https://developer.api.autodesk.com/authentication/v1/authorize?response_type=code&client_id=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&redirect_uri=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx&scope=data:read data:write bucket:read viewables:read bucket:create data:create";
}
//grab the code from the url
function getCode(){
const querystring = window.location.search;
// console.log(querystring);
const urlParams = new URLSearchParams(querystring);
code = urlParams.get('code');
// console.log(code);
}
//call the function to get the code right away, and obtain a token
getCode();
getToken();
//function to obtain access token
function getToken(){
$.ajax({
method: 'POST',
url: 'https://developer.api.autodesk.com/authentication/v1/gettoken',
headers: {
'Content-Type':'application/x-www-form-urlencoded'
},
data:'client_id=dm2VLfnwJ6rYHKPAg7dG6l9yVbBQPGlH&client_secret=HRMpOPusLhsVoIMk&grant_type=authorization_code&code=' + code + '&redirect_uri=http://team/__MachineViewerMV.php',
success:function(response){
// console.log(response);
access_token = response.access_token;
console.log(access_token);
}
})
}
//Grab desired file id from project folder
function getItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/* beforeSend:function(before){
if(access_token !== '' && viewer !==''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
function get2dItem(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/folders/' + item + '/contents',
headers:{
Authorization:'Bearer ' + access_token
},
/*beforeSend:function(before){
if(access_token !== '' && viewer !== ''){
destroyViewer();}
},*/
success:function(response){
//console.log(response);
// folder = response.data[0].id;
// console.log(folder);
// itemid = response.data[0].id;
//console.log(itemid);
console.log(response);
for (var i = 0; i<response.data.length; i++){
//console.log(response.data[i].attributes.displayName);
if(response.data[i].attributes.displayName == fileName2d){
//console.log('hooray');
itemid = response.data[i].id;
console.log(itemid);
getVersion();
break;
}
else if (response.data[i].attributes.displayName !== fileName2d){
itemid = '';
}
}
},
error:function(error){
authorize();
}
})
}
//get version of the file using its id
function getVersion(){
$.ajax({
method:'GET',
url: 'https://developer.api.autodesk.com/data/v1/projects/' + project + '/items/' + itemid + '/versions',
headers:{
Authorization:'Bearer ' + access_token
},
success:function(response){
//console.log(response);
urn = btoa(response.data[0].relationships.storage.data.id);
console.log(urn);
translateToSVF();
}
})
}
function translateToSVF(){
$.ajax({
method: 'POST',
url:"https://developer.api.autodesk.com/modelderivative/v2/designdata/job",
headers:{
"content-type": "application/json",
Authorization: "Bearer " + access_token
},
data:JSON.stringify({
"input":{ "urn":urn
},
"output": {
"formats": [
{
"type": "svf",
"views": [
"2d",
"3d"
]
}
]
}
}),
success:function(response){
// console.log(response);
urn2 = response.urn;
console.log(urn2);
checkStatus();
}
})
}
function checkStatus(){
$.ajax({
method: 'GET',
url: "https://developer.api.autodesk.com/modelderivative/v2/designdata/" + urn2 + "/manifest",
headers:{
Authorization: "Bearer " + access_token
},
success: function(response){
console.log(response);
if (response.progress == 'complete'){
displayViewer();
}
else if (response.progress !== 'complete'){
alert('File Still Uploading, Press the Display Button Again!');
}
}
})
}
//function to get list of viewables\
var guid = '';
function getViewable(){
$.ajax({
method:'GET',
headers:{
Authorization: "Bearer " + access_token
},
url: 'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata',
success:function(response){
console.log(response);
guid = response.data.metadata[0].guid;
console.log(guid);
}
})
}
//funciton to get the list of items within a model
function getTree(){
$.ajax({
method: 'GET',
headers:{
Authorization: "Bearer " + access_token
},
url:'https://developer.api.autodesk.com/modelderivative/v2/designdata/' + urn2 + '/metadata/' + guid + '/properties',
success:function(response){
console.log(response);
}
})
}
/**********************************************************************************
*
* FUNCTION TO DISPLAY THE VIEWER IN THE HTML PAGE
*
**********************************************************************************/
var viewer;
function displayViewer(){
//var viewer;
var options = {
env: 'AutodeskProduction',
api: 'derivativeV2', // for models uploaded to EMEA change this option to 'derivativeV2_EU'
getAccessToken: function(onTokenReady) {
var token = access_token;
console.log(token);
var timeInSeconds = 3600; // Use value provided by Forge Authentication (OAuth) API
onTokenReady(token, timeInSeconds);
}
};
Autodesk.Viewing.Initializer(options, function() {
var htmlDiv = document.getElementById('forgeViewer');
viewer = new Autodesk.Viewing.Private.GuiViewer3D(htmlDiv);
var startedCode = viewer.start();
// sessionStorage.setItem("viewer", viewer);
if (startedCode > 0) {
console.error('Failed to create a Viewer: WebGL not supported.');
return;
}
console.log('Initialization complete, loading a model next...');
});
var documentId = 'urn:'+urn2;
Autodesk.Viewing.Document.load(documentId, onDocumentLoadSuccess, onDocumentLoadFailure);
function onDocumentLoadSuccess(viewerDocument) {
var defaultModel = viewerDocument.getRoot().getDefaultGeometry();
viewer.loadDocumentNode(viewerDocument, defaultModel);
console.log(viewer);
}
function onDocumentLoadFailure() {
console.error('Failed fetching Forge manifest');
}
}
//function to hide the viewer
function destroyViewer(){
console.log(viewer);
viewer.finish();
viewer = null;
Autodesk.Viewing.shutdown();
}
/*****************************************************************************
* FUNCTIONS TO MODIFY THE VIEWER TO ZOOM INTO THE CORRECT PART/ASSEMBLY
*/
function isolateSelected(){
console.log(dim);
console.log(viewer);
viewer.search(dim, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', dim, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
function isolateSelectedPart(){
console.log(namewithoutextension);
viewer.search(namewithoutextension, function(dbIds) {
// viewer.search('"' + 'M-109408 FOLDING PLOUGH:2' + '"', function(dbIds) {
console.log(dbIds.length);
getSubset(dbIds, 'label', namewithoutextension, function(dbIds) {
// getSubset(dbIds, 'label', 'M-109408 FOLDING PLOUGH:2', function(dbIds) {
// getSubset(dbIds, property.name, 'M-54439 POST TUBING:1', function(dbIds) {
//getSubset(dbIds, property.name, property.value, function(dbIds){
var it = viewer.model.getData().instanceTree;
//console.log(it);
for (i = 0; i<dbIds.length; i++){
var namepart = it.getNodeName(dbIds[i]);
if (namepart !== undefined){
console.log(dbIds);
console.log(namepart);}}
/* for (i = 121; i<381;i++){
var dbId = i;
var it = NOP_VIEWER.model.getData().instanceTree;
var name = it.getNodeName(dbId);
console.log(name);}*/
viewer.isolate(dbIds)
viewer.select(dbIds);
viewer.utilities.fitToView();
})
}, function(error) {})
}
//function to find the dbid of the part/assembly
function getSubset(dbIds, name, value, callback) {
console.log("getSubset, dbIds.length before = " + dbIds.length)
viewer.model.getBulkProperties(dbIds, {
propFilter: [name],
ignoreHidden: true
}, function(data) {
var newDbIds = []
for (var key in data) {
var item = data[key]
// console.log(item.properties);
if (item.properties[0].displayValue === value) {
newDbIds.push(item.dbId)
}
}
console.log("getSubset, dbIds.length after = " + newDbIds.length)
callback(newDbIds)
}, function(error) {})
}
Because of how the webpage is set up, when I needed to use a variable from the second web page in the first, I used sessionStorage.getItem and sessionStorage.setItem. I have also made a simple function as so inside MyForgeFunctions.js:
function checkViewer(){
console.log(viewer);
}
I then included a button in both html pages to execute the function with an onclick event. When the function is run from the first/home html page the following is displayed:
T {globalManager: e, clientContainer: div#forgeViewer, container: div.adsk-viewing-viewer.notouch.dark-theme.quality-text, config: {…}, contextMenu: o, …}. Which is normal for the viewer, but when the function is executed from the second html page, the viewer is undefined. Any help as to why this is happening or any solutions will be greatly appreciated. Cheers!
From the iframe, in order to access the viewer inside the main web page, I had to use (parent.viewer).
I have two files: one file contains php code (and it works properly) and the other one contains javacript.
The problem is in javascript page:
function calcDist() {
var citta = $("#txtpartenza").val();
$.ajax({
type: "POST",
url: 'mostraPartenze.php',
dataType: "json",
success: function (data) {
$.each(data, function (index) {
var partenza = data[index];
trovaGeo(citta, partenza);
});
}
});
}
function trovaGeo(partenza, destinazione) {
var latPartenza;
var lonPartenza;
var latDestinazione;
var lonDestinazione;
console.log(partenza); // for test
console.log(destinazione); // for test
var xmlhttpPart = new XMLHttpRequest();
var xmlhttpDest = new XMLHttpRequest();
xmlhttpPart.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext="+partenza+"&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
xmlhttpPart.send();
xmlhttpDest.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext="+destinazione+"&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
xmlhttpDest.send();
xmlhttpPart.onreadystatechange = function () {
if (xmlhttpPart.readyState == 4 && xmlhttpPart.status == 200) {
xmlhttpDest.onreadystatechange = function () {
if (xmlhttpDest.readyState == 4 && xmlhttpDest.status == 200) {
var resPart = JSON.parse(xmlhttpPart.responseText);
latPartenza = resPart.Response.View[0].Result[0].Location.DisplayPosition.Latitude;
lonPartenza = resPart.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
var resDest = JSON.parse(xmlhttpDest.responseText);
latDestinazione = resDest.Response.View[0].Result[0].Location.DisplayPosition.Latitude;
lonDestinazione = resDest.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
lonDestinazione = resDest.Response.View[0].Result[0].Location.DisplayPosition.Longitude;
console.log(latPartenza);
}
};
}
};
}
Ajax works correctly; I can call trovaGeo(citta, partenza) without problems but in trovaGeo(partenza, destinazione) function, XMLHttpRequest "part" doesn't work properly: in console the variable latPartenza is never printed and obviously all codes in xmlhttpPart.onreadystatechange = [...] it's never executed.
For completeness this is the heart of php file:
$i = 0;
$citta = array();
while ($rows = $result->fetch_assoc()) {
$citta[$i] = $rows['partenza'];
$i=$i+1;
}
echo json_encode($citta);
I find the problem.
I have to use preventDefault in the first line of the event of on('submit'...
This is the solution:
$('form').on('submit', function (e) {
e.preventDefault();
[...]
The problem might be with nested onreadystatechagestatements , there might be a delay in responses. But I can see that second request is dependent on first request response.try the below change
xmlhttpPart.onreadystatechange = function() {
if (xmlhttpPart.readyState == 4 && xmlhttpPart.status == 200) {
xmlhttpDest.open("GET", "https://geocoder.cit.api.here.com/6.2/geocode.json?searchtext=" + destinazione + "&app_id=[APP_ID]&app_code=[APP_CODE]&gen=8", true);
xmlhttpDest.send();
xmlhttpDest.onreadystatechange = function() {
// your code
console.log(latPartenza);
}
};
}
};
After View console all the mobile no showing how can I resolved it?
var jArray = <?php echo json_encode($allmobone); ?>;
var mob = document.getElementById("user_mobile_number").value;
var precode = "91";
mobcode = precode + mob;
for (var r = 0; r < jArray.length; r++) {
if (jArray[r] == mobcode) {
document.getElementById("spn_user_mobile_number_2").style.display = "block";
return false;
}
}
If you need to hide the $allmobone value completely from a browser developer tools, don't send it to clients. Instead send an AJAX request to the server when you need to check a mobile number, and make a decision depending on the request response.
Here is an HTML code of the page with the user interface:
function ajaxGet(url, onload, onerror) {
var request = new XMLHttpRequest();
request.onload = function () {
if (request.status >= 200 && request.status < 400) {
onload(request.responseText);
} else {
onerror();
}
};
request.onerror = onerror;
request.open('GET', url, true);
request.send();
}
var mob = document.getElementById("user_mobile_number").value;
var precode = "91";
mobcode = precode + mob;
ajaxGet('/checkMobileCode.php?mobcode=' + encodeURIComponent(mobcode), function (response) {
if (response === 'ok') {
document.getElementById("spn_user_mobile_number_2").style.display = "block";
}
});
And here is a PHP code of the script which checks a mobile code (/checkMobileCode.php):
if (in_array($_GET['mobcode'] ?? '', $allmobone)) {
echo 'ok';
} else {
echo 'fail';
}
Option 1:
Use Ajax to load your resources dynamically, then viewing source (ctrl+u) will not show any values:
$.ajax({
url: 'getJson.php',
dataType: 'json',
success: function (jArray) {
var mob = document.getElementById("user_mobile_number").value;
var precode = "91";
mobcode = precode + mob;
for (var r = 0; r < jArray.length; r++) {
if (jArray[r] == mobcode) {
document.getElementById("spn_user_mobile_number_2").style.display = "block";
break;
}
}
}
});
But there still be visible response in console network tab
Option 2:
If you have only static data, then loop your data and apply inline css:
<?php
foreach ($allmobone as $el) {
if ($el === $_POST['mobcode']) {
echo "<div id='spn_user_mobile_number_2'>...</div>";
}
}
Only that you have to submit form when user enters "mobcode" to reload page.
I am able to send data on .cs page and image also save in folder but it's corrupted and image size is 0.. i am totally confused that where is the error
Please see the JQUERY CODE & C# CODE also
JQUERY code
<script type="text/javascript">
$(document).ready(function () {
$("#submitPhoto").click(function () {
var photo = $("#uploadPhoto").get(0);
var file = photo.files;
var Photo_Path = $("#uploadPhoto").val();
var extenssion = Photo_Path.split('.').pop().toUpperCase();
if (Photo_Path == "") {
alert('Please Choose Photo');
return;
}
if (extenssion != 'JPEG' && extenssion != 'JPG' && extenssion != 'jpg') {
alert('Invalid File[JPEG,JPG is acceptable]');
return;
}
if (file.size < 4000 || file.size > 14000) {
alert('Photo Size Must be Below 12Kb and Above 4Kb ');
return;
}
var id = $("#submitPhoto").attr('id');
$.ajax({
type: "POST",
contentType: "multipart/form-data",
url: "finalstep-registration.aspx?photoPath=" + Photo_Path + "&id=" + id + "&check=imgUpload",
data: file,
datatype: 'json',
async: false,
processData: false,
success: function (data) {
alert('Image successfully Uploaded');
},
error: function ()
{ console.log('there is some error'); }
});
});
</script>
C# code
By which image are save in folder and name are save in database
I am calling uploadPhoto()function on pageload using query string
public void uploadPhoto(string photoPath,string id)
{
//HttpContext context = HttpContext.Current;
//int regNo = Convert.ToInt32(Session["restrationNumber"].ToString());
int regNo = 1001;
if (id == "submitPhoto")
{
FileInfo CustPic = new FileInfo(photoPath);
System.IO.Stream fileContent = Request.InputStream;
FileStream fileStream = File.Create(Server.MapPath("~/photo/") + CustPic.Name);
fileContent.Seek(0, System.IO.SeekOrigin.Begin);
fileContent.CopyTo(fileStream);
//System.Web.Hosting.HostingEnvironment.MapPath("~/photo/");
string query = "update userDetails set photo='"+photoPath+ "' where regNo="+regNo+"";
int a = bl.executenonquery(query);
if (a == 1)
Response.Write("Photo is uploaded successfully");
else
Response.Write("Oops, We can't upload your photo. try again");
//Session["photo"] = CustPic.Name;
}
}
Check and tell me where i am doing wrong
I am trying to load some data from my JSON file using AJAX. The file is called external-file.json. Here is the code, it includes other parts that haven't got to do with the data loading.The part I'm not sure of begins in the getViaAjax funtion. I can't seem to find my error.
function flip(){
if(vlib_front.style.transform){
el.children[1].style.transform = "";
el.children[0].style.transform = "";
} else {
el.children[1].style.transform = "perspective(600px) rotateY(-180deg)";
el.children[0].style.transform = "perspective(600px) rotateY(0deg)";
}
}
var vlib_front = document.getElementById('front');
var el = document.getElementById('flip3D');
el.addEventListener('click', flip);
var word = null; var explanation = null;
var i=0;
function updateDiv(id, content) {
document.getElementById(id).innerHTML = content;
document.getElementById(id).innerHTML = content;
}
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
function counter (index, step){
if (word[index+step] !== undefined) {
index+=step;
i=index;
updateDiv('the-h',word[index]);
updateDiv('the-p',explanation[index]);
}
}
var decos = document.getElementById('deco');
decos.addEventListener('click', function() {
counter(i,-1);
}, false);
var incos = document.getElementById('inco');
incos.addEventListener('click', function() {
counter(i,+1);
}, false);
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
r.onload = function() {
if(this.status < 400 && this.status > 199) {
if(typeof callback === "function")
callback(JSON.parse(this.response));
} else {
console.log("err");// server reached but gave shitty status code}
};
}
r.onerror = function(err) {console.log("error Ajax.get "+url);console.log(err);}
r.send();
}
function yourLoadingFunction(jsonData) {
word = jsonData.words;
explanation = jsonData.explanation;
updateDiv('the-h',word[i]);
updateDiv('the-p',explanation[i])
// then call whatever it is to trigger the update within the page
}
getViaAjax("external-file.json", yourLoadingFunction)
As #light said, this:
function getViaAjax("external-file.json", callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", "external-file.json", true);
Should be:
function getViaAjax(url, callback) { // url being the url to external File holding the json
var r = new XMLHttpRequest();
r.open("GET", url, true);
I built up a quick sample that I can share that might help you isolate your issue. Stand this up in a local http-server of your choice and you should see JSON.parse(xhr.response) return a javascript array containing two objects.
There are two files
data.json
index.html
data.json
[{
"id":1,
"value":"foo"
},
{
"id":2,
"value":"bar"
}]
index.html
<html>
<head>
</head>
<body onload="so.getJsonStuffs()">
<h1>so.json-with-ajax</h1>
<script type="application/javascript">
var so = (function(){
function loadData(data){
var list = document.createElement("ul");
list.id = "data-list";
data.forEach(function(element){
var item = document.createElement("li");
var content = document.createTextNode(JSON.stringify(element));
item.appendChild(content);
list.appendChild(item);
});
document.body.appendChild(list);
}
var load = function()
{
console.log("Initializing xhr");
var xhr = new XMLHttpRequest();
xhr.onload = function(e){
console.log("response has returned");
if(xhr.status > 200
&& xhr.status < 400) {
var payload = JSON.parse(xhr.response);
console.log(payload);
loadData(payload);
}
}
var uri = "data.json";
console.log("opening resource request");
xhr.open("GET", uri, true);
xhr.send();
}
return {
getJsonStuffs : load
}
})();
</script>
</body>
</html>
Running will log two Javascript objects to the Dev Tools console as well as add a ul to the DOM containing a list item for every object inside the data.json array