Getting "undefined" return in readAsDataURL - javascript

I'm trying to get a image file from a input field in my form, transform it to a base64 string, and then send it to my backend using AJAX, but it's returning undefined. Weird thing is that I managed to do it in a JSFiddle, but am not achieving this in the server.
P.S.: I'm not gonna write the AJAX call and server interactions, as they are not relevant for this issue. I'm sending more data, and it's getting sent just right.
<form method="post">
<input type="file" id="documento" accept="image/*"/><br>
<button type="submit" id="continuar">Continuar</button>
</form>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script type="text/javascript">
$("#continuar").click(function (){
var fileInputDoc = document.getElementById('documento');
var readerDoc = new FileReader();
readerDoc.readAsDataURL(fileInputDoc.files[0]);
readerDoc.onload = function () {
var docb64 = readerDoc.result; //This is the point where everything goes wrong. Here I get the following error: "Cannot read property 'indexOf' of null".
var doc_aux = docb64.indexOf('base64,');
doc_aux += 7;
var doc = docb64.slice(doc_aux);
}
}
</script>
It might also be important to say that I've tested separate parts of the code, such as:
document.getElementById('documento'); (doesn't return null, meaning it found the actual element)
readerDoc.readAsDataURL(fileInputDoc.files[0]); (returns [object FileReader])
Functional JSFiddle
My sources:
https://www.codegrepper.com/code-examples/javascript/convert+input+image+to+base64+javascript
https://developer.mozilla.org/pt-BR/docs/Web/API/FileReader/readAsDataURL

Related

Use Promise to get Custom Dialog Result, Simplified Example

Beginner question here. At various points in my script I need the user to choose something from a selection of radio buttons on a CustomDialog, and then select from a second set of options based on their answer to the first dialog box, and then get that (asynchronous) response back into my main code so I can act on it further.
I can think of some ugly workarounds within my current skill-set, but after a lot of googling it looks the “right” way to handle this is with promises, so I’m trying to learn how. Eventually two promises will need to be chained, but I’m hoping I can tackle that once I understand the structure of the initial promise. What I have so far is clearly not right…
Many thanks for any and all schooling/advice.
function callRadio(myArray,myTitle){
//Call the HTML file and set the width and height
Logger.log('callRadio has been called, with this array: ',myArray);
var html = HtmlService.createTemplateFromFile('Radio_Template')
html.myArray = myArray;
var html = html.evaluate().setHeight(18.5 * myArray.length + 75);
//Display the dialog
var dialog = SpreadsheetApp.getUi().showModalDialog(html, myTitle);
};
function runsies(value){
//Receive value from .html back to .gs side. Display the value submitted from the dialog box in the Logger.
Logger.log("index of user selection is: ",value);
SpreadsheetApp.getActiveSheet().getRange(1, 1).setValue(value)
return(value);
//Fine as far as it goes , but I want to call this asynchronous output back to
// the test2 function to act on it further.
};
function test2(){ //attempt to set up my dialog calls in a promise (and later use .then to chain the follow-up question, but I don't understand the first promise structure yet)
var myTitle1 = "Select your favorite fruit"; //for testing purposes. Will otherwise be a variable string passed to test2()
var myArray1 = ["apples","bananas","grapes"]
var promise1 = new Promise(function(resolve, reject) {
var theAnswer1 = callRadio(myArray1, myTitle1).successHandler;// This calls the CustomDialog just fine, but is clearly not the right way to get at the returned value
Logger.log("What's going on inside the promise?: ",theAnswer1)//Logger returns null
if (theAnswer1 >=0) { /* if everything turned out fine */
resolve(theAnswer1);
}
else {
reject(Error("It broke"));
}
});
var x = promise1.then(function(result) {
Logger.log(result); // "Stuff worked!"
}, function(err) {
Logger.log(err); // Error: "It broke"
});
Logger.log('Your favorite fruit is: ', myArray1[x]);
//I need to chain a follow-up question, calling the dialog again based off the first answer(i.e.using callRadio(myArray2[x][1],myTitle2)).
//I think if I can get the first promise to work, I can extrapolate that to chain the second promise.
}
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<body>
<? for (var i = 0; i < myArray.length; i++){
?>
<div>
<input type="radio" id="<?= myArray[i] ?>" name="selection" value="<?= i ?>">
<label for=i><?= myArray[i] ?></label><br>
</div>
<? } ?>
<br>
<div>
<input type="submit" value="Submit" class="action" onclick="form_data()" >
<input type="button" value="Close" onclick="google.script.host.close()" >
</div>
</body>
<script>
function form_data(){
var value = $("input[name=selection]:checked").val();
google.script.run.withSuccessHandler().runsies(value);
google.script.host.close();
};
</script>
</html>

How to load data from external JSON API onclick (Cant use fetch)

I am trying to create an IE11 compatible webpage which will sit on a few users desktops, which will grab some data from a JSON API and display it.
The user will type in their individual API key before pressing a button, revealing the API data.
Could you please help where my code has gone wrong? The error message I get from the console is: "Unable to get property 'addEventListener' of undefined or null reference. " So it looks like it is not even making the call to the API.
<script>
var btn = document.getElementById("btn");
var apikey = document.getElementById("apikey").value
btn.addEventListener("click", function() {
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', 'http://example.example?&apikey=' + document.getElementById("apikey").value);
ourRequest.onload = function() {
if (ourRequest.status >= 200 && ourRequest.status < 400) {
var ourData = JSON.parse(ourRequest.responseText);
document.getElementById("title").textContent = ourData.data[0]["name"];
}}}
);
</script>
.
<body>
Enter API key: <input type="text" id="apikey">
<button id="btn">Click me</button>
<p id="title"></p>
</body>
The API data which I am trying to just extract the name from, looks something like this:
{"data":[{"name":"This is the first name"},{"name":"This is the second name"}]}
It's likely that you're including the Javascript in the page before the HTML. As Javascript is executed as soon as the browser reaches it, it will be looking for the #btn element which will not have been rendered yet. There are two ways to fix this:
Move the Javascript to the bottom of the <body> tag, making it run after the HTML has been output to the page.
Wrap the Javascript in a DOMContentLoaded event, which will defer the script until the page has finished loading. An example is as follows:
window.addEventListener('DOMContentLoaded', function() {
var btn = document.getElementById('btn');
var apikey = document.getElementById("apikey").value;
[...]
});

Missing POST parameters in AJAX call result in undefined index warnings in PHP script

I am using AJAX for the first time so I write a code and I followed a tutorial, but when I try to send my post with ajax I am getting undefined index and I really don´t know why, I tried to search answer hear but since I am using AJAX and javascript for the first time, the code there didn´t tell me anything.
Here is my code, I would be really greatful for any help, thank you.
js method
function post() {
var name = $('meno').val();
var priez = $('priezvisko').val();
$.post( "aktualizuj.php", {
'meno': name,
'priezvisko': priez
},
function (data) {
$('#result').html(data);
}
);
}
html form...
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" src="prihlasenie.js"></script>
</head>
<body>
<form>
<label for="meno" >Meno:</label><input type ="text" name="meno" id="meno" value ="meno" ><br>
<label for="priezvisko" >Priezvisko:</label><input type ="text" id="priezvisko" name="priezvisko" value ="priezvisko" ><br>
<input type="button" value="ulozZmeny" onclick="post()" >
</form>
<div id="result"></div>
</body>
</html>
this where I should get from ajax/javascript
session_start();
require "pripojenie.php";
$meno = $_POST['meno'];
$priezvisko = $_POST["priezvisko"];
$login = $_SESSION['login'];
jquery doesn't serialize key:value pairs where value is undefined, i.e.
$.post(url, { foo:undefined });
results in jquery not sending any POST parameter.
The problem is because of the following lines,
var name = $('meno').val();
var priez = $('priezvisko').val();
This would look for an element meno and an element priezvisko (and then their values) as if you had a document like
<p>
<meno>...</meno>
<priezvisko>...</priezvisko>
</p>
But you're looking for elements that have meno/priezvisko as value of their id attribute(s):
var name = $('#meno').val();
var priez = $('#priezvisko').val();
You should nevertheless check the existince of the parameters in your php script. Nothing prevents another script/bot/user to invoke your script with different parameters or no parameters at all.
see also:
http://docs.php.net/isset
http://docs.php.net/filter

Backbone: getting the html code of a view?

In order to write the HTML code of social icons (Twitter, Linkedin, etc) to a textarea so that the user can use that code elsewhere, I would like to get the HTML code of the view element, but I'm having some issues. To help illustrate this better, here is the code that creates the view:
define(function(require, exports, module) {
var _ = require('underscore');
var GridControlView = require('pb/views/grid-control');
var SocialiconsControlDialog = require('pb/views/socialicons-control-dialog');
var template = require('text!pb/templates/socialicons-grid-control.html');
var SocialiconsGridControlView = GridControlView.extend({
template: _.template(template)
,templateVars: {
partials: {
facebook: require('text!pb/templates/socialicons-grid-control-facebook.html')
,twitter: require('text!pb/templates/socialicons-grid-control-twitter.html')
,googleplus: require('text!pb/templates/socialicons-grid-control-googleplus.html')
,pinterest: require('text!pb/templates/socialicons-grid-control-pinterest.html')
,linkedin: require('text!pb/templates/socialicons-grid-control-linkedin.html')
}
}
,control_dialog: SocialiconsControlDialog
});
return SocialiconsGridControlView;
});
And, for example, the Linkedin template looks like this:
<script src="//platform.linkedin.com/in.js?<%- t.cache_buster %>" type="text/javascript">lang: en_US</script>
<script type="IN/Share" data-counter="<%- t.linkedin_option_countmode %>"></script>
What I would like to retrieve, is the parsed template code as text, something such as:
<script type="text/javascript" src="//platform.linkedin.com/in.js?0.4670609195438331">
<script data-counter="top" type="IN/Share+init">
But using something such as:
control_view.render().$el.innerHTML;, control_view.render().$el.html().text() or control_view.render().$el.html().replace(/<\/?[a-z][a-z0-9]*[^<>]*>/ig, ""); doesn't return text; it returns the full HTML, and produces a Linkedin icon (when I just want the text to be written to a textarea).
Any thoughts?
Update **
I noticed that the code control_view.render().$el is working correctly on other places of the application, and returning HTML code, but for some reason in this view where I'm trying it doesn't. The code seems to break at:
$control = control_view.render().el;
and in the console I get an error which is:
TypeError: t is undefined - underscore-min.js (line 3)
Use the .outerHTML property of the $el.
var html = $('<script type="text/javascript" src="//platform.linkedin.com/in.js?0.4670609195438331">' +
'<script data-counter="top" type="IN/Share+init">');
var text = html[0].outerHTML;
$('textarea').val(text);
jsFiddle

How to grab text from URL and place in JS array?

I've stated previously that I am very new to JavaScript and HTML. I'm creating a small search tool and I'm very confused as to how to get text from a URL and put it in my JS array.
For example, let's say the URL is: http://www.somethingrandom.com/poop
In that URL, there's a couple of words: "something", "everything", "nothing"
Literally just that. It's in a pre tag in HTML, and that's it.
Now, my JS code, I want it to open up that URL, and take those words and place them in a string/list/array, whatever, it could be anything as long as it can happen, I can manipulate it further later.
I have this so far:
<html>
<head>
<script type = "text/javascript">
function getWords(){
var url = "http://www.somethingrandom.com/poop"
var win = window.open( url );
window.onload = function(){
var list = document.getElementsByTagName("pre")[0].innerHTML;
var listLength = list.length;
alert( listLength);
}
}
</script>
</head>
<body>
<button id="1" onClick="getWords();">Click Here</button>
</body>
</html>
It doesn't work however.. And I'm not sure why. :( Please help.
Make an AJAX request and you will have access to the returned content.
Using jQuery:
function getWords(){
var url = "http://www.somethingrandom.com/poop"
$.get(url, function(data) {
var list = $('pre:eq(0)', data).html;
var listLength = list.length;
alert( listLength);
}, 'html');
}

Categories

Resources