How can I parse specific parts of my AJAX array in Javascript? - javascript

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['']);

Related

Passing an array of strings from JS to PHP

I have an array of strings in JS, and I want to send it to php (to be able to add it to db). This is my current code -> showing success message, but not showing the $_POST['array'] variable.
Keep in mind that that array I want to send has string values only and is called times
JS
function fetchDates(){
times = [];
var table = document.getElementById("timeScheduleBody");
var tableRows = table.getElementsByTagName("tr");
for(var j=0;j<tableRows.length;j++){
var tableCells = tableRows[j].getElementsByTagName("td");
for(var i = 0;i<tableCells.length;i++){
if(tableCells[i].getAttribute('class').includes("success")){
var arr = tableCells[i].getAttribute('value').split("-");
var date, hour, mins;
date = arr[0];
hour = arr[1];
mins = arr[2];
times.push(date);
times.push(hour);
times.push(mins);
}
}
}
window.alert(times);
//send array to PHP from jQuery
jQuery.ajax({
type: "post",
url: window.location.href,
data: {array:times},
success: function(){
alert("done");
}
});
}
PHP
<?php
if(isset($_POST['array'])){
$array = $_POST['array'];
echo $array[0];//just testing -> output: nothing
foreach($array as $d){
print '<script>window.alert($d);</script>';//also just to test -> output: nothing
}
}
?>
But you're not getting and showing the response of the ajax call, to see the response you have to get the response in the success function...
PHP (test.php - Create this file and put it in the same directory):
<?php
if(isset($_POST['array']))
print_r($_POST['array']);
?>
JQUERY:
$.ajax({
type: 'POST',
url: 'test.php',
data: { array: times },
success: function(response) {
alert(response);
}
});
You'll see the array content. You're sending the javascript array correctly, but if you want to see the response of the ajax call you have to get it in the success function and do something with it (alert it, add it to the DOM, etc.)

How to access only one object send by json not the whole array in ajax success function?

I am trying to receive data from the controller to the view using json_encode and ajax functions. But I am sending to separate values through json, and I am tring to access it. So how can I separate those two objects, and get only a single value?
Let me show you my code:
function check_relation_status()
{
var id=$('.id_data').attr('value');
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/check_relation_status"); ?>',
data:{id:id},
dataType:'json',
success:function(data)
{
console.log(data);
var ParsedObject = JSON.stringify(data);
var sender_Data = $.parseJSON(ParsedObject);
var senders_id=sender_Data.senders_id;
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/get_senders_data"); ?>',
data:{id:senders_id},
dataType:'json',
success:function(data)
{
console.log(data);
var ParsedObject = JSON.stringify(data);
var sender_values = $.parseJSON(ParsedObject);
var senders_name=sender_values.sender_data;
// alert(senders_name);
$.each(sender_values, function(key,data)
{
var uname = data.uname;
// alert(uname);
$('#friendship_request').append('<div>'+uname +'has sent you a request</div>');
});
}
});
}
});
}
now the controller code
public function get_senders_data()
{
$sender_id=$this->input->post('id');
$this->load->model('Pmodel');
$userdata=$this->Pmodel->getUserdata($sender_id);
$senders['senders_data']=$userdata;
$senders['senders_post'] = $this->Pmodel->get_all_count($sender_id);
// print_r($senders);
echo json_encode($senders);
}
the json value '$senders' holds both the values but when i try to access it usng 'each' function it shows the values two time when there is only a single column for uname . let me add some images to explain.
Where I am wrong?
Try to change like below:-
if(uname){
$('#friendship_request').html('<div>'+uname +'has sent you a request</div>');
}
Note:-
1.You are appending all usernames (which is not correct).
2.You are not checking that username is either undefined or null or empty etc

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

JSON parse data in javascript from php

I'm trying to retrieve data in a javascript file from a php file using json.
$items = array();
while($r = mysql_fetch_array($result)) {
$rows = array(
"id_locale" => $r['id_locale'],
"latitudine" => $r['lat'],
"longitudine" => $r['lng']
);
array_push($items, array("item" => $rows));
}
ECHO json_encode($items);
and in the javascript file I try to recover the data using an ajax call:
$.ajax({
type:"POST",
url:"Locali.php",
success:function(data){
alert("1");
//var obj = jQuery.parseJSON(idata);
var json = JSON.parse(data);
alert("2");
for (var i=0; i<json.length; i++) {
point = new google.maps.LatLng(json[i].item.latitudine,json[i].item.longitudine);
alert(point);
}
}
})
The first alert is printed, the latter does not, it gives me error: Unexpected token <.... but I do not understand what it is.
Anyone have any idea where am I wrong?
I also tried to recover the data with jquery but with no positive results.
This should do it.
$.post("Locali.php",{
// any parameters you want to pass
},function(d){
alert("1");
for (var i=0; i<d.length; i++) {
point = new google.maps.LatLng(d[i].item.latitudine,d[i].item.longitudine);
alert(point);
}
}, 'json');
the PHP is fine if it is giving the response you mentioned above.
I think u should look more for the data you are getting from the php file. Definitely this is a parse error and must be missing some bracket/something else, ultimately not making the data returned to be a json parseable string.
You should be Ok with this slight modifications:
$items = array();
while($r = mysql_fetch_array($result)) {
$items[] = array(
"id_locale" => $r['id_locale'],
"latitudine" => $r['lat'],
"longitudine" => $r['lng']
);
}
echo json_encode($items);
And the jQuery:
$.ajax({
type:"POST",
dataType: 'json',
url:"Locali.php",
success:function(data){
console.log(data);
for (var i=0; i<data.length; i++) {
point = new google.maps.LatLng(data[i].item.latitudine,data[i].item.longitudine);
alert(point);
}
}
})
data $.ajax({
type:"POST",
dataType: json,
url:"Locali.php",
success:function(data){
for (i in data) {
point = new google.maps.LatLng(json[i].item.latitudine,json[i].item.longitudine);
alert(point);
}
}
})
Try it like that.
yeah just try
for (var i=0; i<json[0].length; i++) {
cause you have an object there..

Categories