Alerting Javascript array object shows empty - php

I am trying to send the JavaScript array to my php, but php gets empty [].
It even shows like that in my browser. I have always sent JSON and had no problem, but now have this format.
I have this example that makes no sense...it's just a code to illustrate the issue:
var blah = [];
var letters = ['a', 'b', 'c', 'd'];
for (var i = 0; i < letters.length; i++)
{
blah[letters[i]] = i;
}
Inside firebug DOM it shows as follows:
blah []
a 0
b 1
c 2
d 3
When I do
alert(blah) ------------------------------- I get empty
alert(JSON.stringify(blah)) ----- I get []
alert(blah.a) ---------------------------- I get 0
So how can I pass this object to php? Thanks

Instead of an array, try using an object.
So instead of:
var blah = [];
Try
var blah = {};

Arrays are continuously numerically indexed. They do not have strings as key names.
What you want is an object {}, not an array [].

Can not assign key value collection in array. You need to work on objects:
var obj = {
key1: value1,
key2: value2
};
for converting array to string you can use:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.toString();
with seperator:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
var energy = fruits.join(" and ");
Here is working Demo
try this:
var blah = {};
var letters = ['a', 'b', 'c', 'd'];
for (var i = 0; i < letters.length; i++)
{
blah[letters[i]] = i;
}
alert(JSON.stringify(blah));

I have answered this before. Anyway, blah is an array, but you are not using it as array, you are using it as a hashmap. Arrays work with indexes and maps work with keys. Any object in JS can also act like a map. For e.g
var obj = new Object();
obj.a = 10;
obj["b"] = 20;
var obj2 = function(){...}
obj2.foo = 10;
obj2.bar = "baz";
Similarly, Array is also and Object and can act like a map. But when you use the array like a map, its array is not utilized to store the elements. They just act like above. So the length of an Array is 0 even though it has properties attached to it.
What you must do is use Array methods like push and pop to populate and retrieve from it.

Related

How to assign the value to JSON by giving INDEX also

How to assign the value to the JSON by providing the index for it..
see the following code,
var jsonVariable = [];
jsonVariable[10] = {1:10};
alert(jsonVariable.toSource());
For the above code the output is,
[,,,,,,,,,{1:10}]
The output i expect and i need is [10 : {1:10}]
How to code to bring the output as i expect... please help me briefly..
You used index-operators ([]), which instanciate a new array and set the element at index 10 to {1: 10}. You actually wanted to use curly braces operators ({}) which instanciate a new object and ad a property 10: {1:10} like that:
var jsonVariable = {};
jsonVariable[10] = {1:10};
alert(jsonVariable.toSource());
Setting members to an array, you can't simply skip some indices (begin at 10). All uninstaciated indices until yours will forcible be created.
When you specify an array index that doesn't yet exist like [10], all previously unfilled indices are created. Just .push() it on.
var jsonVariable = [];
// A numeric property should be a string "1", though the browser will probably forgive you
// Just push the new object onto the array
jsonVariable.push({"1":10});
alert(JSON.stringify(jsonVariable));
// [{1:10}] exactly as you describe
If you need this particular object {1:10} to be present at jsonVariable[10], make it an object {} rather than an array.
var jsonVariable = {};
jsonVariable["10"] = {"1": 10};
alert(JSON.stringify(jsonVariable));
// {"10":{"1":10}}
I guess what you need is:
var jsonVariable = [];
for(var i=0;i<10;i++){
var temp = {};
temp[i] = {'Property' : "Data"}
jsonVariable.push(temp);
}
console.log( JSON.stringify(jsonVariable));
try this:
var jsonVariable = [];
jsonVariable[10] = {1:10};
function isNotEmpty(element, index, array) {
return array[index];
};
jsonVariable = jsonVariable.filter(isNotEmpty);
alert(jsonVariable.toSource());

foreach for javascript, json array

I have a JSON array that looks like this:
[{"RegDate":"31-03-2011"},{"RegDate":"29-07-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"12-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"23-08-2011"},{"RegDate":"07-09-2011"},{"RegDate":"09-09-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"03-11-2011"},{"RegDate":"03-11-2011"},{"RegDate":"11-11-2011"},{"RegDate":"16-11-2011"},{"RegDate":"18-11-2011"},{"RegDate":"21-11-2011"},{"RegDate":"02-12-2011"},{"RegDate":"02-12-2011"},{"RegDate":"12-12-2011"}]
The code to get this json array is as of the following:
var unavailableDates1 = jQuery.parseJSON('<?php echo json_encode($noticesDates) ?>');
I am trying too get all of the dates in that array (which was originally a multidimensional array), and put it inside one array:
var unavailableDates = ["9-3-2012", "14-3-2012", "15-3-2012"]; for example
I am unsure of how to do this, I have tried a foreach but wasn't successful.
All help will be appreciated.
First of all, that parseJSON is unnecessary and actually dangerous. Take it out:
var unavailableDates1 = <?php echo json_encode($noticesDates) ?>;
Then, just use jQuery.map:
var unavailableDates = $.map(unavailableDates1, function(item) {
return item.RegDate;
});
Using a string like that is dangerous for the following three objects, for example:
{"key":"Backslash here: \\"}
{"key":"I'm a horse!"}
{"key":"Some\\backslash"}
They become, respectively:
SyntaxError: Unexpected end of input (Single escape escapes end of string)
SyntaxError: Unexpected identifier (Unescaped single quote breaks out of the string, actually an XSS vulnerability)
Object
key: "Someackslash" (\\b becomes the \b backspace control character)
__proto__: Object
You could escape it again, but there's no need; valid JSON is always a valid JavaScript object, and you can trust your own PHP not to include injection code in there.
var justDates = [];
for (var i=0; i < unavailableDates1.length; i++) {
justDates.push(unavailableDates1[i]['RegDate']);
}
Each Object ({'RegDate:'date'}) is an item in a javascript array. To get an item you use a numerical index. so to get the first item would be theArray[0] this would give you {"RegDate":"31-03-2011"}. Then to get that particular date string you just have to use the key theArray[0]['RegDate']!. So since you want to go through every member of a list, you should get the list length using .length.
For loops are usually used for this type of iteration and not for..in. because for in can access properties that are undesired! http://javascriptweblog.wordpress.com/2011/01/04/exploring-javascript-for-in-loops/
have a look at how to iterate over an array.
You can do something like:
dates = new Array();
unavailableDates1.forEach(function (obj){
dates.push(obj.RegDate);
};
Try the following:
JavaScript:
var x = [{"RegDate":"31-03-2011"},{"RegDate":"29-07-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"09-08-2011"},{"RegDate":"12-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"15-08-2011"},{"RegDate":"23-08-2011"},{"RegDate":"07-09-2011"},{"RegDate":"09-09-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"13-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"25-10-2011"},{"RegDate":"03-11-2011"},{"RegDate":"03-11-2011"},{"RegDate":"11-11-2011"},{"RegDate":"16-11-2011"},{"RegDate":"18-11-2011"},{"RegDate":"21-11-2011"},{"RegDate":"02-12-2011"},{"RegDate":"02-12-2011"},{"RegDate":"12-12-2011"}];
var ary = new Array();
for (foo in x) {
ary.push(x[foo].RegDate);
}
console.log(ary);
jsFiddle example.
I noticed you tag jquery in here as well so, here's a jquery solution:
http://jsfiddle.net/aztechy/DK9KM/
var foo = [
{"RegDate":"31-03-2011"},
{"RegDate":"29-07-2011"},
{"RegDate":"09-08-2011"},
{"RegDate":"09-08-2011"}
];
var datesArray = [];
$.each(foo, function() {
datesArray.push(this.RegDate);
});
console.log(datesArray);​
Try This, it may works.
var unavailableDates = [];
for(var i = 0; i < unavailableDates1.length; i++){
unavailableDates[i] = unavailableDates1[i].RegDate;
}
for(var i=0;i<unavailableDates.length;i++) {
unavailableDates[i] = unavailableDates[i].RegDate;
}

JavaScript: Remove keys from json object

Example output from PHP:
{
"RootName_0":{"Id":1,"ValId":1,"Value":"Colour","Text":"Blue"},
"RootName_1":{"Id":1,"ValId":2,"Value":"Colour","Text":"Red"}
}
How can I use Backbone.js or jQuery to only have:
[
{"Id":1,"ValId":1,"Value":"Colour","Text":"Blue"},
{"Id":1,"ValId":2,"Value":"Colour","Text":"Red"}
]
If it's easier to use PHP to edit the JSON, then so be it.
Well, in PHP it would be easy, just use array_values() on the initial array so that it 'forgets' the array indexes (which by the way, is what 'RootName_X' is called in your case:
$newvalue = array_values( (array)$value );
echo json_encode($newvalue);
In javascript, it's a bit trickier, but it would be on the lines of:
var newvalue = [];
for(var root in value)
newvalue.push(value[root]);
The question title is was a bit confusing since these are certainly not tags.
No need for jquery or Backbone:
var obj = {
"RootName_0":{"Id":1,"ValId":1,"Value":"Colour","Text":"Blue"},
"RootName_1":{"Id":1,"ValId":2,"Value":"Colour","Text":"Red"}
};
var colors = [];
for(var key in obj){
colors.push(obj[key]);
};
The value you want is now in the colors array.
Using ES5 (modern browsers) you could do:
Object.keys(received).map(function(key) {
return received[key];
});
Basically, converting the object into an array of its keys, then replacing each key with the value.
In javascript, if myFirstVar contains the initial object, then do:
mySecondVar = [ myFirstVar.RootName_0, myFirstVar.RootName_1 ];
Once the JSON has been parsed, do it using jQuery's jQuery.map, and borrowing the global Object function...
var arr = $.map(obj,Object);
EDIT:
If you do it in JavaScript, you should be aware that the objects may not remain in their original order.
You can remedy this if the RootName_n keys are sequential, and you know the n of the last key.
var last_key = 20;
var arr = [];
for(var i = 0; i <= last_key; i++)
arr.push( obj['RootName_' + i] );

JavaScript arrays behave like PHP?

Is there a way to assign values in a JavaScript array in the way I do it in PHP.
For example in PHP I can do that:
$ar = array();
$ar[] = "Some value";
$ar[] = "Another value";
Is that posible to be done with JavaScript? Or if not is there any similar way ?
The direct translation of your original code is
var ar = [];
ar[ar.length] = "Some value";
ar[ar.length] = "Another value";
However a better looking solution is to use the pretty universal push method:
var ar = [];
ar.push("Some value");
ar.push("Another value");
As with most languages, JavaScript has an implementation of push to add an item to the end of an array.
var ar = [];
ar.push("Some value");
ar.push("Another value");
var myArray = [];
myArray.push('value1');
myArray.push('value1');
Or
var myArray = [];
myArray[myArray.length] = 'value0';
myArray[myArray.length] = 'value1';
myArray[myArray.length] = 'value2';
Check out this reference document for more about javascript arrays: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array
Arrays are treated slightly different in javascript. In PHP, an array like this:
PHP
$myArray = array();
$myArray[1] = 'value';
$myArray[10] = 'value';
echo count($myArray); // output: 2
Javascript:
var myArray = [];
myArray[1] = 'value';
myArray[10] = 'value';
console.log(myArray.length); // output: 11
What's going on here? In PHP, an array is an dynamic container. The indexes needn't be sequential - indeed, there is little difference between an associative array (an array with string indexes instead of numeric ones) and a standard array.
In javascript, the concept of "associative array" does not exists in the array context - these would be object literals instead ({}). The array object in javascript is sequential. If you have an index 10, you must also have the indexes before 10; 9,8,7, etc. Any value in this sequential list that is not explicitly assigned a value will be filled with the value undefined:
From the example above:
console.log(myArray); //[undefined, "value", undefined, undefined, undefined, undefined,` undefined, undefined, undefined, undefined, "value"]

Php pass array to Javascript

I want an array in Javascript, structure like this
$(function()
{
// prepare the data
for (var i=0; i<50000; i++) {
var d = (data[i] = {});
d["id"] = "id_" + i;
d["num"] = i;
d["title"] = "Task " + i;
d["duration"] = "5 days";
}
I want this array to be created through php.
I already have the array there created by for loop
EDITED:
Is the above data in Javascript a multidimensional array, a simple array or a var?
is the structure saved in "d" or in data[i][id],data[i][title],... ?
ie, $data = array('item' => 'description', 'item2' => 'description2');
json_encode($data);
All you need
Use json_encode() to encode the array.
Access PHP variable in JavaScript
That example works with arrays, too.

Categories