Get JSON format from MySql to javascript using PHP - javascript
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.
Related
Converting PHP array to JS array in PHP itself
Hey just a small thing I am stuck on. I do have the structure ready for the JS array but I need to assign it to a variable like var data ={ Php array } Here is the structure of my php array: https://imgur.com/a/LPbCqEu This is just a part of the array. My code looks like this: $csvfile = 'Property_CSVTruncated.csv'; $handle = fopen($csvfile, 'r'); $jsData = array( 'properties' =>array() ); $header = NULL; while (($row = fgetcsv($handle, 1000000, ',')) !== FALSE) { $i = 0; if (!$header) { $header = $row; } else { $data = array_combine($header, $row); $fields = array( '_id' => $data['C4021040'], 'index' => $i, 'price' => $data['123'], 'picture' => "https://ihatetomatoes.net/demos/_rw/01-real-estate/tn_property01.jpg", 'city' => "Calgary", 'MLS# ' => $data['C4021040'], 'address' => $data['6 ASPEN RIDGE LN SW'], 'latitude' => $data['51.045681'], 'longitude' => $data['-114.191544'], 'Bed' => $data['123'], 'Bath' => $data['123'], 'capSpaces' => $data['T3H 5H9'], ); array_push($jsData['properties'], $fields); } $i++; } fclose($handle); $str = "const data = "; print($str); header('Content-type: application/json'); json_encode($jsData, JSON_NUMERIC_CHECK); $jsonFile = fopen('csvTojs.js', 'w'); fwrite($jsonFile, json_encode($jsData)); fclose($jsonFile); So basically I need that string 'var data = ' and then prints the array. Anyway to do that in php itself? Thanks
in server, echo json_encode($phpArray) and exit; in callback of ajax or init js variable, parse json to array with JSON.parse('jsonString');
Use json_encode() <script> var data = <?php echo json_encode($jsData, JSON_PRETTY_PRINT); ?> </script> Or in your case: header('Content-Type: application/json'); echo json_encode($jsData); exit;
Convert PHP array to JS array (ISO 8859-1 characters)
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...
How can i add Dynamic Json data into a Mysql Database.
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);
PHP json to google chart api
I'm having trouble parsing my php generated json array to a google chart. I have included Jquery, but some how i can't figure out how to parse my json data. I run a MySQL query to retrieve data from the database. Then i encode the query result with php json_encode. I use ajax to get the json data from my php file. getData.php: <?php function get_meta_values( $key, $type = 'workout', $status = 'publish' ) { global $wpdb; $user_ID = get_current_user_id(); if ( empty( $key ) ) return; $r = $wpdb->get_results( $wpdb->prepare( " SELECT pm.meta_value, p.post_date FROM {$wpdb->postmeta} pm LEFT JOIN {$wpdb->posts} p ON p.ID = pm.post_id INNER JOIN $wpdb->term_relationships ON (p.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) WHERE pm.meta_key = '%s' AND $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->term_taxonomy.term_id IN (4) AND p.post_status = '%s' AND p.post_type = '%s' AND p.post_author = $user_ID ORDER BY pm.meta_value DESC ", $key, $status, $type)); if ( $r ) { $user_ids = wp_list_pluck( $r, 'post_date' ); cache_users( $user_ids ); } return $r; } $workout_history = get_meta_values( '1_rep', 'workout' ); echo json_encode($workout_history); ?> The page that holds the chart: <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> google.load("visualization", "1", { packages: ["corechart"] }); google.setOnLoadCallback(drawChart); function drawChart() { var jsonData = $.ajax({ url: "http://localhost:41175/wp-content/themes/wordpress-bootstrap-master/getData.php", dataType: "json", async: false }).responseText; var obj = window.JSON.stringify(jsonData); var data = google.visualization.arrayToDataTable(obj); var options = { title: 'Test' }; var chart = new google.visualization.LineChart( document.getElementById('chart_div')); chart.draw(data, options); } </script> When i try to echo my json file it looks like this: [ { "meta_value":"999", "post_date":"2014-04-12 18:21:51" }, { "meta_value":"1", "post_date":"2014-04-12 18:58:20" } ] Any suggestions to what i am doing wrong?
https://developers.google.com/chart/interactive/docs/reference#google.visualization.arraytodatatable Seems that your JSON dataset is incorrect for use with that method. It should be (in javascript): var data = [ ['metavalue', 'post_date'], ['999', '2014-04-12 18:21:51'], ['1', '2014-04-12 18:58:20'] ] which in JSON equals to: [["metavalue","post_date"],["999","2014-04-12 18:21:51"],["1","2014-04-12 18:58:20"]] As I have no clue where $workout_history is coming from I can't help you out with how get to that.
Your object graph is incorrect before you return $r do this: $results = array(); $result[] = array_values($r); return $result; alternatively you can build an your array of array like this: $results = array(); $result[] = array($r['message_type'], $r['post_date']); return $result;
AJAX POST request is failing
Apologies for the generic title. Essentially, when the script runs 'error' is alerted as per the jQuery below. I have a feeling this is being caused by the structuring of my JSON, but I'm not sure how I should change it. The general idea is that there are several individual items, each with their own attributes: product_url, shop_name, photo_url, was_price and now_price. Here's my AJAX request: $.ajax( { url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1', type : 'POST', data : 'data', dataType : 'json', success : function (result) { var result = result['product_url']; $('#container').append(result); }, error : function () { alert("error"); } }) Here's the PHP that generates the JSON: <?php function scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country) { header("Access-Control-Allow-Origin: *"); $html = file_get_contents($list_url); $doc = new DOMDocument(); libxml_use_internal_errors(TRUE); if(!empty($html)) { $doc->loadHTML($html); libxml_clear_errors(); // remove errors for yucky html $xpath = new DOMXPath($doc); /* FIND LINK TO PRODUCT PAGE */ $products = array(); $row = $xpath->query($product_location); /* Create an array containing products */ if ($row->length > 0) { foreach ($row as $location) { $product_urls[] = $product_url_root . $location->getAttribute('href'); } } $imgs = $xpath->query($photo_location); /* Create an array containing the image links */ if ($imgs->length > 0) { foreach ($imgs as $img) { $photo_url[] = $photo_url_root . $img->getAttribute('src'); } } $was = $xpath->query($was_price_location); /* Create an array containing the was price */ if ($was->length > 0) { foreach ($was as $price) { $stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue); $was_price[] = "£".$stripped; } } $now = $xpath->query($now_price_location); /* Create an array containing the sale price */ if ($now->length > 0) { foreach ($now as $price) { $stripped = preg_replace("/[^0-9,.]/", "", $price->nodeValue); $now_price[] = "£".$stripped; } } $result = array(); /* Create an associative array containing all the above values */ foreach ($product_urls as $i => $product_url) { $result = array( 'product_url' => $product_url, 'shop_name' => $shop_name, 'photo_url' => $photo_url[$i], 'was_price' => $was_price[$i], 'now_price' => $now_price[$i] ); echo json_encode($result); } } else { echo "this is empty"; } } /* CONNECT TO DATABASE */ $dbhost = "xxx"; $dbname = "xxx"; $dbuser = "xxx"; $dbpass = "xxx"; $con = mysqli_connect("$dbhost", "$dbuser", "$dbpass", "$dbname"); if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } $id = $_GET['id']; /* GET FIELDS FROM DATABASE */ $result = mysqli_query($con, "SELECT * FROM scrape WHERE id = '$id'"); while($row = mysqli_fetch_array($result)) { $list_url = $row['list_url']; $shop_name = $row['shop_name']; $photo_location = $row['photo_location']; $photo_url_root = $row['photo_url_root']; $product_location = $row['product_location']; $product_url_root = $row['product_url_root']; $was_price_location = $row['was_price_location']; $now_price_location = $row['now_price_location']; $gender = $row['gender']; $country = $row['country']; } scrape($list_url, $shop_name, $photo_location, $photo_url_root, $product_location, $product_url_root, $was_price_location, $now_price_location, $gender, $country); mysqli_close($con); ?> The script works fine with this much simpler JSON: {"ajax":"Hello world!","advert":null}
You are looping over an array and generating a JSON text each time you go around it. If you concatenate two (or more) JSON texts, you do not have valid JSON. Build a data structure inside the loop. json_encode that data structure after the loop.
If i have to guess you are echoing multiple json strings which is invalid. Here is how it should work: $result = array(); /* Create an associative array containing all the above values */ foreach ($product_urls as $i => $product_url) { // Append value to array $result[] = array( 'product_url' => $product_url, 'shop_name' => $shop_name, 'photo_url' => $photo_url[$i], 'was_price' => $was_price[$i], 'now_price' => $now_price[$i] ); } echo json_encode($result); In this example I am echoing the final results only once.
You are sending post request but not sending post data using data $.ajax( { url : 'http://www.comfyshoulderrest.com/shopaholic/rss/asos_f_uk.php?id=1', type : 'POST', data : {anything:"anything"}, // this line is mistaken dataType : 'json', success : function (result) { var result = result['product_url']; $('#container').append(result); }, error : function () { alert("error"); } })