Storing items in Parse (Javascript) [duplicate] - javascript

This question already has answers here:
Save input into Parse (Javascript)
(3 answers)
Closed 8 years ago.
I want to store two text field (userID, and address), as well as the file the user has uploaded to parse, but despite support, my attempt has been unsuccessful. I am not sure if there a typo that lies in the code, but it just doesn't seem to record in Parse.
<HTML>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.15.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// ***************************************************
// NOTE: Replace the following your own keys
// ***************************************************
Parse.initialize("id", "id");
function saveDocumentUpload(objParseFile)
{
var documentUpload = new Parse.Object("Scan");
documentUpload.set("Name", "");
documentUpload.set("DocumentName", objParseFile);
documentUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
$('#documentFileUploadButton').bind("click", function (e) {
var fileUploadControl = $("#documentFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
var user_id = $('#user_id').val();
var address = $('#address').val();
parseFile.set('UserId', user_id);
parseFile.set('Address', address);
parseFile.save().then(
function () {
saveDocumentUpload(parseFile);
},
function (error) {
alert("error");
}
);
});
});
</script>
<body><form>
<input type="file" id="documentFileUpload">
<br/>
<input type="text" placeholder="UserID" id="user_id">
<br/>
<input type="text" placeholder="Address" id="address">
<br/>
<input type="submit" id="documentFileUploadButton" value="submit">
</form>
</body>
</HTML>
Update:
<HTML>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script type="text/javascript" src="http://www.parsecdn.com/js/parse-1.2.15.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
// ***************************************************
// NOTE: Replace the following your own keys
// ***************************************************
Parse.initialize("ID", "ID");
function saveDocumentUpload(objParseFile)
{
var documentUpload = new Parse.Object("Scan");
documentUpload.set("Name", "");
documentUpload.set("DocumentName", objParseFile);
documentUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
$('#myForm').bind("submit", function (e) {
e.preventDefault();
var fileUploadControl = $("#documentFileUpload")[0];
var file = fileUploadControl.files[0];
var name = file.name; //This does *NOT* need to be a unique name
var parseFile = new Parse.File(name, file);
var user_id = $('#user_id').val();
var address = $('#address').val();
parseFile.set('UserId', user_id);
parseFile.set('Address', address);
parseFile.save().then(
function () {
saveDocumentUpload(parseFile);
},
function (error) {
alert("error");
}
);
});
});
</script>
<body><form id='myForm'>
<input type="file" id="documentFileUpload">
<br/>
<input type="text" placeholder="UserID" id="user_id">
<br/>
<input type="text" placeholder="Address" id="address">
<br/>
<input type="submit" value="submit">
</form>
</body>
</HTML>

First, do you have your api keys entered properly? I'm assuming you changed this out to post on here, but if not they need your keys.
Parse.initialize("id", "id");
You're posting the form back normally so your javascript isn't running.
Change your button click to the below - give your form some Id - I gave it an Id of myForm for this example.
Instead of:
$('#documentFileUploadButton').bind("click", function (e) {
//your code to run
});
try:
$('#myForm').bind("submit", function (e) {
e.preventDefault();
//your code to run
});

Related

How to add input field to Yammer api query

I am a boiler plate programmer, so not very technical on how scripts work indepthly.
I have a yammer api for pulling user information from Yammer:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<span id="yammer-login"></span>
<script type="text/javascript" data-app-id="bdlZbJHCm1RY8pMUbuoBlQ" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js"></script>
<script>
yam.getLoginStatus(
function (response) {
var result = 1625803434;
if (response.authResponse) {
console.log("logged in");
yam.platform.request({
url: "users/"+result+".json",
method: "GET",
data: { //use the data object literal to specify parameters, as documented in the REST API section of this developer site
"User_Id": result,
},
success: function (user) { //print message response information to the console
str = JSON.stringify(user, null, 4); // (Optional) beautiful indented output.
document.write(str);
},
error: function (user) {
alert("There was an error with the request.");
}
});
}
else {
alert("not logged in")
}
}
);
</script>
</body>
</html>
I have to hard code the Yammer id into it using the result variable.
I tried adding an input box then the yam.getLoginStatus fails with:
alert("There was an error with the request.");
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="frm1" action="#" method="post">
Yammer ID: <input type="text" name="y_id"><br><br>
<input type="submit" onclick="yam_id()" value="Submit">
</form>
<span id="yammer-login"></span>
<script type="text/javascript" data-app-id="bdlZbJHCm1RY8pMUbuoBlQ" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js"></script>
<script>
yam.getLoginStatus(
function (response) {
var result = 1625803434;
frm_i=document.getElementById("frm1");
result=frm_i.elements[0].value;
// alert (result);
if (response.authResponse) {
console.log("logged in");
yam.platform.request({
url: "users/"+result+".json",
method: "GET",
data: { //use the data object literal to specify parameters, as documented in the REST API section of this developer site
"User_Id": result,
},
success: function (user) { //print message response information to the console
str = JSON.stringify(user, null, 4); // (Optional) beautiful indented output.
document.write(str);
//console.dir(user);
},
error: function (user) {
alert("There was an error with the request.");
}
});
}
else {
alert("not logged in")
}
}
);
</script>
Does anyone know how to simply add an input box for this script?
Here are two examples I prepared for you.
One is form submit, second is alert prompt. In both cases you need to pass a value into an input otherwise function will fail to run.
Put your authentication into authUser() function. Run example code to see it in action.
// Your auth function
function authUser(id) {
// Lets validate
if (id.length === 0) {
alert('Please enter your data, missing id');
return false;
}
// ur ajax/xhr request here
// Just console log so you can see the data
console.log(id);
}
// Example 1
document.getElementById('login-action2').addEventListener('click', function() {
var id = prompt("Please enter your auth credentials/id");
// then pass your id to your auth function
authUser(id);
});
// Example 2
function formSubmit() {
var id = document.getElementById('login-action1').value;
authUser(id);
// Prevent form from auto submitting
return false;
}
<button id="login-action2" type="button">Log me in</button>
<form action="form-login" onSubmit="return formSubmit();">
<fieldset>
<input id="login-action1" type="text" placeholder="enter auth credentials/id" value="" />
<input type="submit" value="Submit" />
</fieldset>
</form>

Uncaught TypeError: Cannot read property 'urlshortener' of undefined

I am receiving the following error:
Uncaught TypeError: Cannot read property 'urlshortener' of undefined
I am essentially trying to store into parse a url generated from google drive that has been shorten.
Below is the entire code:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<title>upload</title>
<script type="text/javascript">
// The Browser API key obtained from the Google Developers Console.
var developerKey = 'ID';
// The Client ID obtained from the Google Developers Console.
var clientId = 'ID';
// Scope to use to access user's photos.
var scope = ['https://www.googleapis.com/auth/photos'];
var pickerApiLoaded = false;
var oauthToken;
// Use the API Loader script to load google.picker and gapi.auth.
function onApiLoad() {
gapi.load('auth', {'callback': onAuthApiLoad});
gapi.load('picker', {'callback': onPickerApiLoad});
}
function onAuthApiLoad() {
window.gapi.auth.authorize(
{
'client_id': clientId,
'scope': scope,
'immediate': false
},
handleAuthResult
);
}
function onPickerApiLoad() {
pickerApiLoaded = true;
createPicker();
}
function handleAuthResult(authResult) {
if (authResult && !authResult.error) {
oauthToken = authResult.access_token;
createPicker();
}
}
// Create and render a Picker object for picking user Photos.
function createPicker() {
if (pickerApiLoaded && oauthToken) {
var picker = new google.picker.PickerBuilder().
enableFeature(google.picker.Feature.MULTISELECT_ENABLED).
addView(google.picker.ViewId.PDFS).
setOAuthToken(oauthToken).
setDeveloperKey(developerKey).
setCallback(pickerCallback).
build();
picker.setVisible(true);
}
}
// A simple callback implementation.
function pickerCallback(data) {
var url = 'nothing';
if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
url = doc[google.picker.Document.URL];
var message = url;
document.getElementById('result').innerHTML = message;
}
var longUrl=url;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if(response.id != null) {
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null, {
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
} else {
alert("error: creating short url");
}
});
}
function load()
{
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"> </script>
</head>
<body>
<div id="result"></div>
<div id="demo">
<div id="output">
<!-- The Google API Loader script. -->
<script type="text/javascript" src="https://apis.google.com/js/api.js?onload=onApiLoad"></script>
</body>
</html>
In particular, this where I attempt to shorten the URL to store into Parse:
var longUrl=url;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if(response.id != null) {
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null, {
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
} else {
alert("error: creating short url");
}
});
Update:
Please try out this code. It shortens a url from the input value you insert. In the sense that you enter example yahoo.ca in the input field, and once you hit convert it shortens it into a url and store in parse. This works succesfully, but I wanted to integrate that into my code where the url is derived from the url that is generated from the item the user has selected from their google drive:
<html>
<head>
<script src="http://www.parsecdn.com/js/parse-1.2.12.min.js"></script>
<script type="text/javascript">
function makeShort() {
var longUrl=document.getElementById("longurl").value;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response) {
if(response.id != null) {
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", response.id);
PDFUpload.save(null, {
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
} else {
alert("error: creating short url");
}
});
}
function load() {
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"></script>
</head>
<body>
URL: <input type="text" id="longurl" name="url" value="yahoo.com" /> <br/>
<input type="button" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output"></div>
</body>
</html>
I dug through your example and tried to see what is going on, but I opted to start fresh and try to accomplish this in a simple way. I see that you are using Angular, so I made a little fiddle to try and shorten the url to this question.
The main issue I think, is that you need to generate a new key and follow the configuration steps. I did so in minutes and it worked fine. Be sure to choose the api you want (urlshortener) in your dashboard!
Here is the link I was able to generate http://goo.gl/15yWwP
function googleOnLoadCallback() {
var key = '{ YOUR KEY }';
var apisToLoad = 1; // must match number of calls to gapi.client.load()
var gCallback = function () {
if (--apisToLoad == 0) {
//Manual bootstraping of the application
var $injector = angular.bootstrap(document, ['app']);
};
};
gapi.client.setApiKey(key);
gapi.client.load('urlshortener', 'v1', gCallback);
}
<script src="https://apis.google.com/js/client.js?onload=googleOnLoadCallback"></script>
And inside my shorten() function
var request =
gapi.client.urlshortener.url.insert({
'longUrl': '{ YOUR LONG URL }'
});
request.execute(function(response) {
console.log(response.id);
});
JSFiddle link

Uncaught ReferenceError: Parse is not defined

I unexpectedly received the following error through the debugger when trying to execute parse.
Uncaught ReferenceError: Parse is not defined
I am pretty sure its well defined so not sure where the error derives from.
Essentially what happens here is that a long url gets converted into a short url using google url shorten and then parse grabs the shorten url and stores it.
<html>
<head>
</head>
<script type="text/javascript">
function makeShort()
{
var longUrl=document.getElementById("longurl").value;
var request = gapi.client.urlshortener.url.insert({
'resource': {
'longUrl': longUrl
}
});
request.execute(function(response)
{
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", str);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
else
{
alert("error: creating short url");
}
});
}
function load()
{
gapi.client.setApiKey('ID'); //get your ownn Browser API KEY
gapi.client.load('urlshortener', 'v1',function(){});
}
window.onload = load;
</script>
<script src="https://apis.google.com/js/client.js"> </script>
<body>
URL: <input type="text" id="longurl" name="url" value="yahoo.com" /> <br/>
<input type="button" value="Create Short" onclick="makeShort();" /> <br/> <br/>
<div id="output"></div>
</body>
</html>
In particular, below is the conversation happens, and where I try to store the url to parse:
if(response.id != null)
{
str ="<a href='"+response.id+"'>"+response.id+"</a>";
document.getElementById("output").innerHTML = str;
Parse.initialize("ID", "ID");
var PDFUpload = new Parse.Object("Scan");
PDFUpload.set("PDFDocument", str);
PDFUpload.save(null,
{
success: function(uploadResult) {
// Execute any logic that should take place after the object is saved.
},
error: function(uploadResult, error) {
// Execute any logic that should take place if the save fails.
// error is a Parse.Error with an error code and description.
alert('Failed to create new object, with error code: ' + error.description);
}
});
}
Maybe you have this in another file but where is your code where you reference Parse http://www.parsecdn.com/js/parse-1.3.5.min.js ?
Maybe you are missing that and that's why you get the error.

In Play-Scala (activator), not able to dynamically populate a <div> from javascript

Please find the code here - https://github.com/iamanandkris/RedirectURL/blob/master/app/views/editRedirect.scala.html. I am trying to print the contents of Input 1,2 and 3 in to the div as and when the focus changes from any of these 3 objects. I am able to see that the java script is getting invoked when the focus changes and am able to get the alert also. I am able to populate the below 3 values
var idToGet = document.getElementById('uid').value
var qargsToGet = document.getElementById('qargs').value
var rurlToGet = document.getElementById('rurl').value
But the statement is not working
var s= document.getElementById('thecurrenturl');
s.html = "testing again";
Please go thru the full code below:
#(redirectForm: Form[RedirectModel])(implicit flash: Flash, lang: Lang)
#import helper._
#import helper.twitterBootstrap._
#main(Messages("products.form")) {
<h2>#Messages("products.form")</h2>
#helper.form(action = routes.Redirects.save()) {
<fieldset>
<label for="targetURL">Target URL: </label>
<div id="thecurrenturl"></div>
<legend>
#Messages("products.details", Messages("products.new"))
</legend>
#inputText(
redirectForm("uid"), '_label -> "User ID",'onBlur->"myFunction()",'_help -> "Enter a valid user id."
)
#textarea(
redirectForm("qargs"), 'onBlur->"myFunction()"
)
#textarea(
redirectForm("rurl"), 'onBlur->"myFunction()"
)
</fieldset>
<p><input type="submit" class="btn primary"
value='#Messages("products.new.submit")'></p>
}
<script type="text/javascript">
var successFn = function(data) {
console.debug("Success of Ajax Call");
console.debug(data);
};
var errorFn = function(err) {
console.debug("Error of ajax Call");
console.debug(err);
}
ajax1 = {
success: successFn,
error: errorFn
}
function myFunction() {
alert("test")
var idToGet = document.getElementById('uid').value
var qargsToGet = document.getElementById('qargs').value
var rurlToGet = document.getElementById('rurl').value
var s= document.getElementById("thecurrenturl");
s.html = "testing again";
alert(idToGet+'/'+qargsToGet+'/'+rurlToGet)
jsRoutes.controllers.Redirects.getString()
.ajax(ajax1);
}
</script>
}
Change line below
s.html = "testing again";
to
s.innerHTML = "testing again";
html is a jQuery function.

How can I parse a text file using javascript

The code below is to read a text file using javascript. it works.
However, I just want to read part of the content.
For example, the content of the file is :"Hello world!"
I just want to display "Hello".
I tried function split(), but it only works on strings. I don't know how to insert it here.
var urls = ["data.txt"];
function loadUrl() {
var urlToLoad = urls[0];
alert("load URL ... " + urlToLoad);
browser.setAttributeNS(xlinkNS, "href", urlToLoad);
}
thank you!!!
I used
jQuery.get('http://localhost/foo.txt', function(data) {
var myvar = data;
});
, and got data from my text file.
Or try this
JQuery provides a method $.get which can capture the data from a URL. So to "read" the html/text document, it needs to be accessible through a URL. Once you fetch the HTML contents you should just be able to wrap that markup as a jQuery wrapped set and search it as normal.
Untested, but the general gist of it...
var HTML_FILE_URL = '/whatever/html/file.html';
$(document).ready(function() {
$.get(HTML_FILE_URL, function(data) {
var fileDom = $(data);
fileDom.find('h2').each(function() {
alert($(this).text());
});
});
});
Try this to read separate words if I understood correctly what you need.
Create a file with the contents "hello world" and browse to it with the example script.
The output is "hello".
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
function readSingleFile(evt) {
var f = evt.target.files[0];
if (f) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
var ct = r.result;
var words = ct.split(' ');
alert(words[0]);
}
r.readAsText(f);
} else {
alert("Failed to load file");
}
}
document.getElementById('fileinput').addEventListener('change', readSingleFile, false);
</script>
</head>
<body>
</body>
</html>
Reading directly has to be with an ajax request due to the javascript restrictions regarding safety.
This code shoudl perform the requested operation:
<html>
<head>
<input type="file" id="fileinput" />
<script type="text/javascript">
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState==4){
var words = xmlhttp.responseText.split(' ');
alert(words[0]);
}
}
xmlhttp.open("GET","FileName.txt",true);
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
Opening a file in javascript with ajax (without using any framework)
var urls = ["data.txt"];
xhrDoc= new XMLHttpRequest();
xhrDoc.open('GET', urls[0] , async)
if (xhrDoc.overrideMimeType)
xhrDoc.overrideMimeType('text/plain; charset=x-user-defined')
xhrDoc.onreadystatechange =function()
{
if (this.readyState == 4)
{
if (this.status == 200)
{
var data= this.response; //Here is a string of the text data
}
}
}
xhrDoc.send() //sending the request

Categories