php json to load jquery datagrid - php

I've this php code that passes results to a jquery getJSON function that doesn't work properly.
here is my code:
$data["total"]=mysql_num_rows($s);
while ($r = mysql_fetch_array($s))
{
$ris_sql["utente"]=tv($r["utente"]);
$ris_sql["contratto"]=tv($r["contratto"]);
$ris_sql["login"]=tv($r["login"]);
$ris_sql["piattaforma"]=tv($r["piattaforma"]);
$ris_sql["azione"]=tv(format_valid($r["azione"]));
$ris_sql["data"]=tv($r["data"]);
$ris_sql["note"]=tv(str_replace("<br>","",$r["note"]));
$riga[]=$ris_sql;
}
$data["rows"]=json_encode($riga, JSON_FORCE_OBJECT);
echo json_encode($data);
If I try to use firebug I see that my rows elements in JSON result like a string instead a series of objects, what is wrong in my code??

You are double-encoding the $riga JSON. Don't separately encode the $riga part prior to encoding the rest of the $data array you're sending back to the browser.
// Instead of
$data["rows"] = json_encode($riga, JSON_FORCE_OBJECT);
// This double-encodes the contents of $data before outputting back to the browser or ajax call
echo json_encode($data);
// Just do:
echo json_encode($data, JSON_FORCE_OBJECT);
If the format isn't what you expect, instead you can cast $riga from an array to an object and then encode the whole thing without JSON_FORCE_OBJECT.
// Cast $riga from an assoc array to an instance of stdClass
$data['rows'] = (object)$riga;
// And then JSON encode the whole $data
echo json_encode($data);

Related

Get values from JSON array using PHP

I run the following PHP after I submit a form and get the output shown below:
$data = json_encode($_POST);
// output
{"First_Name":"Fred"}
How do I use PHP to just display the value 'Fred'?
I tried echo $data['First_Name']; but this is blank.
You no need to encode your incoming $_POST data.
Just say:
echo $_POST['First_Name'];
If you get a json data, decode it into an array:
$data = '{"First_Name":"Fred"}';
$decoded = json_decode($data, true);
echo $decoded['First_name'];
First of all, don't know why you use json_encode on PHP Array, and try to access it like it's an array - because after json_encode it's a string.
You have to use json_decode($data, true) and then you can access it like $data['First_Name'] or try to access it directly without json_encode() by $_POST['First_Name']
The json_decode() function is used to decode or convert a JSON object to a PHP object.And try to put the object to decode in another variable to avoid errors
<?php
$obj = '{"First_Name":"Fred"}';
$data = json_decode($obj);
echo ($data->First_Name);
?>

php - convert mysql data into json object

I using codeigniter. I want to retrive data from database and convert it into JSON object not JSON array.I'm using following code
public function json()
{
$content = $this->db->get('todolist'); //todolist table name
$data = $content->result_array();
echo json_encode($data);
}
Above code is converting database into JSON array.
Output
[{"todo_id":"1","todo_content":"Homework","date":"2016-05-05","iscomplete":null,"imagelink":"Lighthouse.jpg"},{"todo_id":"2","todo_content":"exam","date":"2015-04-21","iscomplete":null,"imagelink":"Desert.jpg"},{"todo_id":"3","todo_content":"Lab report","date":"2014-08-29","iscomplete":null,"imagelink":"FB_IMG_14700753538617403.jpg"}]
What will be best way to convert it into JSON object
Sangam try to understand the concept, check the following line:
$data = $content->result_array(); // $data is an array
echo json_encode($data); // here you are converting it into an json object
Your $data array contains more than one index in it that's why the json object is having multiple {} inside [];
You want to json_encode($data, JSON_FORCE_OBJECT).
The JSON_FORCE_OBJECT flag, as the name implies, forces the json output to be an object, even when it otherwise would normally be represented as an array.
Refer: PHP Array to Json Object
You can use JSON_FORCE_OBJECT see the example below.
echo json_encode($data, JSON_FORCE_OBJECT);
Assuming you're only getting one row back from your query.
change
echo json_encode($data);
to
echo json_encode($data[0]);

How to insert an array in a json object in PHP

I have a string on my databas, that I'm trying to insert into a json object as an Array, not a string..:
$arrayInString = "[2,3,5,5,6]"; // this comes from the database
$jsonObject = array('numbers' => $arrayInString);
$json = json_encode($jsonObject, JSON_UNESCAPED_SLASHES);
echo $json;
When I execute this.. my Json object is..
numbers: "[2,3,5,5,6]";
and not
numbers: [2,3,5,5,6];
Like I originally wanted.. can't get this to work, can anyone help?
Like was said you need to decode the passed data from the database and then build your array output. Something like this:
$arrayInString = "[2,3,5,5,6]"; // this comes from the database
// decode the JSON from the database as we build the array that will be converted back to json
$jsonObject = array('numbers' => json_decode($arrayInString));
echo json_encode($jsonObject, JSON_UNESCAPED_SLASHES);
The slightly modified code above outputs:
{"numbers":[2,3,5,5,6]}
You need to json_decode your $arrayInString variable before you add it to the associative array.

Passing PHP array to Javascript via GET

I'm trying to pass an array to Javascript after it has sent a GET request to PHP.
Sending and retrieving the data works perfectly but I couldn't find anything about passing the data back as an array like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo $result_as_javascript_array;
?>
<script>
$('result').innerHTML = httpGet.responseText
</script>
Convert the data you get from MySQL to JSON. First build a "normal" PHP array as you would normally do, then pass it through the json_encode() function and return it.
On the client you have to parse the JSON string into a JS array or object. See this SO question for details: Parse JSON in JavaScript?
And please use something else for accessing MySQL. The extension you are using is basically obsolete: http://si1.php.net/manual/en/faq.databases.php#faq.databases.mysql.deprecated
you should use json_encode, which works fine, when directly assigning output to a javascript variable
<?php
$result = mysql_query('blablabla');
//first convert result to an associative array
$myarray = array();
while($fetch = mysql_fetch_assoc($result)){
$myarray[]=$fetch;
}
//converting $result to an array?
echo "<script>";
echo "var myArray = ".json_encode($myarray).";";
echo "</script>";
?>
<script>
//now you can use myArray global javascript variable
$('result').innerHTML = myArray.join(",");
</script>
You are looking for json_encode.
Use json_encode like this:
<?php
$result = mysql_query('blablabla');
//converting $result to an array?
echo json_encode($result);
?>
You probably won't want to put the response text right into the innerHTML of your element though unless you are wanting to display the json text in the element.
$arr = array();
while ($row = mysql_fetch_array($result)) {
$arr[] = $row;
}
echo $arr;
However, mysql_ is deprecated, use mysqli instead.
If you want to pass it as JSON, use this:
echo json_encode($arr);

Encoding a SELECT statement as JSON, iOS issues

I am trying to JSON encode the results of my SQL SELECT statement using PHP and am unsure if I am formatting my array correctly before encoding.
My PHP code is:
$stmt = $this->db->prepare('SELECT CLINIC.clinic_name AS "clinicname" FROM CLINIC ORDER BY CLINIC.clinic_name ASC');
$stmt->execute();
$stmt->bind_result($clinicname);
$test = array();
while($stmt->fetch()){
$tempArray = array('clinicname' => $clinicname);
array_push($test, $tempArray);
}
$stmt->close();
// Return clinics, encoded with JSON
header('Content-type: application/json');
$json = json_encode($test);
echo $json;
The result of this array creation and encoding is:
[{"clinicname":"Bangor"},{"clinicname":"Belfast"},{"clinicname":"Crumlin"},{"clinicname":"Londonderry"}]
So I have an array of arrays.
Will this be okay for sending as JSON? All the examples I see seem to be a single array. Am I correct so far?
And then, regarding iOS, will the received object be a NSDictionary or an NSArray?
Any help or feedback on the above would be greatly received.
Matt.
Yes, your JSON is properly formatted. Next time you can use a JSON validator to check.
Also, some details on json_encoding.
A [] represents an array and {} represents an object.
In iOS, if this is the result from an http request, it will be of type NSString, and then need to be parsed by something like:
http://developer.apple.com/library/ios/#documentation/Foundation/Reference/NSJSONSerialization_Class/Reference/Reference.html
which then converts it to NSArray, NSDictionary NSString, etc.
Yes, you can send an array of arrays, and you can acces like the follow way:
$response = json_decode($response,true);
foreach ($response as $resp)
{
echo "<br>";
print_r($resp);
}
json example:
[{"id":"38","first_name":"prueba","second_name":"example","first_surname":"prueba","second_surname":"GONZALEZ","email":"x#x.net","network_login":"x.x","pos_name":"x x","position":"1","active":"1"},{"vhur":"292","first_name":"c","second_name":"example","first_surname":"example","second_surname":null,"email":"example#example.com","network_login":"example.example","pos_name":"example example","position":"2","active":"1"}]

Categories