Make array jquery/js - javascript

I want to make an array like this. (on alert it gives object)
var playlist = [{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"}];
From:
var playlist = [];
$.ajax({
url: 'url.php',
data: {
album_name: album_name
},
type: 'POST',
success: function( data ) {
var data_array = JSON.parse(data);
for( var i=0; i<data_array.length; i++ ) {
var value = data_array[i].split('::');
playlist.push('{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"},'); // putting the same thing just for testing.
}
alert(playlist);
}
});
Now the new array playlist didn't seem to be working for me. i guess there is something wrong the way i am creating an array like above.

you need to push object instead of object string:
playlist.push({"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"});
//------------^---remove the single quote.

Try this one
var playlist =[{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"}];
alert(JSON.stringify(playlist));

Use jQuery.map() for making array.
playlist = $.map(data_array, function(val, i){
splitArr = val.split('::')
return {
'title':splitArr[0],
'mp3':splitArr[1]
}
})

As #Jai said you need to push an object: playlist.push({"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"});
Arrays in JavaScript are objects.
You'd be better using the console to log or debug your javascript.
In this fiddle you can see
that the array is created and the object pushed to it but its
still logged as an object.
And since you are using jQuery it has a method isArray() to determine if
something is an array or not.

or you can try like this
var playlist = [];
$.ajax({
url: 'url.php',
data: {
album_name: album_name
},
type: 'POST',
success: function( data ) {
var data_array = JSON.parse(data);
for( var i=0; i<data_array.length; i++ ) {
var value = data_array[i].split('::');
var ArrObj = '{"title":"Kalimba","mp3":"http://www.jplayer.org/audio/mp3/TSP-01-Cro_magnon_man.mp3"},';
playlist.push(ArrObj);
}
alert(playlist);
}
});

Related

jquery.html array as a selector

Below is my code for getting a data from api for 2 different URLs. The result is positive when I use $('#resultDiv1').html instead of opts[j].html. On using opts[j].html, I am getting error as opts[j].html is not a function'. Where is the mistake? Please help me.
var domain = "https://example.com/api#token=";
var detail = "/some_data"
$(document).ready(function() {
var token = ['260105', '49409' ];
var resultElement1 = $('#resultDiv1');
var resultElement2 = $('#resultDiv2');
var opts = ["resultElement1", "resultElement2"];
for (j=0; j<1; j++){
$.ajax({
url: domain + token[j] + detail,
method: 'get',
dataType: 'json',
success: function(response) {
opts[j].html(response.data.candles[response.data.candles.length - 1][4]);
}
})
}
});
That won't work because "resultElement1" and "resultElement2" are two different strings in the opts array. To use the selected elements, you need to create array using the variables resultElement1 and resultElement2, like this:
var opts = [resultElement1, resultElement2];
Also, your for loop will only work for resultElement1, because you end the iteration as soon as j becomes 1.

push object to array and eventually convert array to json

I am creating an object and pushing it into array.Then I convert it into json.When I alert dataCharts it is returned as:
[{"AllLinks":"Link9","LinkURL":"url1"},{"AllLinks":"Link6","LinkURL":"url2"}]
Whereas I want it as:
[{AllLinks:"Link9",LinkURL:"url1"},{AllLinks:"Link6",LinkURL:"url2"}]
My code is as follows:
$.ajax({
url: url,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var array = new Array();
var temp = new Object();
for (var i=0; i< data.d.results.length; i++) {
var it=data.d.results[i];
array.push({
"AllLinks": it.AllLinks,
"LinkURL": it.LinkURL.Url
});
}
dataCharts=JSON.stringify(array);
alert(dataCharts);
AddDefaultLinks(dataCharts);
},
error: function (data) {
alert(data.responseJSON.error);
}
});
Hint:
[{"_aaaa_":"bbbb","_cccc_":"eeee"}]
[{aaaa:"bbbb",cccc:"eeee"}]
If you want to remove the quotes: name your label like this:
_AllLinks_: it.AllLinks,
_LinkURL_: it.LinkURL.Url
and then remove the underscores and the quotes like this:
dataCharts.replace(/"_|_"/g,"")
But be carefull that this does not conflict with other data (or take two _ or so)

fabric js load single objects to canvas from mysql database

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();
}
}
});

How to send JavaScript collection to PHP variable?

I am trying to send data from form to PHP file using JavaScript. PHP file pushes this data to database. For now, almost all works well but I have a problem with array from getElementsByClassName. After sending to database I can see only "Array" but no values of this array.
Here's a JS:
function przekaz_form($wejscie) {
var datas = document.formularz.datas.value;
var klient = document.formularz.firma.value;
var comment = document.formularz.comment.value;
var collect = document.getElementsByClassName($wejscie);
var datan = document.formularz.datan.value;
var items = new Array();
for(var i = 0; i < collect.length; i++) {
items.push(collect.item(i).value);
}
jQuery.ajax({
url: 'addtobase.php',
type: 'post',
data:{
devices: items,
datas: datas,
klient: klient,
comment: comment,
datan: datan
},
success: function(output) {
alert('Success');
}
});
}
One way to do this is:
$inputData = json_decode(file_get_contents('php://input'));
Once you have the $inputData variable you can access the data in the JSON by:
$devices = (!is_null($inputData) && property_exists($inputData, "devices")) ? strip_tags($inputData->{"devices"}) : 0;
You should also try to better format the JSON : http://json.org/example

Problem understanding javascript multi-dimension arrays

I want to get some values out of TinyMCE textboxes, along with IDs. Then post these via ajax to the server.
jQuery 1.4 and JSON library are loaded
var send_data = [];
$('.contact_check').each(function(i, item) {
var this_id = $(item).attr('id');
var msgbox = tinyMCE.get('contacts[' + this_id + '][message]');
var content = addslashes(msgbox.getContent());
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
});
var encoded = JSON.stringify(send_data);
$.ajax({
type: 'POST',
url: 'http://localhost/test.php',
data: encoded,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() {
alert('jay');
}
});
Firstly,
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
does not seem to work. It says send_data[i] undefined. I've also tried:
send_data[this_id] = escape(content);
That does not seem to work either. The JSON string returns as []. What am I doing wrong?
You're not really making a multi-dimensional array. You're making an array of objects. Either way, before you can set an attribute or array element of something at send_data[i], you have to make send_data[i] be something.
send_data[i] = {};
send_data[i]['id'] = this_id;
send_data[i]['content'] = escape(content);
or, better:
send_data[i] = {
id: this_id,
content: escape(content)
};
You have to make each send_data[i] an object first:
$('.contact_check').each(function (i, item) {
var this_id = $(item).attr('id');
var msgbox = tinyMCE.get('contacts['+this_id+'][message]');
var content = addslashes(msgbox.getContent());
send_data[i] = {};
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
});

Categories