i have this code :
$wage = array();
foreach ($result3 as $row3) {
$wage[] = '[' . floatval($row3['age']) . ',' . floatval($row3['point']) .']';
}
if ($userid == 0 ) {
$age= "";
} else {
$age = implode(',', $wage).",";
}
echo json_encode("var2"=>$myvar ,"var3"=>$age)); // i didnt write var2 because is same as var3
the above will outputs something like [4,2.3][5,6],[1.7,5],
and in javascript im receiving this value outputed above via ajax which has name var3.
dataType: 'json' ,
success: function(response){
var age = response['var3'] ;
.....
so the question is how can i parseFloat this variable age ?
EDIT .
if i alert the json like that
alert (response);
i get [object Object] // make attention to small o and big O
EDIT2 .
used consol log
and i get this
{"var2":"[2,5],[3.5,5],[6.5,6.5],[8,7],","var3":"[2,46],[3.5,61],[6.5,70],[8,71],","var4":"[2,32],[3.5,41],[6.5,42],[8,43],","var5":"[46,5],[61,5],[70,6.5],[71,7],"}
this returned values i want to parseFloat them as you see they are like strings between two quotes
This is incorrect:
$wage[] = '[' . floatval($row3['age']) . ',' . floatval($row3['point']) .']';
You're building a string, which coincidentally happens to LOOK like a javascript array definition, but it's still just a string. When this gets json_encoded, it'll come out as
"[...,...]"
^-- ^-- string
You need to build NATIVE data structures at all stages while in PHP, e.g.
$wage[] = array(floatval($row3['age']), floatval($row3['point']));
and not this mish-mash of native AND "json-like" strings. json_encode() converts NATIVE datatypes of the equivalent Javascript types. Since your own floatval business is producing a string, you'll get a json-encoded string, not an array.
You are getting this all wrong. You do not need to do this;
foreach ($result3 as $row3) {
$wage[] = '[' . floatval($row3['age']) . ',' . floatval($row3['point']) .']';
}
Perhaps what you want is;
foreach ($result3 as $i => $row3) {
$newRow = $row3;
$newRow['age'] = intval($row3['age']);
$newRow['point'] = floatval($row3['point']);
$result3[$i] = $newRow;
}
And then do this;
// Create JSON data, assuming that $result3 is an array
$jsonData = json_encode($result3);
// This will give you a JSON string, output this and finish to ensure it IS the only thing output
echo $jsonData;
die;
Now in your javascript, open the development console in what ever browser your using and use the following code in javascript
console.log(response)
This will output the whole response variable to the console and enable you to debug how to get specific data out of the response var.
Hope that helps.
Related
i am using dataTables to display data from a MySQL database by using PHP, Ajax, and jQuery.
The data i am showing are numbers and everything works fine.
Here is my php script
require_once '../core/init4ajax.php';
$loteria=$_POST['loteria'];
$lotto = new Lotto();
$ultimos_resultados=$lotto->last_results($loteria,20);
function objectToArray($d)
{
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
return array_map(__FUNCTION__, $d);
} else {
// Return array
return $d;
}
}
$new_array = objectToArray($ultimos_resultados);
$result = array();
echo '[';
foreach ($new_array as $new_array2) {
echo '[';
foreach ($new_array2 AS $value){
/********The following piece of code is used to add a leading zero to single digit numbers********/
/*if (1 == strlen($value)) {
$zero=0;
$value = $zero.$value;
}*/
echo $value;
if($value!==end($new_array2)){ //referencias: http://stackoverflow.com/a/8780881/1883256
echo',';
}
}
echo ']';//referencias: http://www.mydigitallife.info/how-to-access-php-array-and-multidimensional-nested-arrays-code-syntax/
if($new_array2!==end($new_array)){
echo ',';
}else{ echo '';}
}
echo ']';
Here is the output sample of the php script:
[[2740,3,9,21,27,46,48],[2741,3,4,13,22,27,29], ... ,[2757,32,34,35,36,50,55]]
And here is the ajax code.
$(document).ready(function() {
$.ajax({
url: "ajax/default_chart_numbers_table.php",
type: "post",
data: {loteria: 'melate'},
success : function (resp){
// would look something like ['val1','val2', 'etc']
var column_data = $.parseJSON(resp);
//alert(column_data);
// adding data to datatables
for (var j=0;j<=column_data.length-1;j++){
// adding each row with its column data
//iterating values to add leading zeros to single digits:
$('#dataTables-melate').dataTable().fnAddData(column_data[j]);
}
},
error: function(jqXHR, textStatus, ex) {
console.log(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
} );
I have realized that i want the single digit numbers to be lead by a zero, e.g. 4, should be shown as 04.
By adding the code in order to add a leading zero (this piece of code is already in my php code but commented):
if (1 == strlen($value)) {
$zero=0;
$value = $zero.$value;
}
Now the php code returns the array the way i want it:
[[2740,03,09,21,27,46,48],[2741,03,04,13,22,27,29], ... ,[2757,32,34,35,36,50,55]]
however, now from the ajax script i get the following error:
SyntaxError: JSON.parse: expected ',' or ']' after array element at line 1 column 9 of the JSON data
and the data is no longer displayed in the dataTables.
Why is this happening? How can i fix it?
I HAVE FIXED IT:
I just had to add double quotes to those single edit numbers:
if (1 == strlen($value)) {
$zero=0;
$value = '"'.$zero.$value.'"';
}
And that did the trick! ☺
It has nothing to do with the leading zeros. This is because you treat the output as JSON, which it is not. It is an array of arrays. The error is caused by the line :
var column_data = $.parseJSON(resp);
Try test the output / supposed JSON with http://jsonlint.com. Example how it could work :
var column_data = [
[2740,3,9,21,27,46,48],
[2741,3,4,13,22,27,29],
[2757,32,34,35,36,50,55]
];
var dataTable = $('#dataTables-melate').dataTable()
for (var j=0;j<=column_data.length-1;j++){
// adding each row with its column data
//iterating values to add leading zeros to single digits:
dataTable.fnAddData(column_data[j]);
}
see demo -> http://jsfiddle.net/jPLSf/
Adding a leading zero changes a javascript "number" to a "string". So JSON.parse returns an error expecting numbers (eg: 4) but instead sees a string (eg: "04").
In the picture below, you can see that I have ran two commands that try to parse a string into JSON. In the first command, the second item in the first array is 03 and outputs a SyntaxError. In the second command, The 03 was changed to 3 and now it parses properly.
I would recommend researching how to add data to the datatable without leading zeros in order for the table to show up properly and then change how the numbers are viewed/displayed
I would also recommend researching json_encode() to echo json from PHP.
I use json_encode() to echo json from PHP all the time to make sure I get the proper data output when making AJAX calls.
I'd appreciate any help I could get with this — I've been scouring stack overflow and couldn't find anything that directly related with what I'm trying to accomplish.
Issue: I'm trying to update a specific name/value pair in a JSON file, and I'm trying to do it by sending specific parameters through an AJAX call to a PHP file. Two of the parameters are the path (delineated with hyphens) to the name, and the value that I'm swapping in.
A small portion of the JSON:
{
"character" :
{
"name" : "Foo",
"species" : "Bar",
}
}
Using this JSON as an example, I'm trying to update a specific array value, such as:
$char['character']['name']
I'm passing a variable to the PHP file with the path information, such as:
updater.php?char=character-name&val=Newname
Is there a way to convert the string "character-name" (or any string for that matter with a particular delineation) to the path in an Array, like $char['character']['name']?
$array = explode("-", $_GET['char']);
$char=json_decode(....); //your json string
$char[$array[0]][$array[1]]=$_GET['val'];
To not only read the value at the specified path, but also update the json, I would suggest something like
<?php
function json_replace_path($json, $path, $newValue)
{
$json = json_decode($json);
$pathArray = explode('-', $path);
$currentElement = $json;
foreach ($pathArray as $part)
{
$currentElement = &$currentElement->$part;
}
$currentElement = $newValue;
return json_encode($json);
}
$json = '{"character":{"name":"Foo","species":"Bar","other":{"first_name":"Jeff","last_name":"Atwood"}}}';
echo json_replace_path($json, 'character-name', 'new name') . "\n";
echo json_replace_path($json, 'character-species', 'new species') . "\n";
echo json_replace_path($json, 'character-other-last_name', 'Bridges') . "\n";
Does not support JSON including arrays, though.
Something like that should work, I guess :
$a = explode("-", $_GET['char']);
$array = ...; //Your json array here
while (is_array($array) && count($a) > 0)
{
$array = $array[array_shift($a)];
}
Why not just use updater.php?character[name]=Newname? Then you can get it with:
echo $_GET['character']['name'];
Makes much more sense. Why concatenate things and then try and separate them into an array when you can just use an array from the start?
I have a loop that grabs DB values and creates an object. I want to echo a JSON object every time the loop is iterated through. As of now, I just get blank in my console. Also, those commented out printf statements work fine. Any help would be much appreciated!
AJAX call
$.ajax({
url:'ajax/ipGet.php',
type: 'GET',
dataType:'json',
success:function(response){
console.log(response);
}
});
PHP Data Generation
$infoArray = new Array();
while($row = mysqli_fetch_array($getIpQuery, MYSQLI_NUM)){
for($x=0;$x<count($row);$x++)
{
$getIpInfo = mysqli_query($dbcon,"SELECT * FROM ipInfo WHERE address='$row[$x]'");
$retrievedInfo = mysqli_fetch_array($getIpInfo,MYSQLI_NUM);
$ipInfo->ipAddress = $retrievedInfo[0];
$ipInfo->port = $retrievedInfo[1];
$ipInfo->status = getStatus($ipInfo->ipAddress, $ipInfo->port);
array_push($infoArray,$ipInfo);
}
}
echo json_encode($infoArray);
Thanks for any help!
~Carpetfizz
json must be a single self-contained entity. You're outputting MULTIPLE separate bits of JSON text, which is incorrect.
JSON encoding should be the very LAST thing you do, e.g.
while(...) {
$array[] = ....
}
echo json_encode($array);
Consider what you're doing from the client perspective... building an array of ipinfo, so you run the loop once and produce
{"ipAddress":"127.0.0.1","port":80,....}
But you're doing it multple times, so you end up with
{"ipAddress":"127.0.0.1","port":80,....}{"ipAddress":"127.0.0.1","port":80,....{"ipAddress":"127.0.0.1","port":80,....}
as your output, and now you've got illegal javascript. Remember that JSON text is essentialy the right-hand-side of a Javascript assignment operation, e.g.
var somevar = ...json_goes_here...;
So you're doing
var stuff = {...}{...}{...};
which is an outright syntax error, instead of
var stuff = [{...},{...},{...}];
which would be correct.
This question already has answers here:
JQuery string not parsing correctly in PHP
(2 answers)
Closed 9 years ago.
I was wondering, does anyone know how do I properly deserialize a string from a JQuery using PHP? The string that JQuery passes into my PHP file is this:
age_gender=1&age_gender=2&age_gender=3&age_gender=4&age_gender=5&age_gender=6
The values I need are the numbers after the equal signs (they are just dummy values that I used for testing).
EDIT: Actually, I am already using parse_str(). Here is my PHP code:
if(isset($_POST['age_gender'])) {
$formSerialized = $_POST['age_gender'];
$formData = array();
parse_str($formSerialized, $formData);
addRow($formData, $link);
}
function addRow($dataArray, $link) {
$age_group = $dataArray[0];
$populations = array(intval($dataArray[1]) + intval($dataArray[2]), intval($dataArray[1]), intval($dataArray[2]));
$percents = array(doubleval($dataArray[3]) + doubleval($dataArray[4]), doubleval($dataArray[3]), doubleval($dataArray[4]));
$m_per_100_f = doubleval($dataArray[6]);
$query = "INSERT INTO national_age_gender_demographics (age_group, both_pop, male_pop, female_pop, both_percent, male_percent, female_percent, males_per_100_females)
VALUES ('$age_group','$populations[0]','$populations[1]','$populations[2]','$percents[0]','$percents[1]','$percents[2]','$m_per_100_f')";
$result = mysqli_query($link,$query);
if(!$result) die( "Query: " . $query . "\nError:" . mysql_error() );
}
For some reason, I am getting a blank string for $age_group, and 0's for all other values. Could anyone help me here?
See parse_str()
Example:
parse_str('age_gender=1&age_gender=2&age_gender=3&age_gender=4&age_gender=5&age_gender=6', $output);
print_r($output);
Also if you want to get the querystring of the request you can get it with php using $_SERVER['QUERY_STRING']
parse_str()
is the function you are looking for.
You have two options to use with this:
parse_str($string) - this will actually create a variable for each key in the string.
parse_str($string,$arr) - this will populate $arr with an associative array containing all the key=>value pairs from the string.
The documentation gives some great code to demonstrate this behavior:
$str = "first=value&arr[]=foo+bar&arr[]=baz";
parse_str($str);
echo $first; // value
echo $arr[0]; // foo bar
echo $arr[1]; // baz
parse_str($str, $output);
echo $output['first']; // value
echo $output['arr'][0]; // foo bar
echo $output['arr'][1]; // baz
I have got my self confused on how to construct arrays correctly in PHP prior to my json encode to check them in javascript.
I'm trying to store an array of objects with their grid reference (x,y)
So i do this in php:
$get = mysql_query("SELECT x,y,sid FROM $table WHERE uid='1'") or die(mysql_error());
while($row = mysql_fetch_assoc($get)) {
$data[$row['x'].$row['y']] = $row['sid'];
}
//print_r($data);
$data = json_encode($data);
In javascript i then try to check if a object exists on a given co-ordinate so i try this:
for (i=0;i<tilesw;i++){ //horizontal
for (j=0;j<tilesh;j++){ // vertical
if(sdata[i.j]){
alert(sdata[i.j][sid]);
}
}
}
sdata is my array after json encode.
My json encode looks like this:
{"44":"0","21":"0"}
Problem is i get :
Uncaught SyntaxError: Unexpected token ] on the alert line.
Also is my approach correct or is there a better way to construct my array?
You have a JavaScript syntax error in your code. There is an extra ] on your alert() line.
alert(sdata[i.j][sid]]);
Should be
alert(sdata[i.j][sid]);
If you're actually trying to concatenate the values i and j you also need to be using + rather than ., so you would use i.toString()+j.toString() as the key rather than i.j.
Example of using this with two-dimensional arrays:
PHP
$arr = array();
while($row = mysql_fetch_assoc($get)) {
if(!isset($arr[$row['x']])) $arr[$row['x']] = array();
$arr[$row['x']][$row['y']] = $row['sid'];
}
$data = json_encode($arr);
JavaScript
for(var x in sdata) {
for(var y in sdata[x]) {
alert('Object found at coordinates ' + x + ',' + y + ' ' + sdata[x][y]);
}
}