I'm trying to refresh the content of my cells of an table. Therefore, I have a JavaScript which contains an AJAX request to a .php file, which creates my content that I want to insert into my table via JavaScript. The .php files last command is something like echo json_encode($result);.
Back in the JavaScript it says:
var testarray = xmlhttp.response;
alert(testarray);
But the outut from the alert looks like:
{"1":{"1":"3","2":"0","3":"2","4":"0"}}{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}...
So it seems the variable testarray isn't handled as an array but as a string. I already tried var testarray = JSON.parse(xmlhttp.response), but this doesn’t work. Neither does eval() works.
I don't know what to do, so the response of my request becomes an object.
There are 2 strange things in your json:
this part is not json valid: ...}{...
two object should be separated by comas
The notation is object with string indexes not array with int indexes
it should be something like: [[1,2,3,4],[5,6,7,8]]
for the point 1. it looks like you have a loop that concatenate many json
for the point 2. the object notation can be used as an array so it doesn't matter
Some code:
//the folowing code doesn't work: }{ is not parsable
var a=JSON.parse('{"1":{"1":"3","2":"0","3":"2","4":"0"}}{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}');
//the folowing code work and the object can be used as an array
var a=JSON.parse('{"1":{"1":"3","2":"0","3":"2","4":"0"},"2":{"1":"2","2":"1","3":"1","4":"1"}}');
alert(JSON.stringify(a[1]));
//the folowing code displays the real notation of a javascript array:
alert(JSON.stringify([1,2,3,4]));
I think that the problem here might be that your arrays do not have index 0.
e.g. if you output this from the server - it would produce an object:
$result = [];
for ($i = 1; $i < 5; $i++) $result[$i] = $i;
echo json_encode($result); // outputs an object
if you output this from the server - it would produce an array:
$result = [];
for ($i = 0; $i < 5; $i++) $result[$i] = $i;
echo json_encode($result); // produces an array
Anyways, even if your server outputs array as object - you should still be able to access it normally in javascript:
var resp = xmlhttp.responseText, // "responseText" - if you're using native js XHR
arr = JSON.parse(resp); // should give you an object
console.log(arr[1]); // should give you the first element of that object
Related
My php script returns data to the web client where it is processed by javaScript.
If data is found it is stored in an associative array / object. If no data is found I would like to send a blank associative array.
The only example I have seen on line is in the manual where you create an empty class and then instantiate an object from that.
Below is my code and the results it produces on the web client side
$sql = 'select job, client, project from jobs j left join client c on c.key = j.cKey where j.key='.$this->p['reckey'];
if ( $result = $db->query($sql) )
{
if ($result->num_rows > 0)
{
$l = mysqli_fetch_all( $result, $resulttype = MYSQLI_ASSOC );
$this->res_array['info'] = $l[0];
}else{
$this->errors[] = 'No such job # '.$this->p['reckey'];
$this->res_array['info']=[];
}
}else{
$this->errors[] = 'Query failed!';
$this->res_array['info']=[];
}
$this->res_array['errors'] = $this->errors;
echo json_encode ($this->res_array);
Here are two examples of what the data looks like when it arrives at the web client before it is decoded by JSON. Note the difference in the "info" element.
response {"info":{"job":"999","client":"My Company, Inc. ","project":"This Project"},"errors":[]}
error response {"info":[ ],"errors":["No such job # 0"]}
In the successful response I have an object/associative array where I would use the
for (variable in object) {...}
In the blank response I just get the standard array [ ] square brackets where I would use the
for (step = 0; step < info.length; step++) {}
This occurs of course because I am specifying a blank array in the php code above.
My question is simple how can I change my php code so a blank associtive array is transmitted?
The only example I have seen on line is in the manual where you create an empty class and then instantiate an object from that.
Sounds like you've answered your own question!
Since in JavaScript an object and an associative array are basically the same thing all you have to do is replace this line:
$this->res_array['info']=[];
With this one:
$this->res_array["info"] = new StdClass;
Or if you want to make the change only before sending the response you could check for an empty info array and replace it with an empty class.
if(!count($this->res_array["info"]))
$this->res_array["info"] = new StdClass;
I would suggest to take the best of both worlds, and let PHP generate an array of associative arrays, even though you expect at the most one, but at least you'd use the same structure for when you have none.
So change:
$this->res_array['info'] = $l[0];
to:
$this->res_array['info'] = $l;
And then in JavaScript do:
for (var step = 0; step < info.length; step++) {
for (variable in info[step]) {
// ...
}
}
... and if you still need to, you can deal with the no-data condition separately in JavaScript. Something like:
if (errors.length) {
// deal with this case...
}
I am having a problem of how to organize my variables in flash that are from a PHP script.Ideally i want them in an array type format so i can loop through them.Below is some code to go with.
function completeHandler(evt:Event){ // after loading the php
var symbolsArray:Array = new Array()
symbolsArray.push(evt.target.data.symbol_1);// php variable named: symbol_1, symbol_2
trace(evt.target.data);
}
The above is allworking, the PHP variables are listed as symbol_1, symbol_2 etc
Instead of pushing each variable separably into the array i want a loop, along the lines of:
function completeHandler(evt:Event){
var symbolsArray:Array = new Array()
var counter =1
symbolsArray.push(evt.target.data.symbol_+counter); this is the issue
trace(symbolsArray[0]); //returns NaN
}
Below is the php return vars to flash to give an idea:
$returnVars['symbol_1'] = $virtualReel1[0];
$returnVars['symbol_2'] = $virtualReel1[1];
$returnVars['symbol_3'] = $virtualReel1[2];
$returnVars['symbol_4'] = $virtualReel2[0];
$returnVars['symbol_5'] = $virtualReel2[1];
//etc
$returnString = http_build_query($returnVars);
echo $returnString;
symbolsArray.push(evt.target.data["symbol_"+counter]);
If you need to dynamically query properties of an object, you address it as an Array or a Dictionary, by a string key, which can be dynamically formed. Works on anything.
The returned data can be treated as an Object (containing Objects) so you can loop thru it like so:
function completeHandler(evt:Event)
{
var symbolsArray:Array = new Array();
for each (var obj:Object in evt.target.data)
{
symbolsArray.push(obj);
}
}
If you know all items are oif same type, you can cast the object. eg: if all Numbers:
symbolsArray.push(Number(obj));
Or Strings:
symbolsArray.push(String(obj));
Problem: returns array, but not in json.
Result: must return array with in array. outer array has key with numbers and value is array with keys "ID" and "NAME" and there values are assigned from database.
$i = 0;
$json_values = array();
while($sctg = mysql_fetch_assoc($get_sctg)){
$json_values[$i] = array("ID" => $sctg['ID'], "NAME" => $sctg['NAME']);
$i++;
}
echo json_encode($json_values);
Your code is perfectly fine - you just misunderstood the different between arrays and objects in JavaScript.
[{"ID":"4","NAME":"asdasd"},
{"ID":"3","NAME":"LOKS"},
{"ID":"1","NAME":"LOL"}]
This is JSON containing an array with three elements. Each element is an object with the properties ID and NAME.
Let's assume that array is stored in data. You can iterate over the objects in that array with a simple for loop:
for(var i = 0; i < data.length; i++) {
var row = data[i];
// Here you can use row.ID and row.NAME
}
I guess you expected your JSON to look like this:
{
0: {"ID":"4","NAME":"asdasd"},
1: {"ID":"3","NAME":"LOKS"},
2: {"ID":"1","NAME":"LOL"}
}
This would actually be bad since objects in JavaScript are not ordered (even though they actually are in most browsers, but that's not guaranteed!). So when iterating over the rows in such an element (using for(var key in data)), you would not necessarily get the row with ID=4 first just because its key is zero.
However, if you really want an object instead of an array for some reason (you don't!), you could always cast the array to object:
echo json_encode((object)$json_values);
As a side-note, usually it's a good idea to have an object as the top-level element in JSON for security reasons (you can redefine the array constructor and then include something with a top-level array with a script tag and thus access data usually protected by the same origin policy if it was accessed by an XHR request), so I'd change the PHP code like this:
echo json_encode(array('rows' => $json_values));
No need to use $i++; directly use
while($sctg = mysql_fetch_assoc($get_sctg)){
$json_values[] = array("ID" => $sctg['ID'], "NAME" => $sctg['NAME']);
}
and it will return you the JSON
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;
}
I'm creating an array on the jquery side this way. The array is an array of arrays where each element is an array that looks like [jskey, jsvalue].
var jsarray = [];
// jsarray.push([jskey, jsvalue]);
jsarray.push([1, 123]);
jsarray.push([2, 98]);
jsarray.push([3, 107]);
jsarray.push([4, 34]);
I then add the array to an element of a form before it's submitted
$('#myform input[name=jsvalues]').val(jsarray);
On the php side, I'm expecting to receive an array of array, but all I get when I do a print_r() or var_dump() is a string that looks like this
string() "1,123,2,98,3,107,4,34"
Attribute values are strings. When you convert an array to a string, you get each element in that array converted to a string and separated by commas (unless you override the toString() method (hint: don't)).
I suggest converting the array to JSON and then assigning that to the form control. You can then parse the JSON in PHP.
http://json.org has links (at the bottom) to PHP and JS implementations of JSON serializers / deserializers.
David Dorward gave a really good solution.
To clarify a little bit, when you assign a complex object (like an array) to the attribute of a HTML element (that's what jQuery does when you call val()), the object is converted into a string (by calling the toString method on the object).
An array has a toString method that does exactly what you are experiencing: a list of the values inside the array separated by commas:
[1, [2, 3]].toString(); // returns "1,2,3"
To transmit complex objets, you can use JSON (JavaScript Object Notation) which is native in JS:
$('#myform input[name=jsvalues]').val(JSON.stringify(jsarray));
On the server side, PHP 5 has a really fast JSON API:
$jsvalues = json_decode($_POST['jsvalues']);
You could convert that string back into an array of arrays, assuming they were all pairs:
$arr = explode(",", $_POST['jsvalues']);
$jsvalues = array();
for ($i = 0; $i < count($arr); $i += 2) {
$jsvalues[] = array($arr[$i], $arr[$i + 1]);
}