i'm tying to do an ajax get call
i can successfully console.log the result without putting the datatype json in the ajax
dataType: 'json',
when i console.log without it i get
{"id":"1","post_id":"748037498494861","post_title":"laptop","image1":"team217.jpg","price":"1234"}{"id":"2","post_id":"740811329642473","post_title":"remote control car","image1":"team522.jpg","price":"50"}{"id":"4","post_id":"316194613858174","post_title":"Ipad 3","image1":"team523.jpg","price":"400"}
however i cant display the json data
if i put
dataType: 'json',
my
console.log
is empty
i dont understand where the problem is
$(document).ready(function(){
var username = $("#usernameinfo").text();
$.ajax({
type:"GET",
url: "<?= base_url()?>"+"account/listings/more_user_ads",
data: {"username":username,"pid":"<?=$this->input->get('pid')?>"},
success: function(res){
console.log(res);
}
});
});
php
function more_user_ads(){
$post_id = $this->input->get('pid');
$username = $this->input->get('username');
$query = $this->get_where_custom('username', $username);
if($query->num_rows()>0){
foreach($query->result() as $row){
if($post_id != $row->post_id){
$result = array(
'id'=> $row->id,
'post_id'=> $row->post_id,
'post_title'=> $row->post_title,
'image1'=> $row->image1,
'price'=> $row->price,
'price'=> $row->price,
);
$res = json_encode($result);
echo $res;
Add each row to the $result array then echo the json_encode once.
public function more_user_ads()
{
$post_id = $this->input->get('pid');
$username = $this->input->get('username');
$query = $this->get_where_custom('username', $username);
$result = []; //so we have something if there are no rows
if($query->num_rows() > 0)
{
foreach($query->result() as $row)
{
if($post_id != $row->post_id)
{
$result[] = array(
'id' => $row->id,
'post_id' => $row->post_id,
'post_title' => $row->post_title,
'image1' => $row->image1,
'price' => $row->price,
'price' => $row->price,
);
}
}
}
echo json_encode($result);
}
Actually, you can shorten this a bit by using $query->result_array(); because you won't have to convert an object to an array.
public function more_user_ads()
{
$post_id = $this->input->get('pid');
$username = $this->input->get('username');
$query = $this->get_where_custom('username', $username);
$result = []; //so we have something if there are no rows
if($query->num_rows() > 0)
{
$rows = $query->result_array();
foreach($rows as $row)
{
if($post_id != $row['post_id'])
{
$result[] = $row;
}
}
}
echo json_encode($result);
}
I can't get it to work despite all the sources. I try the following :
<?php
$list_array = array();
foreach ($this->resultatTypeMail as $mailType) {
$nom = $mailType->getNom();
$objet = $mailType->getObjet();
$list_array[] = array(
'Name' => $nom,
'Object' => $objet,
);
echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
?>
<script type="text/javascript">
var js_array = [<?php echo json_encode( $list_array ); ?>];
alert(js_array[0]); // This returns undefined
</script>
I get satisfying results on $nom and $objet when I alert them.
Problem :
js_array[0] returns undefined
Note that I'm not in UTF-8. I'm not sure it's relevant though.
EDIT : A big picture of my goal is to get an array of custom php objet to be usable in JS.
Just remove the [] from var js_array = line and it will work:
wrong:
var js_array = [<?php echo json_encode( array_values($list_array) ); ?>];
right:
var js_array = <?php echo json_encode( array_values($list_array) ); ?>;
Working code:
<?php
class MailType {
function __construct($n, $o) {
$this->nom = $n;
$this->objet = $o;
}
private $nom;
private $objet;
public function getNom() {
return $this->nom;
}
public function getObjet() {
return $this->objet;
}
}
$list_array = array();
$resultatTypeMail = array(new MailType('John', 'obj1'), new MailType('Mary', 'obj2'));
foreach ($resultatTypeMail as $mailType) {
$nom = $mailType->getNom();
$objet = $mailType->getObjet();
$list_array[] = array(
'Name' => $nom,
'Object' => $objet,
);
//echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
//echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
?>
<script type="text/javascript">
var js_array = <?php echo json_encode( $list_array ) ?>;
alert(js_array[0].Name); // This returns John
</script>
You can see it running here: http://phpfiddle.org/main/code/5xei-ybpn
(press F9 or click on 'Run - F9' to Run)
In PHP an array that has string keys gets converted to an object when parsed with json_encode.
You could either use array_keys to force the creation of an array, or use the object notation in your javascript
<?php
$list_array = array();
foreach ($this->resultatTypeMail as $mailType) {
$nom = $mailType->getNom();
$objet = $mailType->getObjet();
$list_array[] = array(
'Name' => $nom,
'Object' => $objet,
);
echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
<script type="text/javascript">
var js_array = [<?php echo json_encode( array_values($list_array) ); ?>];
alert(js_array[0]);
</script>
Or
<?php
$list_array = array();
foreach ($this->resultatTypeMail as $mailType) {
$nom = $mailType->getNom();
$objet = $mailType->getObjet();
$list_array[] = array(
'Name' => $nom,
'Object' => $objet,
);
echo "<script type='text/javascript'>alert('$nom');</script>"; // this is OK
echo "<script type='text/javascript'>alert('$objet');</script>"; // this is OK
}
<script type="text/javascript">
var js_array = [<?php echo json_encode( array_values($list_array) ); ?>];
alert(js_array.Name);
</script>
I think you have multiple issues: you're missing the ; after the json_encode() line (which is not actually required); you're surrounding the result of json_encode() with brackets (which should work but I expect it's not what you want); and the most important, you're missing the closing PHP ?> tag before printing the JS...
This works for me:
<?php
// your PHP code here...
?>
<script type="text/javascript">
var js_array = <?php echo json_encode($list_array); ?>;
alert(js_array[0]); // This works for me!
</script>
It looks like the issue may be in the encoding as you say - it seems that json_encode only works with UTF-8! From the json_encode() docs:
All string data must be UTF-8 encoded.
So I think you'll have to convert your strings to UTF-8 before putting them into the array, something like:
$list_array[] = array(
'Name' => utf8_encode($nom),
'Object' => utf8_encode($objet),
);
I think just that should work - otherwise you can try this from the comments in the same json_encode() docs; or this other question to get more ideas...
i want to get the json format from my SQL database using PHP
here is a capture of mySql database
data.php
<?php include("include/connexion.php");
$requete = "SELECT * from statistika";
$resultat = mysql_query( $requete ) or die( mysql_error() );
$rows = array();
$total_vue = 0;
here is the php code to get the data
while( $data = mysql_fetch_assoc( $resultat ) ) {
$total_vue+=$data['temps'];
$rows[] = array(
"date" => strtotime( $data['date']) * 1000,
"value" => $data[ 'temps' ]
);
}
?>
json_encode.php
<?php
include("data.php");
echo json_encode($rows);
?>
The content of json_encode is valid and i get the json format successfully
[{"date":1439769600000,"value":"5"},{"date":1439787600000,"value":"12"},{"date":1439806631000,"value":"8"},{"date":1439821320000,"value":"18"},{"date":1439919642000,"value":"6"},{"date":1439889752000,"value":"2"},{"date":1439893260000,"value":"20"},{"date":1439906400000,"value":"9"},{"date":1429308000000,"value":"15"},{"date":1421535600000,"value":"12"},{"date":1413583200000,"value":"18"},{"date":1405634400000,"value":"6"},{"date":1439828640000,"value":"14"},{"date":1439935200000,"value":"19"},{"date":1439863200000,"value":"12"},{"date":1439884800000,"value":"18"},{"date":1439917200000,"value":"26"},{"date":1439920800000,"value":"4"},{"date":1439904320000,"value":"0"},{"date":1439907420000,"value":"1"},{"date":1439907428000,"value":"1"},{"date":1439907434000,"value":"3"},{"date":1439907437000,"value":"1"},{"date":1439907447000,"value":"8"},{"date":1439907452000,"value":"3"},{"date":1439907459000,"value":"5"},{"date":1439907469000,"value":"8"},{"date":1439907482000,"value":"10"},{"date":1439907507000,"value":"21"},{"date":1439907510000,"value":"1"},{"date":1439907519000,"value":"7"},{"date":1439907526000,"value":"5"},{"date":1439907547000,"value":"18"},{"date":1439907557000,"value":"8"},{"date":1439907560000,"value":"1"},{"date":1439907576000,"value":"3"},{"date":1439907581000,"value":"3"},{"date":1418857200000,"value":"300"},{"date":1426633200000,"value":"450"},{"date":1434578400000,"value":"500"},{"date":1424214000000,"value":"600"}]
Now i want to pass the JSON format to javascript , i am using this code
var foo = {};
foo.toString = function () { return <?php echo json_encode($rows);?> };
document.write(foo.toString);
the problem is that when printing foo.toString i get this
function () { return [{"date":1439769600000,"value":"5"},{"date":1439787600000,"value":"12"},{"date":1439806631000,"value":"8"},{"date":1439821320000,"value":"18"},{"date":1439919642000,"value":"6"},{"date":1439889752000,"value":"2"},{"date":1439893260000,"value":"20"},{"date":1439906400000,"value":"9"},{"date":1429308000000,"value":"15"},{"date":1421535600000,"value":"12"},{"date":1413583200000,"value":"18"},{"date":1405634400000,"value":"6"},{"date":1439828640000,"value":"14"},{"date":1439935200000,"value":"19"},{"date":1439863200000,"value":"12"},{"date":1439884800000,"value":"18"},{"date":1439917200000,"value":"26"},{"date":1439920800000,"value":"4"},{"date":1439904320000,"value":"0"},{"date":1439907420000,"value":"1"},{"date":1439907428000,"value":"1"},{"date":1439907434000,"value":"3"},{"date":1439907437000,"value":"1"},{"date":1439907447000,"value":"8"},{"date":1439907452000,"value":"3"},{"date":1439907459000,"value":"5"},{"date":1439907469000,"value":"8"},{"date":1439907482000,"value":"10"},{"date":1439907507000,"value":"21"},{"date":1439907510000,"value":"1"},{"date":1439907519000,"value":"7"},{"date":1439907526000,"value":"5"},{"date":1439907547000,"value":"18"},{"date":1439907557000,"value":"8"},{"date":1439907560000,"value":"1"},{"date":1439907576000,"value":"3"},{"date":1439907581000,"value":"3"},{"date":1418857200000,"value":"300"},{"date":1426633200000,"value":"450"},{"date":1434578400000,"value":"500"},{"date":1424214000000,"value":"600"}]
i don't want function () { return to appear in the output !!!
Any hints ?
thanks .
Change this line in your JS code
From
foo.toString = function () { return <?php echo json_encode($rows);?> };
To
foo.toString = '<?php echo json_encode($rows);?>';
var foo = {};
foo.toString = function () { return <?php echo json_encode($rows);?> };
document.write(foo());
You are creating foo as function so call like this you will get only json.
How can i add JSON Data into a Database? i have a script there is generating automatic updated JSON Data. i read in a book that i should use a methode called
JSON_decode
I Think i should have to do something like, put The value into The tables for each value. Then try to use The methode JSON_decode and then make a loop foreach. but i am not sure about this. what is the best way, and can you tell me what to do in my case or maby show a example?
Here is the data located:
http://csgo.nssgaming.com/api.php
The current script:
<?php
require_once ('simple_html_dom.php');
$html = #file_get_html('http://csgolounge.com/');
$output = array();
if(!$html) exit(json_encode(array("error" => "Unable to connect to CSGOLounge")));
// Source: http://php.net/manual/en/function.strip-tags.php#86964
function strip_tags_content($text, $tags = '', $invert = FALSE) {
preg_match_all('/<(.+?)[\s]*\/?[\s]*>/si', trim($tags), $tags);
$tags = array_unique($tags[1]);
if(is_array($tags) AND count($tags) > 0) {
if($invert == FALSE)
return preg_replace('#<(?!(?:'. implode('|', $tags) .')\b)(\w+)\b.*?>.*?</\1>#si', '', $text);
else
return preg_replace('#<('. implode('|', $tags) .')\b.*?>.*?</\1>#si', '', $text);
} elseif($invert == FALSE) {
return preg_replace('#<(\w+)\b.*?>.*?</\1>#si', '', $text);
}
return $text;
}
foreach($html->find('.matchmain') as $match) {
$when = $match->find('.whenm')[0];
$status = trim($when->find('span')[0]->plaintext) == "LIVE" ? true : false;
$event = $match->find('.eventm')[0]->plaintext;
$time = trim(strip_tags_content($when->innertext));
$id = substr($match->find('a')[0]->href, 8);
$additional = substr(trim($when->find('span')[$status ? 1 : 0]->plaintext), 4);
$result;
$output[$id]["live"] = $status;
$output[$id]["time"] = $time;
$output[$id]["event"] = $event;
foreach($match->find('.teamtext') as $key => $team) {
$output[$id]["teams"][$key] = array(
"name" => $team->find('b')[0]->plaintext,
"percent" => $team->find('i')[0]->plaintext
);
if(#$team->parent()->find('img')[0])
$result = array("status" => "won", "team" => $key);
}
if($additional)
$result = $additional;
if(isset($result))
$output[$id]["result"] = $result;
}
echo json_encode($output);
I am doing this little project. Everything seems working , but I want to make even better.
I have code
-Part1 -takes date from database and converts to JSON
<?php
$sth = mysql_query("select Value, Stats from table");
$rows = array();
$flag = true;
$table = array();
$table['cols'] = array(
array('label' => 'Stats', 'type' => 'string'),
array('label' => 'Value', 'type' => 'number')
);
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$temp = array();
$temp[] = array('v' => (string) $r['Stats']);
$temp[] = array('v' => (int) $r['Value']);
$rows[] = array('c' => $temp);
}
$table['rows'] = $rows;
$jsonTable = json_encode($table, JSON_NUMERIC_CHECK);
?>
-Part 2 Draws Google Bar chart and shows it on page
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable(<?php echo $jsonTable; ?>);
var options = {
legend: {position: 'none'},
bar: {groupWidth: "85%"},
colors:['#4A9218'],
hAxis: {viewWindowMode: 'explicit'},
} };
var chart = new google.visualization.BarChart(document.getElementById('charts_div'));
chart.draw(data, options);
}
</script>
<div class='data' id="charts_div" style="width:100%; height:200px"></div>
-My Qyestion
How to convert (combine) Part2 code to php. I tried echo around lines, but unsuccesfully
I want to assign Part2 as Php variable $Graph1 and then echo $graph1 on page, because It works better with my other code, so its consistent.
So I would like something like:
<?php
Part1
?>
<?php
$graph1=."<script>...</script>"
$graph = "<div class='data'><ul>" . $graph1 . "</ul></div>
echo $graph
?>
Why don't you just add it after the ?> ?
In PHP you can include HTML like this
<?php
// My PHP Code
echo "test";
?>
<H1>My Title in HTML</H1>
<script> ... </script>
<?php
echo "test2";
?>
You can also include PHP into HTML
<script> var a = "<?php echo $somevariable; ?>"</script>
You can also wrap your HTML code into a PHP variable care about the ". You will need to escape it or us single quote instead:
<?php
$myHTML = "<script> window.location=\"mylocation.com\";</script>";
$myHTML = "<script> window.location= 'mylocation.com' ;</script>";
...
echo $myHTML;
?>