How can i add Dynamic Json data into a Mysql Database. - javascript

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);

Related

Error parsing JSON file - Incorrect Object

I've replicated a graph script from one Wordpress installation to another
It operates using graph_nat and defs.php - Defs stores the DB details
I have not altered the script after migrating but now I'm getting JSON error
I've checked to ensure after object it's true
I'm struggling to figure out the bug, error reporting doesn't include the JSON error only false positives for PHP
<?php
include ('../wp-load.php');
include ('defs.php');
// we need this so that PHP does not complain about deprectaed functions
error_reporting( 0 );
// Connect to MySQL
// constants stored in defs.php
$db = mysqli_connect("localhost", DB_NAT_USER, DB_NAT_PASS, DB_NAT_NAME);
// get user id
$current_user = wp_get_current_user();
$current_user_id = $current_user->ID;
if ( $current_user_id == null || $current_user_id == 0) {
$message = 'User not authorized';
die( $message );
}
if ( !$db ) {
die( 'Could not connect to database' );
}
if (!isset($_GET['id'])) {
$message = 'Missing ID url parameter';
die( $message );
}
$id = $_GET['id'];
$practitionerId = $current_user_id;
$query = "SELECT results FROM submissions WHERE ID = ? AND practitionerId = ?";
$result = [];
if ($stmt = $db->prepare($query)) {
$stmt->bind_param('ss', $id, $practitionerId);
$stmt->execute();
$stmt->bind_result($results);
if ($stmt->fetch()) {
$result = $results;
}
$stmt->close();
}
// decode json from database
$json = json_decode($result, true);
$outputArray = [];
$healthIndex = 100;
if ($json) {
foreach($json as $key=>$val) {
$healthEvents = explode(", ", $val);
// filter out empty strings
$healthEventsFiltered = array_filter($healthEvents, function($value) {
if ($value == '') {
return false;
}
return true;
});
// points to decrease per event
$healthDecrease = (count($healthEventsFiltered))*2;
$healthIndex -= $healthDecrease;
if ($healthIndex<0) {
$healthIndex = 0;
}
// implode array to get description string
$arrayString = implode(",<br>", $healthEventsFiltered);
// age groups
$ageGroup = $key*5;
$ar = array("category" => "Age: " . $ageGroup, "column-1" => $healthIndex, "events" => $arrayString);
array_push($outputArray, $ar);
}
echo json_encode($outputArray, true);
} else {
$message = 'Could not decode JSON: ' . $result;
die( $message );
}
// Close the connection
mysqli_close( $db );
?>
Figured it out, I wasn't passing USER ID in url. It was undefined. I should go back to school

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;

json not displaying with dataType :'json'

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);
}

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");
}
})

I want to create advanced search using ajax codeigniter per categories

I am making a search function with codeigniter.
The search needs to show the search result per category, when I click the categories it will be show the real result (detail, with the image).
For the search I made a form:
Title:
Author:
Publisher:
Year Published
ISBN :
<btn submit>
if I submit it will show the URL like this:
http:readynew1.8/advancedsearch/search?advTitle=diktat&advAuthor=&advPublisher=&advYear=&advISBN=
===========================================
Search Result
==========================================
Book 6
Journal 4
The code is fine until here.
The problem is that when I click the category book I cant get the data that was sent from the input form.
If I use $this->input->get(); and send it as parameter to my function showdetails(Title,ISBN);
the parameter cant be null, and also I cant find any book with title that contains a comma,
so I think I need to get the input data with ajax with form.serialize but I still don't get the data from input text.
Can anyone help me?
code search controller that I get for categories
public function search()
{
$AssetTitle = $this->input->POST("advTitle");
$Author = $this->input->POST('advAuthor');
$Publisher = $this->input->POST('advPublisher');
$Year = $this->input->POST('advYear');
$ISBN = $this->input->POST('advISBN');
$result = $this->advanced_model->search_result();
$data['temp']=$this->advanced_model->getcountadvanced();
$data["CatId"]=$this->viewbook_model->getCategory();
$x=0;
if(count($result) > 0){
foreach($result AS $d)
{
$data['searchresult'][$x] = array(
'CategoryAssetName' => $d['CategoryAssetName'],
'CategoryAssetId' => $d['CategoryAssetId'],
'AssetTitle' => $d['Bibli'],
'Author' => $d['Bibli'],
'Publisher' => $d['PublisherId'],
'Year' => $Year,
'ISBN' => $ISBN
);
$x++;
}
}
else
{
$data['searchresult'] = array();
}
$page_content["page_title"] = "Advanced Search";
$page_content["title"] = "Advanced Search";
$page_content["icon_title"] = "search";
$menu_params["current_navigable"] = "AdvancedSearch";
$menu_params["sub_current_navigable"] = "";
$page_content["menu"] = $this->load->view("main_menu", $menu_params, true);
$page_content["content"] = $this->load->view("advancedsearch", $data, true);
$page_content["navmenu"] = $this->load->view("nav_menu",$data, true);
$this->load->view("template/main_template", $page_content);
}
my function to get details:
function test($CategoryAssetId="",$AssetTitle="",$Author="",$Publisher="",$Year="",$ISBN=""){
$data = $this->input->post();
echo $data;
$data["CatId"]=$this->viewbook_model->getCategory();
/*$AssetTitle = $this->input->GET('advTitle');
$Author = $this->input->GET('advAuthor');
$Publisher = $this->input->GET('advPublisher');
$Year = $this->input->GET('advYear');
$ISBN = $this->input->GET('advISBN');
*/
/*echo $AssetTitle.'<br />';
echo $Author.'<br />';
echo $Publisher.'<br />';
echo $Year.'<br />';
echo $ISBN.'<br />';*/
$AssetTitleEx = explode("-",$AssetTitle);
$AssetTitleIm = implode(" ",$AssetTitleEx);
//echo $Author;
$AuthorEx = explode("-",$Author);
$AuthorIm = implode(" ",$AuthorEx);
//echo $AuthorIm;
$PublisherEx = explode("-",$Publisher);
$PublisherIm = implode(" ",$PublisherEx);
$result = $this->advanced_model->searchresult($CategoryAssetId,$AssetTitleIm,$AuthorIm,$PublisherIm,$Year,$ISBN);
//print_r($result);
//echo count($result);
$x=0;
if(count($result) > 0){
foreach($result AS $d)
{
$data['tem'][$x] = array(
'categoryassetid' =>$d["CategoryAssetId"],
'AssetTitle' => $d["AssetTitle"],
'AssetSubtitle' => $d["AssetSubtitle"],
'PublisherName' => $d['PublisherName'],
'PublishYear' => $d['PublishYear'],
'MainAuthor' => $d['MainAuthor'],
'ISBN' => $d['ISBN'],
'Photo' => $d['Photo'],
'Bibli' => $d['Bibli'],
'CategoryAssetName' => $d['CategoryAssetName'],
'Description' => $d['Description']
);
$x++;
}
}
else
{
$data['tem'] = array();
}
/*$page_content["page_title"] = "Advanced Search";
$page_content["title"] = "Advanced Search";
$page_content["icon_title"] = "search";
$menu_params["current_navigable"] = "AdvancedSearch";
$menu_params["sub_current_navigable"] = "";
$page_content["menu"] = $this->load->view("main_menu", $menu_params, true);
$page_content["content"] = $this->load->view("advancedsearch", $data, true);
$page_content["navmenu"] = $this->load->view("nav_menu",$data, true);
$this->load->view("template/main_template", $page_content);*/
}
}
please help me if you have another idea..

Categories