I am using Codeigniter and AngularJS.
Can someone help me?
I would like to save $scope.ListTabel to the database. It is possible for "FOR" to pass in the codeigniter controller - to be executed on the server and not in javascript?
Thanks a lot!
$scope.ListaTabel = [];
$scope.adauga_in_tabel = function () {
var camp = {};
camp.tbl_date = new Date();
camp.tbl_consumator = ServGlob.data.consumator;
camp.tbl_produs = ServGlob.data.produs;
camp.tbl_cantitate = ServGlob.data.cantitate;
camp.tbl_pret = ServGlob.data.pret;
$scope.ListaTabel.push(camp);
}
$scope.salveaza = function(){
for(var i = 0; i < $scope.ListaTabel.length; i++){
var item = $scope.ListaTabel[i];
$scope.items = {date: item.tbl_date, consumator: item.tbl_consumator, produs: item.tbl_produs, pret: item.tbl_pret};
$http.post('<?php echo base_url()."consum/add_consum";?>', $scope.items);
}
//$scope.ListaTabel = null;
//$scope.items = null;
}
Codeigniter Controller
public function add_consum()
{
$request= json_decode(file_get_contents('php://input'), TRUE);
$data=$this->Consum_model->insert_consum($request);
//$this->session->set_flashdata('message', 'Datele au fost salvate cu succes...');
}
Codeigniter Model
public function insert_consum($request)
{
//$val = array(
// 'date' => $request['date'],
// 'consumator' => $request['consumator'],
// 'produs' => $request['produs'],
// 'pret' => $request['pret']
// );
$insert=$this->db->insert('consum',$request);
return $insert;
}
i think the best solution would be to store alle data in an array and after that send it to the server
something like the following should work
Your JS Controller function
$scope.salveaza = function()
{
let arrItems = [];
for(var i = 0; i < $scope.ListaTabel.length; i++)
{
var item = $scope.ListaTabel[i];
let itemToPost = {date: item.tbl_date, consumator: item.tbl_consumator, produs: item.tbl_produs, pret: item.tbl_pret};
arrItems.push(itemToPost);
}
$http.post('<?php echo base_url()."consum/add_consum";?>', arrItems).then(function(result){
//do whatever you want
});
}
and your controller function
public function add_consum()
{
$request= json_decode(file_get_contents('php://input'));
foreach($request as $arrItem)
{
$this->Consum_model->insert_consum($arrItem);
}
//$this->session->set_flashdata('message', 'Datele au fost salvate cu succes...');
}
Related
I have a code which is works fine, but the data cannot save to the database. I want to insert cost, currency_rate, profit_rate and pprice to database through Ajax. Here are the code of javascript and update.php, I have tried to modify the code to save in my Mysql server, but it didn't success. Can someone help with this?
javascript
$(".profitRate").change(function() {
var myArray = [];
//find closest table->next table
var elem = $(this).closest('table').next('table');
var action = elem.find('tr').data('action');
console.log(action)
var profitRate = Number($("#profitRate").val());
//looping
elem.find('tr').each(function() {
//get cost
var cost = $(this).find('input[name=cost]').val();
//get curency rate
var currecy_rate = $(this).find('select[name=currency_rate]').val();
//calculate profit
var profit_total = Math.round(cost * profitRate * currecy_rate)
$(this).find('input[name=pprice]').val(profit_total)
//add to json object
auto_array = {};
auto_array["cost"] = cost;
auto_array["currecy_rate"] = currecy_rate;
auto_array["pprice"] = profit_total;
myArray.push(auto_array) //push to array
});
console.log(myArray)
form_data = elem.find('tr').data('action');
$.ajax({
data: {
action: action,
form_data: form_data,
},
url: 'update.php',
type: 'post',
beforeSend: function() {
},
success: function(data) {
if(data == 1){
}
}
});
})
update.php
<?php
if ($_POST['action'] == 'update_price') {
parse_str($_POST['form_data'], $my_form_data);
$id = $my_form_data['id'];
$cost = $my_form_data['cost'];
$profit_rate = $my_form_data['profit_rate'];
$currency_rate = $my_form_data['currency_rate'];
$pprice = $my_form_data['pprice'];
$sql = $query = $finalquery = $sqlresult = '';
if ($cost){
$sql.="cost='$cost',";
}
if ($profit_rate){
$sql.="profit_rate='$profit_rate',";
}
if ($currency_rate){
$sql.="currency_rate='$currency_rate',";
}
if ($pprice){
$sql.="pprice='$pprice',";
$finalquery = rtrim($sql,',');
$query="UPDATE `gp_info` SET $finalquery where id=$id";
$sqlresult=mysql_query($query);
if($sqlresult){
$reback=1;
}else{
$reback=0;
}
echo $reback;
}
}
I have an Excel file with the following content:
Inside my component.ts, I extract the Excel's content as follow:
var testUrl= "excel.xlsx";
var oReq = new XMLHttpRequest();
oReq.open("GET", testUrl, true);
oReq.responseType = "arraybuffer";
oReq.onload = function(e) {
var arraybuffer = oReq.response;
var data = new Uint8Array(arraybuffer);
var arr = new Array();
for(var i = 0; i != data.length; ++i){
arr[i] = String.fromCharCode(data[i]);
}
var bstr = arr.join("");
var workbook = XLSX.read(bstr, {type:"binary"});
var first_sheet_name = workbook.SheetNames[0];
var worksheet = workbook.Sheets[first_sheet_name];
var json = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], {header:1, raw:true});
var jsonOut = JSON.stringify(json);
console.log("test"+jsonOut);
}
oReq.onerror = function(e) {
console.log(e);
}
oReq.send();
XLSX.utils.sheet_to_json will format JSON as follow:
However, I would like the JSON to be as follow:
Most probably I would need to manually create the JSON, but can anyone help me point to the direction on how I can accomplish this?
In your case we need to modify the JSON data by looping over XLSX.utils.sheet_to_json JSON object:
// This object will contain the data in the format we want
var finalObj = { "object": []};
// Variables to track where to insert the data
var locIndex, firstCondIndex, secondCondIndex,
lockey, firstCondKey, secondCondkey;
// We need to initialize all indexes to -1 so that on first time we can get 0, as arrays start with 0 in javascript
locIndex = -1;
// here obj is XLSX.utils.sheet_to_json
obj.object.map((value, index) => {
// we don't want to consider name of columns which is first element of array
if(!index) return;
// Go inside only if not null
if(value[0]) {
// For Location
finalObj.object.push(createObj(value[0]));
locIndex++;
// We also need to store key names to push it's children
lockey = value[0];
firstCondIndex = -1;
}
if(value[1]) {
// For First Condition
finalObj.object[locIndex][lockey].push(createObj(value[1]));
firstCondIndex++;
firstCondKey = value[1];
secondCondIndex = -1;
}
if(value[2]) {
// For Second Condition
finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey].push(createObj(value[2]));
secondCondIndex++;
secondCondkey = value[2];
}
if(value[3]) {
// For Products
// We just push the string
finalObj.object[locIndex][lockey][firstCondIndex][firstCondKey][secondCondIndex][secondCondkey].push(value[3]);
}
});
function createObj(val) {
// We need to initialize blank array so we can push the children of that element later on
var obj = {};
obj[val] = [];
return obj;
}
console.log(finalObj);
I have an ajax request which helps me to get a JSON-object from a webserver!
function _loadModel(filename) {
var request = new XMLHttpRequest();
request.open("GET", filename);//open(method, url, async)
request.onreadystatechange = function() {
console.info(request.readyState +' - '+request.status);
if (request.readyState == 4) {//4 == finished download
if(request.status == 200) { //OK -> bezogen auf http Spezifikation
handleLoadedGeometry(filename,JSON.parse(request.responseText));
}
else if (document.domain.length == 0 && request.status == 0){ //OK but local, no web server
handleLoadedGeometry(filename,JSON.parse(request.responseText));
}
else{
alert ('There was a problem loading the file :' + filename);
alert ('HTML error code: ' + request.status);
}
}
}
request.send();// send request to the server (used for GET)
}
_loadModel('http://localhost:8080/bbox?XMIN=3500060&YMIN=5392691&XMAX=3500277&YMAX=5393413')
JSON file:
[{"building_nr": 5, "geometry": "{\"type\":\"Polygon\",\"coordinates\":[[[3500267.16,5392933.95,456.904],[3500259.19,5392933.01,456.904],[3500258.586,5392938.152,456.904],[3500258.02,5392942.97,456.904],[3500265.98,5392943.94,456.904],[3500266.552,5392939.097,456.904],[3500267.16,5392933.95,456.904]]]}", "polygon_typ": "BuildingGroundSurface"}, ...]
This is one object and I have a lot of them in this array.
Now I want to create a mesh!
I think this can be done inside the function handleLoadedGeometry()
//Callback funktion
function handleLoadedGeometry(filename, model) {
var geom = new THREE.BufferGeometry();
for (var i=0;i<10;i++)
{
var vertex = new THREE.Vector3();
vertex.x = model.geometry[i].coordinates[0];
vertex.y = model.geometry[i].coordinates[1];
vertex.z = model.geometry[i].coordinates[2];
geometry.vertices.push( vertex );
}
geom.addAttribute( 'position', new THREE.BufferAttribute( vertices, 3 ) );
var material = new THREE.MeshBasicMaterial( { color: 0xff00f0 } );
var mesh = new THREE.Mesh( geom, material );
Scene.scene.add(mesh);
}
At the end I get this error in the browser: Cannot read property '0' of undefined
How can I refer to geometry coordinates inside the JSON?
from what you provided it seems the loaded JSON contains an array of multiple objects that is why you get the error
try something like this
function handleLoadedGeometry(filename, models) {
for (var i=0; i<models.length; i++)
{
var model = models[i];
var coordinates = model.geometry.coordinates;
var positions = [];
for (var j=0; j<coordinates.length; j++){
positions.push(coordinates[j][0]);
positions.push(coordinates[j][1]);
positions.push(coordinates[j][2]);
}
var geometry = new THREE.BufferGeometry();
// buffer attributes contain an array not vectors
var positionAttribute = new THREE.BufferAttribute(new Float32Array(positions),3);
geometry.addAttribute("position", positionAttribute);
var material = new THREE.MeshBasicMaterial( { color: 0xff00f0 } );
var mesh = new THREE.Mesh( geom, material );
Scene.scene.add(mesh);
}
}
or remove the first loop if you call it for each object in the JSON array
I did it in another way...I just created instead of BufferGeometry the default Geometry in three.js:
function handleLoadedGeometry(filename) {
var material = new THREE.MeshBasicMaterial({color: 0xFF0000});
for (var i=0; i<filename.length; i++)
{
var model = filename[i]; // erstes Objekt
var coordinates = JSON.parse(model.geometry);
var geometry = new THREE.Geometry();
var coordinates_updated = _transformCoordinates(coordinates.coordinates[0]);
for (var j = 0; j<coordinates_updated.vertices.length; j++){
geometry.vertices.push(
//new THREE.Vector3(coordinates.coordinates[0][j][0], coordinates.coordinates[0][j][1], coordinates.coordinates[0][j][2])//x,y,z Koordinatenpunkte für Surface 1
new THREE.Vector3(coordinates_updated.vertices[j][0],coordinates_updated.vertices[j][1],coordinates_updated.vertices[j][2])
);
geometry.faces.push(
new THREE.Face3(0,1,2),
new THREE.Face3(0,3,2)
geometry.computeBoundingSphere();
}
var mesh = new THREE.Mesh(geometry, material);
Scene.scene.add(mesh);
}
};
And now it works!
I think BufferGeometry is more for more complex surfaces.
In order to try and get around the odd issue in having with CORS (here) I am attempting to reload any images loaded via canvas.loadFromJSON()
But, I am experiencing weird issues. Sometimes only one image is replaced, other times I get duplicates of one image.
Here is my code:
canvas.loadFromJSON(<?php echo json_encode($objects); ?>, function() {
var objArray = canvas.getObjects();
for (var i = 0; i < objArray.length; i++) {
canvas.setActiveObject(objArray[i]);
var activeObject = canvas.getActiveObject();
if(activeObject.type === 'image') {
fabric.util.loadImage(activeObject.src, function(img) {
var object = new fabric.Image(img);
object.hasControls = true;
object.lockUniScaling = true;
object.scaleX = activeObject.scaleX;
object.scaleY = activeObject.scaleY;
object.originX = activeObject.originX;
object.originY = activeObject.originY;
object.centeredRotation = true;
object.centeredScaling = true;
canvas.add(object);
}, null, {crossOrigin: 'Anonymous'});
canvas.remove(activeObject);
}
activeObject.setCoords();
}
canvas.deactivateAll();
canvas.renderAll();
canvas.calcOffset();
});
Any ideas why I'm getting these weird issues?
First glance at your code I don't see anything wrong... But I'm also thinking the code might be a bit inefficient? Is there a need to create a new image instance?
I believe you should be able to just set the crossOrigin property on the image object.
This code is untested, but I'd try something like this:
canvas.loadFromJSON(<?php echo json_encode($objects); ?>, function() {
var objArray = canvas.getObjects();
for (var i = 0; i < objArray.length; i++) {
canvas.setActiveObject(objArray[i]);
var activeObject = canvas.getActiveObject();
if(activeObject.type === 'image') {
activeObject.crossOrigin = 'Anonymous';
}
}
canvas.deactivateAll();
canvas.renderAll();
canvas.calcOffset();
});
I had the same problem and overcome it downloading again the image then reassign it to object._element once each fabric object was created using loadFromJSON.
export const getImage = url => {
return new Promise((resolve, reject) => {
let img = new Image();
img.onload = () => resolve(img);
img.onerror = reject;
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;
});
}
canvas.loadFromJSON(json, canvas.renderAll.bind(canvas), async (o, object) => {
if (object.type === "image") {
let imagecore = await getImage(object.src);
object._element = imagecore;
}
});
I am try to read list from json here id my code:-
List<EmailProvider> list = new List<EmailProvider>();
XmlDocument doc = new XmlDocument();
doc.Load(Server.MapPath("~/WidgetXml.xml"));
XmlElement root = doc.DocumentElement;
XmlNodeList nodes = root.SelectNodes("//widget");
foreach (XmlNode node in nodes)
{
EmailProvider obj = new EmailProvider();
obj.Name = node["Name"].InnerText;
obj.left = Convert.ToInt32(node["left"].InnerText);
obj.Id = node["id"].InnerText;
obj.IsVisible = Convert.ToBoolean(node["isActive"].InnerText);
long s = Int64.Parse(node["top"].InnerText);
obj.top = s;
obj.desc = node["desc"].InnerText;
list.Add(obj);
}
var result = list.OrderBy(p => p.IsVisible).ToList();
return result.ToArray();
and on view:-
$(document).ready(function () {
$.post(siteUrl.getSiteUrl + '/Admin/ReadXml/', function (data) {
alert(data.length);
var st = JSON.stringify(data);
alert(st.length);
});
});
length always show 54 but in array only 4 items. How can i read all recors from array by json from json object.
Thanks in advance.
Try returning a JsonResult from your controller method, using the controller method Json
var result = list.OrderBy(p => p.IsVisible).ToList();
return Json(result.ToArray());
On JavaScript, you should just need to iterate over the array as in:
$(document).ready(function () {
$.post(siteUrl.getSiteUrl + '/Admin/ReadXml/', function (data) {
for(var i = 0;i < data.length; i++){
alert(data[i].Name);
}
});
});