Sending array via Ajax fails - javascript

var labels = new Array();
<?php foreach($crud_data as $cd ) { ?>
labels['<?php echo $cd['name'] ; ?>'] = '<?php echo $cd['label'] ; ?>';
<?php } ?>
$.post('url.php' , { labels:labels} );
Why can I not send labels array like this? It doesn't show anything in Firebug.
My console.log(labels) result:
[]
avatar
"avatar"
email
"email"
id
"id"
name
"name"
password
"password"
if i populate array like this
<?php foreach($crud_data as $cd ) { ?>
labels.push('<?php echo $cd['label'] ; ?>');
<?php } ?>
$.post('url.php' , { labels:labels} );
it works fine !

Oh I see now. If you have string keys, you have to use an object, not an array:
var labels = {};
Arrays in JavaScript are supposed to only hold elements with numeric keys. While you can assign arbitrary properties to arrays, they are not considered to be elements of the array and thus ignored by most processes which deal with arrays.
Additionally you might want to have a look at jQuery.param to see how jQuery will convert the input to a transport-able string and adjust your data structure accordingly.

labels['<?php echo $cd['name'] ; ?>'] =
It seems you want to create an associative array, which is in fact an object in JavaScript (JavaScript has no dedicated associative arrays). So the array itself is in fact empty because you are adding properties to the array object.

Related

object_to_array and encode - php to js opbject

I send Ajax call to AjaxHandler.php page, the AjaxHandler page call other function in Functions.php (other page).
On success i need to return object from AjaxHandler.php, the object need to have 2 params.
Here is the ajax call:
var month_number = document.getElementById("Month").innerHTML;
var year_number = document.getElementById("Year").innerHTML;
$.get("AjaxHandler.php", { "year": year_number, "month": month_number }, function (encodedata) {
var data = JSON.parse(encodedata);
$("#LinesPlace").html(data);
});
Here is the AjaxHandler.php code the need to handle that:
if(isset($_GET['year'],$_GET['month']))
{
$year = $_GET['year'];
$month = $_GET['month'];
$a = getExpenses($year, $month);
echo $a->pharama;
echo $a->pharamb;
$b = object_to_array($a);
echo $b;
return json_encode($b);
}
Now when i put that url:
http://xxxxxxxxx.com/AjaxHandler.php?year=2015&month=09
Its show me the echo of pharama and pharamb but when i try to convert the object to array and then decode it its just not working, i tryed alot but nothing.
Here is the object_to_array function:
//convert php object to array
function object_to_array($data){
if(is_array($data) || is_object($data))
{
$result = array();
foreach($data as $key => $value) {
$result[$key] = $this->object_to_array($value);
}
return $result;
}
return $data;
}
*I taked that function from this site from other question..
Please advice =]
Regards,
Rafael.
If you need to decode the JSON as an array or object, json_decode has a parameter specifically for that: http://php.net/json_decode
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
...
assoc
When TRUE, returned objects will be converted into associative arrays.
For example:
$json_as_object = json_decode($json, false);
$json_as_array = json_decode($json, true);
Attempting to manually convert an object into an array should be unnecessary.
You need to encode it very specifically with JSON_UNESCAPED_UNICODE like this:
$jsonObj = json_encode ( string $json, JSON_UNESCAPED_UNICODE);
I have this code in a standard function for this sort of thing
http://php.net/manual/en/function.json-last-error.php
PS. I think you are over checking it in your object to array function. I would probably choose something like: if(is_array($param)){ .. }
Rafael I cant comment need 50 rep or something:D You say: What you mean unnecessary? you mean i can return the object php as is?
Half of what if am saying: you know the things you put into the function obj_to_array() rigth? That what goes in and it ain't an object so why check it? Who will send it? Do you foresee a $_POST incomming all wrapped up as a nice object and ready to go? Like normally the form does a $_POST / $_GET and provides arrays by default as far as I know? And if you produce an obj elsewhere in your code why put use it as input for this function? Don't you know what you are doing somewhere else in your code? Sure you do and as long as you are concise and precise it will never suddenly be a object returned form $_POST or any function normally outputting arrays or integers etc. Check your output as you created it in the first place? Check your web inputs very well (1 time! and for js injections), then only check your types for validating ambiguous output / inputs of your own like an output that can produce an array or a true / false return value. Checking this output for a value of 1 for a TRUE value of the boolean can result in disappointment because:
if the value of $a is 1 in if($a) do something; then a 1 can be the TRUE value returned as the result of the function that produced the thing that we are checking or the result of count($a). If we then assume the array is length 1 because of a misinterpretation of the value of $a then this can give unintended results? You want to be sure that it is the array in $_array($a) that's doing the talking and not the array for example? Thats all to it I think? Or am I rambling (again)?

php file to php array to js array - as array of arrays

...
$php_array = mysqli_fetch_all($result,MYSQLI_ASSOC);
?>
<script type='text/javascript'>
<?php
$js_array = json_encode($php_array);
echo "var location = ". $js_array . ";\n";
?>
</script>
How can I modify the above code that gives me this output (an array of objects methinks?)
var javascript_array = [
{"city":"Hermosa Beach","lat":"33.860069","lng":"-118.398784"},
{"city":"San Jose","lat":"34.694628","lng":"-118.398784"},
.... ]
to give me this... (an array of arrays?)
var javascript_array = [
["Hermosa Beach",33.860069,-118.398784],
["San Jose",34.694628",-118.398784],
.... ]
without a bunch of foreaching's...
Use MYSQLI_NUM instead of MYSQL_ASSOC when you call mysqli_fetch_all(). Then the rows will be indexed arrays instead of associative arrays.
Although I don't know why you would want the array to be like this. Arrays should be used for uniform data, objects should be used for heterogeneous data.
thanks, this works and is very lean...
<?php
$query = "SELECT * FROM file";
$result = $con->query($query);
// Fetch all rows and return the result-set as an associative array:
// using numeric keys for the array, instead of creating an associative array.
$php_array = mysqli_fetch_all($result,MYSQLI_NUM);
?>
<script type='text/javascript'>
<?php
// create a JSON representation of a value that javascript will understand
$js_array = json_encode($php_array);
// dump json object into javascript variable 'locations'
echo "var locations =" . $js_array . ";\n";
?>
</script>

Retrieving and using a json associative array

I use jquery and ajax to retrieve a dynamically made array made in php, like so:
$json = array();
while ($row = $stmt->fetch_assoc()) {
$json['item_'.$row['id']] = $row['name'];
}
header('Content-type: application/json; charset=utf-8');
echo json_encode($json);
exit;
If I test the php file in browser, it outputs:
{"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"}
So far so good. But how do I use that array in jquery?
I have this jquery ajax:
$.getJSON( "json.php", function(data) {
console.log(data);
});
And testing that page in browser, it put this in console:
Object {item_3: "Simon", item_1: "Miriam", item_2: "Shareen"}
And that's ok right? Or should item_x also be in quotes?
Now, how do I USE that array in jquery?
If I try console.log(data[0]) it puts undefined
As i mentioned in comments, php associative arrays become javascript objects, which cant be accessed numericaly.
A solution would be to send an array of objects instead:
while ($row = $stmt->fetch_assoc()) {
$json[]= ['key'=>'item_'.$row['id'] , 'value' => $row['name']];
}
the in js:
data[0].key;
data[0].value;
EDIT obviously key is a misleading name in this example, better to call it something else:
$json[]= ['id'=>'item_'.$row['id'] , 'value' => $row['name']];
//js
data[0].id;
Try to use $.each() to iterate through that object,
$.each(data,function(key,val){
console.log(key,val);
});
DEMO
If you want to access it without iterating it then simply use bracket notation
data['item_3'] //Simon
Or directly access it like,
data.item_3 //Simon
Then convert it like an array as per your wish like this,
var obj = {"item_3":"Simon","item_1":"Miriam","item_2":"Shareen"};
var convertedArray = $.map(obj,function(val,key){
var obj = {}; obj[val] = key;
return obj;
});
DEMO

Database string value to PHP array to be used in Javascript

I need to store values into a Wordpress database and the use the value in a Google Chart.
The questions are:
1. What format do I use to store it into the database?
Currently I am using WP-TYPES and adding the array as follows to a Multi Line Box:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
This is what it needs to output in the Javascript for the chart.
Convert the String to a array in PHP (Not doing it correctly)
I retrieve the data with:
$graphdata = types_render_field("graph-data", array("output" => "raw","separator"=>";"));
This gives me a string value.
Then I add it to an array:
$thechartcontent[$i] = [
"name" => get_the_title(),
"chartheaders" => array($graphdata),
];
In JavaScipt:
I set the PHP Array to Java
var chart1 = <?php echo json_encode($thechartcontent[0]); ?>;
Then I get the data from the array to a var:
var chartheaders1 = chart1['chartheaders'];
This is where I get stuck. The value that I get is a string. It needs to show exactly this:
['Month','Value 1','Value 2'],['2004',1000,400],['2005',1170,460],['2006',660,1120],['2007',1030,540]
for it to work.
Any help please.
Well, it will not be exacly like you want since it's JSON encoded in JSON format. This might be useful. Or you can convert object into array in JS.
I suspect that what you are outputting is an array containing a string, which is not what you want. You must split $graphdata into an array of arrays containing your data before adding it to $thechartcontent:
$graphdata = substr($graphdata, 1, strlen($graphdata) - 1); // trim the opening and closing brackets
$graphdata = explode('],[', $graphdata); // split $graphdata into an array of strings
foreach($graphdata as &$row) {
$row = explode(',', $row); // split the row into an array
}
$thechartcontent[$i] = array(
'name' => get_the_title(),
'chartheaders' => $graphdata
);
When you json encode the data, you should use the JSON_NUMERIC_CHECK constant, so your numbers don't get quoted as strings:
var chart1 = <?php echo json_encode($thechartcontent[0], JSON_NUMERIC_CHECK); ?>;

json_decoded array in php - get key and values

I have a array which comes through an POST request from javascript/jquery. In php the array content is as follows:
[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},{"name":"manual","def":"somestring"}]
How do I iterate over this array to get the keys and values?
When I do: json_decode($_POST['shape_defs'])
How do I iterate over this array. Doing foreach says:
Invalid argument supplied for foreach()
While the (current) other two answers do get working code, they fail to address why you get the error you do.
$data = json_decode($j);
var_dump($data);
This will produce an object, with keys as properties. An object is not valid to be passed to foreach unless it implements Traversable.
What you need to do is:
$data = json_decode($j,true);
This will make objects be associative arrays instead, which are compatible with foreach and most likely the rest of your code.
When there's a definite number of children, you can use nested foreach-loops:
$json = '[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"}, {"name":"manual","def":"somestring"}]';
$decode = json_decode($json, true);
foreach ($decode as $k1 => $v1) {
foreach ($v1 as $k2 => $v2) {
echo "$k2: $v2, ";
}
echo "<br>";
}
It will output this:
name: Ta, def: somestring, <br>
name: WSCall, def: somestring, <br>
name: manual, def: somestring, <br>
$j= '[{"name":"Ta","def":"somestring"},{"name":"WSCall","def":"somestring"},{"name":"manual","def":"somestring"}]';
$data = json_decode($j,true);
foreach($data as $key=>$val){
foreach($val as $k=>$v){
echo "Key :".$k." Value :".$v."<br />";
}
}

Categories