Total.js save data to database - total.js

js framework. I'm trying to save data to DB from post request
model(article.js):
NEWSCHEMA('Article').make(function(schema) {
schema.define('title', 'String', true); // title of article
schema.define('about', 'String', true); // about
schema.define('text', 'String', true); // text
schema.define('date', 'Date'); // created date
schema.setSave(function(error , model, options, callback){
var sql = DB(error);
sql.insert('articles').make(function(builder) {
builder.set('title', model.title);
builder.set('about', model.about);
builder.set('text', model.text);
builder.set('date', F.datetime);
});
sql.exec(n => callback(SUCCESS(true)));
});
});
and i have controller(default.js):
exports.install = function() {
F.route('/add_article', add_article, ['authorize', '*Article', 'post']);
};
function add_article(){
var self = this;
self.body.$save(self, self.callback());
}
But i am getting error:
======= default ---> TypeError: sql.insert(...).make is not a function (http://127.0.0.1:8000/add_article?ts=1489500750601)TypeError: sql.insert(...).make is not a function
please help thanks.

You are entering an error to the DB on this line
var sql = DB(error);
You're passing the error, you should use
var sql = DB(model);

Related

How I can extract, or save data from promise

people please help me with this.
I have an object, and I need to add some data to this object from json file.
let data = {
'test1':1,
'test2:2
}
function convert(){
fetch("./test.json")
.then(response => {
return response.json();
})
.then(jsondata => {
{data = {...data, ...jsondata}}
console.log(data)
});
}
console.log(data)
What I must to do in order to save new version data?
In your case, you just need to do this:
data = {...data, ...jsondata};
instead of this:
{data = {...data, ...jsondata}}

"Attempt to assign property "weight" on null", exception: "Error",…}

Good Evening... New in Laravel and trying to develop web app for home business.
I am trying to Add new data on one table (buffaloinspectiondata) and update data on another table (buffalodata) using one Ajax.
For new data its working fine but for update in another table its giving error
Attempt to assign property "weight" on null
Controller File
public function addbuffaloinspectiondata(Request $req)
{
// add new data in buffaloinspection table for Buffalo ID
$newdata = new buffaloinspectiondata;
$newdata->buffaloID = $req->buffaloID;
$newdata->inspectiondate = $req->inspectiondate;
$newdata->weight = $req->weight;
$newdata->height = $req->height;
$newdata->pregnant = $req->pregnantstatus;
$newdata->health = $req->healthstatus;
$newdata->weeklytika = $req->weeklytika;
$newdata->monthlytika = $req->monthlytika;
$newdata->inspection = $req->inspection;
$newdata->inspectionby = $req->inspectionby;
$newdata->inspectionnote = $req->inspectionnote;
// Update data in buffalodata table for Buffalo ID
$updatedata = buffalodata::find($req->buffaloID);
$updatedata->weight = $req->get('weight');
$updatedata->height = $req->get('height');
$updatedata->pregnant = $req->get('pregnantstatus');
$updatedata->health = $req->get('healthstatus');
$newdata->save ();
$updatedata->save ();
return response()->json( $newdata,$updatedata );
}
AJAX Code =
$.ajaxSetup({
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$(document).on('click', '#footer_addnewinspectiondata_button', function() {
$.ajax({
type: 'post',
url: '/addbuffaloinspectiondata',
data: {
'_token' : $('input[name=_token]').val(),
'id' : $('#fid').val(),
'buffaloID' : $('#buffaloID').val(),
'inspectiondate' : $('#inspectiondate').val(),
'pregnantstatus' : $('#pregnantstatus').val(),
'healthstatus' : $('#healthstatus').val(),
'weight' : $('#weight').val(),
'height' : $('#height').val(),
'weeklytika' : $('#weeklytika').val(),
'monthlytika' : $('#monthlytika').val(),
'inspection' : $('#inspection').val(),
'inspectionby' : $('#inspectionby').val(),
'inspectionnote' : $('#inspectionnote').val(),
},
success: function(data) {
console.log (data)
}
});
});
Web.php
Route:: post('/addbuffaloinspectiondata',
[viewbuffaloController::class,'addbuffaloinspectiondata']);
Did i miss something..... Thanks in Advance
you need to store each element because if you don't want to update one column the value is null
so try the following code is the example
$updatedata = buffalodata::find($req->buffaloID);
$weight = $request->weight;
if($weight != null)
$updatedata->weight = $weight;
$updatedata->save ();
and do this condition for each column
hopefully this help you

how do I get the section title, sub_section_title and file in the formData in laravel

I am developing an application using laravel 8 and vuejs. I am trying to post form data from my vuejs to backend(laravel) but it is not working
The vuejs creates a subsection of a section which is add to an array of subsection inside the section array which is converted to string and added to a form data then sent as a request to my backend.
The frontend is working perfectly well but I cant access the data on my backend. How do I get the values of the course title, section title, sub section title and file added
Vuejs
<script>
import { reactive } from "vue";
import axios from "axios";
export default {
name: 'CreateCourse',
setup(){
const sections = reactive([{'section_title': '', 'sub_sections': [{'sub_section_title': '', 'file': '', 'url': ''}]}]);
const course = reactive({'title': '', 'description': ''});
const addSection = () => {
sections.push({"section_title": "", 'sub_sections': [{'sub_section_title': '', 'file': '', 'url': ''}]});
}
const addSubSection = (idx) => {
console.log('the value of idx is ', idx);
sections[idx].sub_sections.push({"sub_section_title": "", 'file': '', 'url': ''});
}
const uploadFile = (e, idx, i) => {
sections[idx].sub_sections[i].file = e.target.files[0];
sections[idx].sub_sections[i].url = URL.createObjectURL(sections[idx].sub_sections[i].file);
}
const createCourse = (e) => {
e.preventDefault();
let newCourse = JSON.stringify(course)
let newSection = JSON.stringify(sections)
const formData = new FormData();
formData.append("course", newCourse);
formData.append("sections", newSection);
showLoader(true);
axios.post('/api', form, { headers: {'Content-Type': 'multipart/form-data'}}).then(response =>
{
NotificationService.success(response.data.message);
showLoader(false);
course.title = '';
course.description = '';
}).catch(err => {
NotificationService.error(err.response);
showLoader(false);
});
}
return {
course,
createCourse,
sections,
addSection,
addSubSection,
uploadFile
}
}
</script>
laravel code
echo $request->get("title");
echo $request->get("description");
foreach($request->section_title as $titles)
{
echo $titles
}
foreach($request->section_sub_title as $sub_titles)
{
// info($sub_titles);
// return $sub_titles;
echo $sub_titles
}
{"course":{"title":"Frontend","description":"This is building web interface with html, css and javascript"},"sections":[{"section_title":"HTML","sub_sections":[{"sub_section_title":"What is HTML","file":{},"url":"blob:http://localhost:8080/ea0acc7d-34e6-4bff-9255-67794acd8fab"}]}]}
Bit tricky to understand where you're stuck, but let's give it a shot:
Does the api request actually reach your route (post -> /api), do you see in the network tab a post request to the route?
Have you tried running dd($request->all()) in the controller method so see what you're getting (just do this on the first line inside your method)?
Small gotcha moment:
Sometimes it helps to run the php artisan route:clearcommand

How to POST correctly a form that have data and files with VueJS, Axios and Laravel?

I am posting here as a beginner of VueJS and Laravel. I am stuck with a problem that I can't fix by myself after hours of search.
I would like to know how correctly send and get back the inputs of a form (complex data and files).
Here is the submit method of the form:
onSubmit: function () {
var formData = new FormData();
formData.append("data", this.model.data);
formData.append("partData", this.model.partData);
if (this.model.symbolFile != null) {
formData.append("symbolFile", this.model.symbolFile);
}
if (this.model.footprintFile != null) {
formData.append("footprintFile", this.model.footprintFile);
}
axios
.post("/api/updatecomponent", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
},
The variable Data and PartData contains multiple string fields which will be stored in different tables in my database. Example :
Data
{
string Value,
string Tolerance,
string Power
}
Here is the method of the Controller in the server side:
public function updateComponent(Request $req)
{
$data = $req->input('data');
$partData = $req->input('partData');
$symbolFile = $req->file('symbolFile'); // is null if the user did not modify the symbol
$footprintFile = $req->file('symbolFile'); // is null if the user did not modify the footprint
// etc...
}
I am able to get the files, everything work for that and I can store and read them :)
But, the problem is that I am unable to get back properly my Data or PartDat.
When I do :
dd($partData);
I got as result in the console:
"[object Object]"
I am almost sure that I don't use correctly the FormData but after hours of search, I can't find the good way I should gave the Data and PartData to the FormData.
My code was working well for Data and PartData until I add FormData to support the file upload :(
Thank you for your help :)
Here my working code:
Client side:
var formData = new FormData(); // create FormData
formData.append("subcat", this.subcategory);// append simple type data
formData.append("data", JSON.stringify(this.model.data));// append complex type data
axios // send FormData
.post(url, formData, {
headers: {
"Content-Type": "multipart/form-data",
},
})
.then((res) => {
// do something with res
// console.log(res);
})
.catch((err) => {
/* catch error*/
console.log(err);
});
Server side:
public function createComponent(Request $req)
{
$subcategory = $req->input('subcat'); // get the input parameter named 'subcat' (selected subcategory)
$data = json_decode($req->input('data'), true); // get the input, decode the jason format, force to return the result as an array
}
I hope it will help other peoples :)
Simple solution
let data = new FormData();
data.append('image',file_name.value);
_.each(form_data, (value, key) => {
data.append(key, value)
})
console.log('form data',data);
Now you can get data in laravel controller like:
$request->title
$request->description
$request->file

Dojo Cache - Tree - Uncaught TypeError: object is not a function

I am trying to use a data store cache with a tree.
I am getting Uncaught TypeError: object is not a function error.
I have tested the data and it is being pulled correctly.
I have checked the JSON and it is also correct.
Where am I going wrong?
require(["dojo/store/JsonRest"
, "dojo/store/Memory"
, "dojo/store/Cache"
, "dojo/json"
, "dijit/tree/ObjectStoreModel"
, "dijit/Tree"
, "dojo/domReady!"],
function (JsonRest, Memory, Cache, ObjectStoreModel, Tree) {
var restStore = new JsonRest({ target: "/DataStore/", idProperty: "id" });
var memoryStore = new Memory({
idProperty: "id",
getChildren: function (object) {
return this.query({ parent: object.id });
}
});
var store = new Cache(restStore, memoryStore);
store.query({ type: "index" }).forEach(function (item) {
console.log(item.name);
});
var docModel = new ObjectStoreModel(
{
store: store,
getRoot: function (onItem) {
this.store.get("index").then(onItem);
},
mayHaveChildren: function (object) {
return object.type === "folder" || object.type === "root";
}
});
var docTree = new Tree({
model: docModel,
onOpenClick: true,
onClick: function (item) {
if (item.type == "link") {
OpenLink(item.link);
}
},
persist: false
}, "divTree");
docTree.startup();
});
This has to do how Cache works. The first time store.get() is called, it uses the JsonRest store which returns a Promise. A Promise has a then() function so there is no problem. The next time it's called, it uses the Memory store which returns your JavaScript object itself. Your JavaScript object has no then() function, so an error is thrown. This can be fixed by surrounding the store.get() in a when().
Try changing
this.store.get("index").then(onItem);
to
when(this.store.get("index")).then(onItem);
Take a look here for more details.

Resources