File converting into empty array on angular to laravel post request - javascript

I'm trying to perform a basic Laravel 5 post request which simply do the following:
Save some data into a database
Stores a file (image) into public storage under a name which is a possible combo of 20 random numbers following '.jpg'
Save a url (which is used to locate the image in an img tag. I'm aware this isn't the best approach so feel free to post)
However, when performing an ordinary post request with no special headers from angular 6 to laravel 5, for some reason the File keeps converting into an empty array. (Before and after shots are below)
Before:
0: Object { id: 0, body: null, file: File }
After:
0: Object { id: 0, body: null, file: [] }
The File is full and is used to create a preview on a canvas before submitting so It works. The console is logging this data the line before posting and returning the $req Request before performing any php code in Laravel.
So the only place anything could get lost in translation is the in between. Code is as follows:
Angular 6:
postToLaravel(object) {
console.log(object.message);
this.http.post(this.url + '/add/message', object).subscribe(res => {
console.log(res);
});
}
Laravel 5:
function addMessage(Request $req) {
return $req->messages;
The empty array keeps pushing nothing to storage under a name its registered as a jpg file but no image is shown.
On the component that images are uploaded we have the following block take place after a (change)="" event:
onFileSelected(e: any) {
this.sectedFile = e.target.files[0];
this.isImage = true;
this.messageService.addImage(this.id, this.sectedFile);
this.preview();
}
The service function just finds the right object and adds a file:
addImage(id, file) {
var index = this.data.findIndex(x => x['id'] == id);
this.data[index]['body'] = null;
this.data[index]['file'] = file;
}
And when the submit button is pressed it just takes all the variables in the service and compacts them into an object. this object contains messages which is an array of further objects (the objects are as shown at the top) (If that made sense)
pushMessageToServer() {
this.messageService.postToLaravel({
title: this.title,
location: this.location,
gender: this.gender,
age: this.age,
deadline: this.deadline,
messages: this.data
});
}
Is there something I'm missing here?
Let me know should You need any extra info.

Turns out images in FormData are passed through and displayed as empty objects in the console. I just needed to know how to grab them. Thanks for your help everyone

Related

set vue data: object value

I have Vue.ja app and I try to change a value inside an object. Basically when #change="onfilechangev" occurred I would like to update name: ' ' value
Is there any way to do this or as it is an object I wont be able to update it?
app.js
var vm = new Vue({
el: '#regapp',
data: {
team:[
{
img: '',
name: '',
}
],
},
methods: {
onfilechangev(event) {
let uploads = event.target.files[0]
let pic = uploads.name;
Vue.set(vm.team.name, 'pic', )
},
Thanks for the answers. I have tried to do it but no luck. I have modified the codesandbox below to my situation. https://codesandbox.io/s/736nqq6070
little explain: I have dynamically added fields with optional profile image upload. So when I have added for example 3 team members then I would like to save them to the database with Laravel on the backend. if i select an image i push that file to the selectedFile array (it works), But as the profile pic only optional and not required somehow i need to know if teamemeber has image or not. That is why I try to set a hidden input field filename. so on the back end i can check selectedField array contains the filename if yes then i can save the image to the member.
Since you are only modifying an existing property of an array member, you don't even need to use Vue.set.
A simple this.team[0].name = pic will suffice, check this sandbox:
https://codesandbox.io/s/l2ky6rkx0l
The JS limitations regarding reactivity only apply to re-assigning an array element or adding a new root property, neither of which is the case for you.

Write to a existing js file using javascript

Suppose I have a file on server file1.js
Now my file1.js contains an code:
var arr = [ {'id':1, 'name':'one'},
{'id':2, 'name':'two'} ]; // array of two objects
There are two input boxes:
ID: <input id>
Name: <input name>
<button type="submit" action="xyz">
Now on clicking the submit button, I want to open file1.js and add {'id':<user_entered>, 'name':<user_entered>} i.e. an object to the existing array.
Is it doable? I don't want to involve any database here.
arr.push(..)
is the temporary solution i.e. If I open the web page on other PC or refresh the page, the source rendered here will not contain an array of 3 objects..isn't it????
If you are in a server-side environment you could first load the file using fs.readFile, parse the JSON into a normal JS array, manipulate the array however you need (i.e. append the extra object), and then write the serialized JSON back to the same path.
It would look something like this:
fs.readFile(path.join(__dirname, 'myFile.json'), 'utf-8', (err, data) => {
if (err) {
console.log('Error reading file');
}
const myArray = JSON.parse(data);
myArray.push({ new: 'object' });
fs.writeFile(path.join(__dirname, 'myFile.json'), JSON.stringify(myArray), e => {
if (e) {
console.log('Error writing file');
}
console.log('Success');
});
});
If you are only building for the web, however, this sounds like a job for localStorage. It would work very similarly:
const savedArray = localStorage.getItem('my_saved_array');
const myArray = savedArray ? JSON.parse(savedArray) : {};
myArray.push({ new: 'object' });
localStorage.setItem('my_saved_array', JSON.stringify(myArray));
It is possible for JSON.parse to throw and error so you may want to wrap this in a try-catch. This also gets around the issue of opening the page in a different tab as localStorage is persisted for each site in the same browser. If you were to open the site in chrome and then in safari, however, localStorage will not sync.
Hope this helps.

pouchdb inline attachment - saving and retrieving

I'm trying to use pouchdb to save an image which has been encoded in base64 format as an attachment against a document (inline) and then retrieve it again.
However, when i retrieve the document it seems as though pouchdb has modified the base64 image data and has appended 'md5-' to it. There is also no 'data' attribute off of the attachment object, as i would have expected. Instead i find an object called 'digest'. What is this?
I have created an example:
var db = new PouchDB('example');
db.bulkDocs(
[
{
_id: '1',
name: 'example',
"_attachments": {
"avatar.jpg": {
"content_type": "image/jpg",
"data": [BASE65 DATA STRING]
}
}
],
function(err, response) {
if (!err) {
db.allDocs({ include_docs: true, attachments: true }, function(err, docs) {
var d = docs.rows[0].doc;
// d looks like this:
// {"name":"example","_attachments":{"avatar.jpg":{"content_type":"image/jpg","digest":"md5-57e396baedfe1a034590339082b9abce","stub":true}},"_id":"1","_rev":"1-ff23a959ae88b871b94374a784a07728"}
});
}
}
);
Full example can be found here: http://jsfiddle.net/ntan0ycL/
How would i go about retrieving the base64 representation of the image from the pouchdb document? I'm not sure if the problem lies in how i'm saving the attachment or how i'm retrieving it.
Thanks,
Andrew.
Looks like we made a mistake, and the allDocs() API doesn't support the attachments option. So what you're getting back is just an attachments stub.
I've filed an issue: https://github.com/pouchdb/pouchdb/issues/2771
In the meantime, you can use the normal getAttachment() or get() API with {attachments: true} to fetch the attachments individually. Sorry about that.

How to modify a primary key with Restangular?

I've got a very simple object, called "tag" that has only a string primary key. When I go to edit it...
var tag = Restangular.one('tags', 'cat')
.get(function() { // fetches { id: 'cat' } from server
// edit the tag
tag.id = 'dog';
// save changes
tag.post().then(beHappy, beSad);
});
The request that gets sent off is a call to:
POST /tags/cat/dog
with the correct data:
{ id: 'dog' }
I have no doubt that everything work fine if I wasn't trying to modify my primary key, but my server-side REST API isn't expecting the /oldId/newId format, and so I get a 404. Is this a bug in Restangular, or does my REST API need repairing?
Apparently I've been doing CRUD wrong, doing POST for updates and PUT for creates, which is exactly backwards.
Changing it to tag.put() fixed it.

webOS/Ares : read JSON from URL, assign to label

I've used the webOS Ares tool to create a relatively simple App. It displays an image and underneath the image are two labels. One is static, and the other label should be updated with new information by tapping the image.
When I tap the image, I wish to obtain a JSON object via a URL (http://jonathanstark.com/card/api/latest). The typcial JSON that is returned looks like this:
{"balance":{"amount":"0","amount_formatted":"$0.00","balance_id":"28087","created_at":"2011-08-09T12:17:02-0700","message":"My balance is $0.00 as of Aug 9th at 3:17pm EDT (America\/New_York)"}}
I want to parse the JSON's "amount_formatted" field and assign the result to the dynamic label (called cardBalance in main-chrome.js). I know that the JSON should return a single object, per the API.
If that goes well, I will create an additional label and convert/assign the "created_at" field to an additional label, but I want to walk before I run.
I'm having some trouble using AJAX to get the JSON, parse the JSON, and assign a string to one of the labels.
After I get this working, I plan to see if I can load this result on the application's load instead of first requiring the user to tap.
So far, this is my code in the main-assistant.js file. jCard is the image.
Code:
function MainAssistant(argFromPusher) {}
MainAssistant.prototype = {
setup: function() {
Ares.setupSceneAssistant(this);
},
cleanup: function() {
Ares.cleanupSceneAssistant(this);
},
giveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
},
jcardImageTap: function(inSender, event) {
//get "amount_formatted" in JSON from http://jonathanstark.com/card/api/latest
//and assign it to the "updatedBalance" label.
// I need to use Ajax.Request here.
Mojo.Log.info("Requesting latest card balance from Jonathan's Card");
var balanceRequest = new Ajax.Request("http://jonathanstark.com/card/api/latest", {
method: 'get',
evalJSON: 'false',
onSuccess: this.balanceRequestSuccess.bind(this),
onFailure: this.balanceRequestFailure.bind(this)
});
//After I can get the balance working, also get "created_at", parse it, and reformat it in the local time prefs.
},
//Test
balanceRequestSuccess: function(balanceResponse) {
//Chrome says that the page is returning X-JSON.
balanceJSON = balanceResponse.headerJSON;
var balanceAmtFromWeb = balanceJSON.getElementsByTagName("amount_formatted");
Mojo.Log.info(balanceAmtFromWeb[0]);
//The label I wish to update is named "updatedBalance" in main-chrome.js
updatedBalance.label = balanceAmtFromWeb[0];
},
balanceRequestFailure: function(balanceResponse) {
Mojo.Log.info("Failed to get the card balance: " + balanceResponse.getAllHeaders());
Mojo.Log.info(balanceResponse.responseText);
Mojo.Controller.errorDialog("Failed to load the latest card balance.");
},
//End test
btnGiveCoffeeTap: function(inSender, event) {
window.location = "http://jonathanstark.com/card/#give-a-coffee";
}
};
Here is a screenshot of the application running in the Chrome browser:
In the browser, I get some additional errors that weren't present in the Ares log viewer:
XMLHttpRequest cannot load http://jonathanstark.com/card/api/latest. Origin https://ares.palm.com is not allowed by Access-Control-Allow-Origin.
and
Refused to get unsafe header "X-JSON"
Any assistance is appreciated.
Ajax is the right tool for the job. Since webOS comes packaged with the Prototype library, try using it's Ajax.Request function to do the job. To see some examples of it, you can check out the source code to a webOS app I wrote, Plogger, that accesses Blogger on webOS using Ajax calls. In particular, the source for my post-list-assistant is probably the cleanest to look at to get the idea.
Ajax is pretty much the way you want to get data, even if it sometimes feels like overkill, since it's one of the few ways you can get asynchronous behavior in JavaScript. Otherwise you'd end up with code that hangs the interface while waiting on a response from a server (JavaScript is single threaded).

Categories

Resources