I collect data into a JS object:
var elements = {};
$(checked).each(function(i){
elements[i] = {};
elements[i].obj = obj;
elements[i].el = $(this).data('el');
elements[i].height = $(this).data('height');
elements[i].type = $(this).data('type');
elements[i].length = $(this).data('length');
elements[i].width = $(this).data('width');
elements[i].weight = $(this).data('weight');
elements[i].created_by = $(this).data('created_by');
});
Then I'm sending it via an Ajax request:
//SEND TO PHP
$.ajax({
method: "POST",
url: "php/i.php",
data: {elements: elements, obj: obj},
success: function(result){
},
error: function(e){
console.log(e.message);
}
});
This works if the elements obj isn't too big. (I guess).
Is there a limit of size i need to change somewhere?
I have no problem uploading big files like photos etc.
This two dumps represent one Ajax call that works and have data in PHP $_POST,
and one where $_POST returns empty.. i guess it's the size that that makes the difference?!
I have a canvas that lives on top of a video. When a user pauses the video they are able to add fabricjs objects to the canvas. When an object is added to the canvas it is saved to a table in a mysql database as JSON.
When the user clicks a button it will query the mysql database for records and return via ajax the objects for each record in an array.
As it loops through this array I want fabricjs to render each object one at a time until all objects have been rendered.
I have tried using :
canvas.loadFromJSON(rData, canvas.renderAll.bind(canvas), function(o, object) {
fabric.log(o, object);
});
It will load all objects but clears the canvas before each load and will only display the last object.
I have tried the example here:
http://codepen.io/Kienz/pen/otyEz but cannot seem to get it to work for me. I have also tried http://jsfiddle.net/Kienz/bvmkQ/ but cannot see what is wrong.
So I have come to the experts! I appreciate all and any help. Thank you.
Here is my table in mysql wth 2 records:
CREATE TABLE IF NOT EXISTS `telestrations` (
`id_telestration` int(11) NOT NULL AUTO_INCREMENT,
`object` longtext NOT NULL,
PRIMARY KEY (`id_telestration`),
UNIQUE KEY `id_telestration` (`id_telestration`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=65 ;
--
-- Dumping data for table `telestrations`
--
INSERT INTO `telestrations` (`id_telestration`, `object`) VALUES
(63, '{"objects":[{"type":"i-text","originX":"left","originY":"top","left":161.05,"top":359.29,"width":69.3,"height":20.97,"fill":"#e6977e","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"AAAAAA","fontSize":16,"fontWeight":"bold","fontFamily":"arial","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"left","textBackgroundColor":"","styles":{"0":{"1":{},"2":{},"3":{},"4":{},"5":{}}}}],"background":""}'),
(64, '{"objects":[{"type":"i-text","originX":"left","originY":"top","left":463.68,"top":353.84,"width":69.3,"height":20.97,"fill":"#20f20e","stroke":null,"strokeWidth":1,"strokeDashArray":null,"strokeLineCap":"butt","strokeLineJoin":"miter","strokeMiterLimit":10,"scaleX":1,"scaleY":1,"angle":0,"flipX":false,"flipY":false,"opacity":1,"shadow":null,"visible":true,"clipTo":null,"backgroundColor":"","fillRule":"nonzero","globalCompositeOperation":"source-over","text":"BBBBBB","fontSize":16,"fontWeight":"bold","fontFamily":"arial","fontStyle":"","lineHeight":1.16,"textDecoration":"","textAlign":"left","textBackgroundColor":"","styles":{"0":{"1":{},"2":{},"3":{},"4":{},"5":{}}}}],"background":""}');
Here is my php file:
$teles = Telestration::getTeleByVideo();
$objArray = array();
foreach($teles as $tele){
$obj = $tele->getValueEncoded('object');
$objArray[] = $obj;
}
echo json_encode($objArray);
Here is my JavaScript:
document.getElementById("get_json").onclick = function(ev) {
$.ajax({
url: 'getTelestrations.php',
data: dataString,
type: 'POST',
dataType:"json",
success: function(data){
for (var i = 0; i < data.length; i++) {
rData = data[i].replace(/"/g, '\"');
//Do something
canvas.loadFromJSON(rData, canvas.renderAll.bind(canvas), function(o, object) {
fabric.log(o, object);
});
}
}
});
}
Hello inside your success function use instead of canvas.loadFromJSON , the fabric.util.enlivenObjects() funtion, like this:
//inside the success function, you get the results data from the server and loop inside the items, allright if you have only one object but use loop for more.
results.data.forEach(function (object) {
var tmpObject = JSON.parse(object.table_data);
fabric.util.enlivenObjects([tmpObject], function (objects) {
var origRenderOnAddRemove = canvas.renderOnAddRemove;
canvas.renderOnAddRemove = false;
console.log(objects);
objects.forEach(function (o) {
canvas.add(o);
console.log(o);
});
canvas.renderOnAddRemove = origRenderOnAddRemove;
canvas.renderAll();
});//end enlivenObjects
});//end data.forEach
Hope this helps, good luck
I was able to figure out how to load each object. It turns that the json returned from my mysql was not "workable" for fabricjs. I had to clean my json and then the objects would load.
I only made changes to my javascript:
$.ajax({
url: 'getTelestrations.php',
data: dataString,
type: 'POST',
dataType:"json",
success: function(data){
for (var i = 0; i < data.length; i++) {
//clean results for json
json_result = data[i].replace(/"/g, '\"'); //remove quotes from entire result
json_clean = json_result.replace(/"objects"/, 'objects'); //remove quotes around first object
jsonObj = JSON.parse(JSON.stringify(json_clean)); // parse the entire result
jsonobj2 = eval('(' + jsonObj + ')');
// Add object to canvas
var obj = new fabric[fabric.util.string.camelize(fabric.util.string.capitalize(jsonobj2.objects[0].type))].fromObject(jsonobj2.objects[0]);
canvas.add(obj);
canvas.renderAll();
}
}
});
I used AJAX to send back an array with many variables worth of data to my page to have displayed. The array looks something like this right now:
{"dateName":"05/18/2016","hour1":null,"hour2":null,"hour3":null,"hour4":null,"hour5":null,"hour6":null,"hour7":null,"hour8":null,"hour9":null,"hour10":null,"hour11":null,"hour12":null,"hour13":null,"hour14":null,"hour15":null,"hour16":null,"hour17":null,"hour18":null,"hour19":null,"hour20":null,"hour21":null,"hour22":null,"hour23":null,"hour24":null}
Now I am displaying the parts of the array in my data boxes using
//AJAX Data
success: function(data) {
var array = data.split(",");
$("#date").html(array[0]);
i = 0;
while (i < 25) {
$("#hour"+i).html(array[i]);
i++;
}
This displays data that looks like this on my webpage
"hour1":"sleep"
As you can see, the variable name in quotes and the variable value that was passed through ajax. But I only want
sleep
displayed (no quotes, no variable) . How do I get the variable name and quotes out of my displayed data?
Thank you so much!
use this
$.ajax({url: "demo_test.txt", success: function(result){
// $("#div1").html(result);
var parsed = JSON.parse(result);
alert(parsed["hour1"]);
}});
//AJAX Data
success: function(data) {
var hour = "hour";
for(var i=0; i<data.length; i++) {
hour += i;
console.log(data.hour)
}
Through the help of a few of you awesome members here at stackexchange I have finally figured out how to send an ajax, call back multiple variables, and arrange them cleanly on my page. Attached is my code, I hope that this can help future users.
//SEND MULTIPLE DATA THROUGH AJAX
<script>
function ajax() {
$.ajax({
type: "POST",
url: "changeDate.php",
data: {
amount: changeDate,
loginName: "benjamin_lawson"
},
success: function(result) {
//make array out of data
var array = JSON.parse(result);
$("#date").html(array[0]);
i = 0;
while (i < 25) {
//call array information for parts
$("#hour"+i).html(array[i]);
i++;
}
}
});
}
</script>
<?php
//create the array
$response_arr = array();
//add your variables to the array
$response_arr[] = date("m/d/Y", strtotime("+" . $amount . " day"));
$response_arr[] = $row[$dateName];
//echo the final array to be sent to your ajax
echo json_encode($response_arr);
?>
success: function(data) {
var json_obj =JSON.parse(data)
$("#date").html(json_obj['datename']);
i = 0;
while (i < 25) {
$("#hour"+i).html(json_obj['hour'+i]);
i++;
}
}
You can use JSON.parse to convert the string to json obj :
json_obj=JSON.parse(data)
$("#date").html(json_obj['']);
I am trying to create an associative array with the record id as the key and order as the value. I then want to pass this via ajax to php where I will foreach through the array and update the records. But it is not working I seem to be getting null at json_decode($_REQUEST['orderArray'], true);
Whats wrong with the code:
jquery :
//Make project task table rows sortable
$('#Task_table tbody').sortable({
items: "tr:not(.disable_sort)",//disable sortable on header row
helper: fixHelperModified, //call helper function
update: function(event, ui) {
var order = {};//create object
$('#Task_table tr').each(function(){//loop through rows
var id = $(this).children('td:first-child').find(".order_number").attr("rel");
var order_number = $(this).children('td:first-child').find(".order_number").val();
//fill object array with keys(task->id) and values (task->order_number)
order[id] = order_number;
});
//convert array to json
var jsonArray = JSON.stringify(order);
//prepare POST data
var dataString = { 'orderArray':jsonArray };
$.ajax({
type: "POST",
url: "index.php?module=Project&action=update_order",
data: dataString,
success: function() {
// location.reload();
}
});
}
});
this sends via post:
orderArray {"4b0df1da-8b2d-7776-0026-52d0b3cefbfa":"3","161699ae-6db0-43d6-e85b-52ca07767b0f":"1","8da4cfc3-b56d-12da-e34c-52d09ed0b310":"2"}
The php:
//updates the order of the tasks
function action_update_order(){
//create object/array from json data
$orderArray = json_decode($_REQUEST['orderArray'], true);
var_dump($orderArray);
foreach($orderArray as $id => $order_number){
$GLOBALS['log']->fatal('order: '.$order_number[$id]);
$task = new ProjectTask();
$task->retrieve($id);
$task->order_number = $order_number;
$task->save();
}
}
As I said I cant seem to foreach through the result of the jasondecode. Also hard to debug as its ajax.
can you try change this
var dataString = { 'orderArray':jsonArray };
to
var dataString = { 'orderArray': order };
For some reason JSON.stringify(order) is adding the Html entity version of " to my string so I need to use htmlspecialchars_decode(); in my php first before json_decode. It seems to work.
I can't seem to get around this issue... Json I'm trying to pass to an MVC Controller keeps coming out like this
"\"{MaterialQuantity: { MaterialID :18, Quantity:1}}\""
This is the code that generates it:
function CreateJsonForQuantities() {
var inputs = $('input[name=MaterialQuantity]');
var total = inputs.length;
var data = "";
inputs.each(function (index) {
data = data + $(this).val();
if (index != total -1)
data = data + ',';
});
return data;
}
And this is the hidden which it reads data from (of course this is auto-generated as well)
<input name="MaterialQuantity" type="hidden" value="{MaterialQuantity: { MaterialID :12, Quantity:5}}" />
What am I doing wrong?
UPDATE
Ok so now I'm properly getting json object and my ajax requests looks like this. Problem now is that it does pass proper objects but all values are null in the controller action :(
var form_data = CreateJsonForNorm();
var quantity_data = CreateJsonForQuantities();
var data = { norm: form_data, mqvm: quantity_data };
$.ajax({
type: "POST",
url: form.attr("action"),
data: data,
success: function () {
location.href = "#Url.Action("Index")";
('#addDialog').dialog("close");
},
error: function () {
alert("Error");
}
});
Try using JSON.stringify(data) in your request