I'm just starting to learn Laravel and I'd like to create a rest api without a model because I don't use one because my data comes from an external api. I have already written a piece of code however I am facing an error during my javascript request. It tells me that my json is incorrect.
I think the error comes from my api mainly from the way I return my json. Could you help me?
My API ChartCoinController.php
class ChartCoinController extends Controller
{
public function show($id)
{
$client = new CoinGeckoClient();
$dataChart = array(
'marketDataPrice24h' => array(),
'marketDataTime24h' => array(),
'marketDataPrice7j' => array(),
'marketDataTime7j' => array(),
'marketDataPrice1m' => array(),
'marketDataTime1m' => array(),
);
$date = strtotime(date("Y-m-d H:i:s"));
$date24h = strtotime(date("Y-m-d H:i:s", strtotime('-1 day')));
$date7j = strtotime(date("Y-m-d H:i:s", strtotime('-7 day')));
$date1m = strtotime(date("Y-m-d H:i:s", strtotime('-1 month')));
$marketData24h = $client->coins()->getMarketChartRange($id, 'usd', $date24h, $date);
$marketData7j = $client->coins()->getMarketChartRange($id, 'usd', $date7j, $date);
$marketData1m = $client->coins()->getMarketChartRange($id, 'usd', $date1m, $date);
dump($marketData24h);
// Pour 24h
for ($i = 0; $i < count($marketData24h['prices']); $i++) {
$dataChart['marketDataPrice24h'][$i] = number_format($marketData24h['prices'][$i][1], 2, '.', ',');
$dataChart['marketDataTime24h'][$i] = substr($marketData24h['prices'][$i][0], 0, -3);
}
// Pour 7j
for ($i = 0; $i < count($marketData7j['prices']); $i++) {
$dataChart['marketDataPrice7j'][$i] = number_format($marketData7j['prices'][$i][1], 2, '.', ',');
$dataChart['marketDataTime7j'][$i] = substr($marketData7j['prices'][$i][0], 0, -3);
}
// Pour 1 month
for ($i = 0; $i < count($marketData1m['prices']); $i++) {
$dataChart['marketDataPrice1m'][$i] = number_format($marketData1m['prices'][$i][1], 2, '.', ',');
$dataChart['marketDataTime1m'][$i] = substr($marketData1m['prices'][$i][0], 0, -3);
}
return response()->json($dataChart);
}
}
api.php
// API chartController
Route::get("/chart/{id}", [ChartCoinController::class, 'show']);
coinChart.JS
let url = 'http://crypto-data/api/chart/bitcoin'
fetch(url)
.then(function (response) {
console.log(response);
console.log(response.json())
return response.json();
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log('catch');
});
The connection with the api is correct (200) but at the level of the decoding of my json the execution goes directly in the catch:
Thank you in advance for your help
Related
Hi i am inserting data multiple data with for loop . and fetching thos data from database nd inserting to ghseet again now i want to make it happen at a time.
my for each loop is here
if (in_array($_POST['prodname'][$key], $checked_array)) {
$prodname = $_POST['prodname'][$key];
$prod_price = $_POST['prod_price'][$key];
$prod_qty = $_POST['prod_qty'][$key];
$prodsname = $_POST['prodsname'][$key];
$app_id = $_POST['app_id'][$key];
$district = $_POST['district'][$key];
$upazilla = $_POST['upazilla'][$key];
$store_name = $_POST['StoreName'][$key];
$ward = $_POST['ward'][$key];
for ($x = 0; $x < $prod_qty; $x++) {
$couponnumber = random_int(100, 100000);
$sql = "INSERT INTO `retailer_sales`( `product`, `Amount`, `quantity`,`C_Number`,`Retailer_Number`,`Dtistrict`,`Upzilla`,`coupon_number`,`StoreName`,`ward`) VALUES ('$prodname','$prod_price','$prod_qty','$prodsname','$app_id','$district','$upazilla','$couponnumber','$store_name','$ward')";
$result = $db->query($sql);
if ($result) {
$_SESSION["status"] = true;
} else {
$_SESSION["server_down"] = true;
echo '<script>window.location="../../pages/product_sale/main.php";</script>';
}
}
}
and my javascript code for sending to gsheet is
<script>
const scriptURL = 'https://script.google.com/macros/s/AKfycbzfMQmBwDEO8k0H8jeLlKTE_GzK0XuQ1unZd_5ib_DDBhM17b6FVahIW5f3W4FyfCNOAw/exec'
const form = document.forms['submit-to-gateway']
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, {
method: 'POST',
body: new FormData(form)
})
.then(response => $("#form_alerts").html("<div class='alert alert-success'>Id Sent Successfully.</div>"))
.catch(error => $("#form_alerts").html("<div class='alert alert-danger'>Id Could not be Sent.</div>"))
$('#myForm')[0].reset();
})
</script>
i want to insert each data which is inserting to mysql database.
help me with this.
I need a way to unpack JavaScript with PHP the changing code is on my domain here http://beastfeeds.com/ty9.php the full code is in page source view-source:http://beastfeeds.com/ty9.php for some odd reason the webpage only displays part of the code but the full one is there! I just need it to run and decrypt the code so it displays the decrypted code so i can grab the m3u8 from the output as it changes on every page load. Here is what i am trying to run to achieve it which works fine with Javascript Eval (U.n.p.a.c.k.e.d) but not with this format
<?php
class JavaScriptUnpacker
{
private $unbaser;
private $payload;
private $symtab;
private $radix;
private $count;
function Detect($source)
{
$source = preg_replace("/ /","",$source);
preg_match("/eval\(function\(p,a,c,k,e,[r|d]?/", $source, $res);
Debug::Write($res,"detection result");
return (count($res) > 0);
}
function Unpack($source)
{
preg_match_all("/}\('(.*)', *(\d+), *(\d+), *'(.*?)'\.split\('\|'\)/",$source,$out);
Debug::Write($out,"DOTALL", false);
// Payload
$this->payload = $out[1][0];
Debug::Write($this->payload,"payload");
// Words
$this->symtab = preg_split("/\|/",$out[4][0]);
Debug::Write($this->symtab,"symtab");
// Radix
$this->radix = (int)$out[2][0];
Debug::Write($this->radix,"radix");
// Words Count
$this->count = (int)$out[3][0];
Debug::Write($this->count,"count");
if( $this->count != count($this->symtab)) return; // Malformed p.a.c.k.e.r symtab !
//ToDo: Try catch
$this->unbaser = new Unbaser($this->radix);
$result = preg_replace_callback(
'/\b\w+\b/',
array($this, 'Lookup')
,
$this->payload
);
$result = str_replace('\\', '', $result);
Debug::Write($result);
$this->ReplaceStrings($result);
return $result;
}
function Lookup($matches)
{
$word = $matches[0];
$ub = $this->symtab[$this->unbaser->Unbase($word)];
$ret = !empty($ub) ? $ub : $word;
return $ret;
}
function ReplaceStrings($source)
{
preg_match_all("/var *(_\w+)\=\[\"(.*?)\"\];/",$source,$out);
Debug::Write($out);
}
}
class Unbaser
{
private $base;
private $dict;
private $selector = 52;
private $ALPHABET = array(
52 => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOP',
54 => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQR',
62 => '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
95 => ' !"#$%&\'()*+,-./0123456789:;<=>?#ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
);
function __construct($base)
{
$this->base = $base;
if($this->base > 62) $this->selector = 95;
else if($this->base > 54) $this->selector = 62;
else if($this->base > 52) $this->selector = 54;
}
function Unbase($val)
{
if( 2 <= $this->base && $this->base <= 36)
{
return intval($val,$this->base);
}else{
if(!isset($this->dict)){
$this->dict = array_flip(str_split($this->ALPHABET[$this->selector]));
}
$ret = 0;
$valArray = array_reverse(str_split($val));
for($i = 0; $i < count($valArray) ; $i++)
{
$cipher = $valArray[$i];
$ret += pow($this->base, $i) * $this->dict[$cipher];
}
return $ret;
// UnbaseExtended($x, $base)
}
}
}
class Debug
{
public static $debug = false;
public static function Write($data, $header = "", $mDebug = true)
{
if(!self::$debug || !$mDebug) return;
if(!empty($header))
echo "<h4>".$header."</h4>";
echo "<pre>";
print_r($data);
echo "</pre>";
}
}
// FOLLOW ALL REDIRECTS:
// This makes multiple requests, following each redirect until it reaches the
// final destination.
function get_redirect_final_target($url)
{
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_NOBODY, 1);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); // follow redirects
curl_setopt($ch, CURLOPT_AUTOREFERER, 1); // set referer on redirect
curl_exec($ch);
$target = curl_getinfo($ch, CURLINFO_EFFECTIVE_URL);
curl_close($ch);
if ($target)
return $target;
return false;
}
function getURL($u){
$ops = array(
'http'=>array(
'method'=>"GET",
'header'=>"Accept: text/html\r\n" .
"User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0\r\n"
)
);
$co = stream_context_create($ops);
$r = file_get_contents('http://' . $u, false, $co);
return $r != false ? $r : "";
}
function GetStringBetween($string, $start, $finish){
$string = " ".$string;
$position = strpos($string, $start);
if ($position == 0) return "";
$position += strlen($start);
$length = strpos($string, $finish, $position) - $position;
return substr($string, $position, $length);
}
$grab = file_get_contents("http://beastfeeds.com/ty9.php");
$streama = GetStringBetween($grab, 'var', '</script>');
$unpacker = new JavaScriptUnpacker();
$unpacked = $unpacker->Unpack($grab);
preg_match_all('/\b(?:(?:https?|ftp|file):\/\/|www\.|ftp\.)[-A-Z0-9+&##\/%=~_|$?!:,.]*[A-Z0-9+&##\/%=~_|$]/i', $unpacked, $result, PREG_PATTERN_ORDER);
$result = $result[0];
$stream = GetStringBetween($unpacked, "src:'", "'");
?>
<?= trim($unpacked, "\r\n\t ")?>
I reallllllly need this!!!! any help is greatly appreciated i have been trying to do this for a week now.
I'm trying to create a single line chart of a json response(sql) in html/javascript. What im trying to create is a chart with only one line of the tag_name, in the case below: "phone 4". This line should represent all values and datetimes of all json strings.
JSON response:
[{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:20:09"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:19:49"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:19:29"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:19:09"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:18:49"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:18:29"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:18:09"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:17:49"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:17:29"},
{"tag_name":"phone 4","value":"4","datetime":"2017-10-03 14:17:09"}]
What i've reached so far(not much):
<script type="text/javascript">
google.charts.load('current', {'packages': ['line']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('number', 'Datetime');
data.addColumn('number', 'Values');
var options = {
chart: {
title: 'Values',
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}
</script>
How my php code looks like:
require_once 'db_connection.php';
header('Content-type: application/json');
$data = array();
$Chart = "SELECT *
FROM (
SELECT *,
#rn := if( #tag_name = tag_name,
#rn + 1,
if(#tag_name := tag_name, 1, 1)
) as tag_count
FROM waardes
CROSS JOIN ( SELECT #rn := 0, #tag_name := '') as vars
ORDER BY tag_name
) as T
WHERE tag_count < 11 AND machine_id LIKE 3 AND tag_name LIKE 'phone 4'
ORDER BY datetime DESC";
$result = mysqli_query($connection, $Chart);
while ($row = mysqli_fetch_array($result)) {
if ($row["int_value"] == 0 && $row["real_value"] == 0.0 && $row["bool_value"] != "") {
array_push($data, array('tag_name' => $row['tag_name'], 'value' => $row['bool_value'], 'datetime' => $row['datetime']));
} elseif ($row["int_value"] == 0 && $row["real_value"] != 0 && $row["bool_value"] == "") {
array_push($data, array('tag_name' => $row['tag_name'], 'value' => $row['real_value'], 'datetime' => $row['datetime']));
} elseif ($row["int_value"] != 0 && $row["real_value"] == 0 && $row["bool_value"] == "") {
array_push($data, array('tag_name' => $row['tag_name'], 'value' => $row['int_value'], 'datetime' => $row['datetime']));
}
}
echo json_encode($data);
first, don't recommend mixing php and javascript in the same file
separate the html / javascript from the php
use ajax to get the data from php to javascript
for google charts, use the json format found here...
Format of the Constructor's JavaScript Literal data Parameter
this will allow you to create the google data table, directly from the json
getdata.php
require_once 'db_connection.php';
header('Content-type: application/json');
$data = array();
$Chart = "SELECT *
FROM (
SELECT *,
#rn := if( #tag_name = tag_name,
#rn + 1,
if(#tag_name := tag_name, 1, 1)
) as tag_count
FROM waardes
CROSS JOIN ( SELECT #rn := 0, #tag_name := '') as vars
ORDER BY tag_name
) as T
WHERE tag_count < 11 AND machine_id LIKE 3 AND tag_name LIKE 'phone 4'
ORDER BY datetime DESC";
$result = mysqli_query($connection, $Chart);
$data = array();
$data['cols'] = array(
array('label' => 'Date', 'type' => 'string'),
array('label' => 'phone 4', 'type' => 'number')
);
$data['rows'] = array();
while ($row = mysqli_fetch_array($result)) {
if ($row["int_value"] == 0 && $row["real_value"] == 0.0 && $row["bool_value"] != "") {
$row = array();
$row[] = array('v' => (string) $row['datetime']);
$row[] = array('v' => (float) $row['bool_value']);
$data['rows'][] = array('c' => $row);
} elseif ($row["int_value"] == 0 && $row["real_value"] != 0 && $row["bool_value"] == "") {
$row = array();
$row[] = array('v' => (string) $row['datetime']);
$row[] = array('v' => (float) $row['real_value']);
$data['rows'][] = array('c' => $row);
} elseif ($row["int_value"] != 0 && $row["real_value"] == 0 && $row["bool_value"] == "") {
$row = array();
$row[] = array('v' => (string) $row['datetime']);
$row[] = array('v' => (float) $row['int_value']);
$data['rows'][] = array('c' => $row);
}
}
$data['rows'] = $rows;
echo json_encode($data);
JavaScript
google.charts.load('current', {
packages: ['line']
}).then(function () {
$.ajax({
url: 'getdata.php',
dataType: 'json'
}).done(function (jsonData) {
var data = new google.visualization.DataTable(jsonData);
var options = {
chart: {
title: 'Values'
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('chart_div'));
chart.draw(data, google.charts.Line.convertOptions(options));
}).fail(function (jq, text, errMsg) {
console.log(text + ': ' + errMsg);
});
});
this will give you a better structure to handle multiple charts / data tables
now, if you wanted to use a real date in the chart, instead of a string (as in the above php)
it would allow you to use chart options such as format, for the x-axis
you can pass the date value as a string, in the following format found here...
Dates and Times Using the Date String Representation
"Date(Year, Month, Day, Hours, Minutes, Seconds, Milliseconds)"
to do this, change the column type to date...
array('label' => 'Date', 'type' => 'date'),
then when loading the data, using the following to format as above...
$rowDate = "Date(".date_format($row['datetime'], 'Y').", ".((int) date_format($row['datetime'], 'm') - 1).", ".date_format($row['datetime'], 'd').", ".date_format($row['datetime'], 'H').", ".date_format($row['datetime'], 'i').", ".date_format($row['datetime'], 's').")";
$row = array();
$row[] = array('v' => (string) $rowDate);
$row[] = array('v' => (float) $row['bool_value']);
$data['rows'][] = array('c' => $row);
note: month numbers are zero-based in javascript...
I have a function which allows me to save dropped objects for each process in loop. Fiddle here The problem i am creating an array for each process and store dropped items inside. Function i use to save droped items:
<script>
var LISTOBJ = {
saveList: function() {
$(".leader").each(function() {
var listCSV = [];
$(this).find("li").each(function(){
listCSV.push($(this).text());
});
var values = listCSV.join(', ');
$(".output").append("<input type='hidden' name='leader[]' value='"+values+"' />");
$("#output").append("<p>"+values+"</p>");
console.debug(listCSV);
});
}
}
</script>
And what i get after printing saved objects:
Array ( [0] => aaronjames,adelyn [1] => benny,bryanooi )
I want to store names in the database and im able to do it but it stores an array. So i am looking a way to break an array inside array, instead of storing a full array.
I have 2 tables: 'project' and 'process'. I am trying to insert names into 'process' table. I am able to do so. but it stays as an array.
Here is function i am using to store received value inside database. I am generating project number and using foreach to assign names for each process
function insertRecord(){
global $holdcode,$holdtitle,$projLeader,$projChecker,$holdremark,$holdprocess,$holdnumber,$procLeader,$procChecker, $prodStuff;
// To protect MySQL injection (more detail about MySQL injection)
$holdcode = cleanInputData($holdcode);
$holdtitle = cleanInputData($holdtitle);
$projLeader = cleanInputData($projLeader);
$projChecker = cleanInputData($projChecker);
$holdremark = cleanInputData($holdremark);
$holdcode = mysql_real_escape_string($holdcode);
$holdtitle = mysql_real_escape_string($holdtitle);
$projLeader = mysql_real_escape_string($projLeader);
$projChecker = mysql_real_escape_string($projChecker);
$holdremark = mysql_real_escape_string($holdremark);
$result = getLastProjectNo();
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result) == 0)
{
$year = date("y");
$month = date("m");
$number = sprintf("%04d", 1);
$yearStr = strval($year);
$monthStr = strval($month);
$numberStr = strval($number);
$projectNo = $yearStr . $monthStr . $numberStr;
}
else{
if ($row_last = mysql_fetch_array($result))
{
$row_last[0] = cleanOutputData($row_last[0]);
$projectNo = $row_last[0];
$extractedNumberStr = substr($projectNo, -4);
$extractedYearMonthStr = substr($projectNo, 0, 4);
$year = date("y");
$month = date("m");
$yearStr = strval($year);
$monthStr = strval($month);
$currentYearMonthStr = $yearStr . $monthStr;
if($extractedYearMonthStr == $currentYearMonthStr)
{
$extractedNumber = intval($extractedNumberStr);
$extractedNumber++;
$extractedNumber = sprintf("%04d", $extractedNumber);
$extractedNumberStr = strval($extractedNumber);
$projectNo = $currentYearMonthStr . $extractedNumberStr;
}
else
{
$number = sprintf("%04d", 1);
$projectNo = $currentYearMonthStr . $number;
}
}
}
mysql_set_charset('utf8');
//query result
$result = insertProject($projectNo,$_SESSION['login_user'],$holdcode,$holdtitle,$projLeader,$projChecker,$holdremark);
// Check result
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$result = getLastProjectNo();
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$result = getLastProjectNo();
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if ($row_last = mysql_fetch_array($result))
{
$row_last[0] = cleanOutputData($row_last[0]);
$projectNo = $row_last[0];
if (is_array($holdprocess) || is_object($holdprocess))
{
foreach( $holdprocess as $code => $eq )
{
$record = insertProcess($projectNo,$eq,$holdnumber[$code],$procLeader[$code],$procChecker[$code], $prodStuff[$code]);
if (!$record) {
die('Invalid query: ' . mysql_error());
}
}
}
}
}
What I want is to break an array inside array.For example i have Array ( [0] => aaronjames,adelyn [1] => benny,bryanooi ) i need to break [0] => aaronjames,adelyn into something that will allow me to store each name for each row in the table
Let me show you a way to read array value:
for($x = 0; $x < count($array_name); $x++) {
echo $array_name[$x];
echo "<br>";
}
If you need to access an array of objects then, try this
foreach($array_name as $obj){
$status = $obj->status;
}
If you receive a combined string (like 'aaronjames,adelyn') from array, then you can split the combined string using 'explode()' function of Php
<?php
$str = "aaronjames,adelyn";
$str_array=(explode(",",$str));
for($i=0;$i<count($str_array);$i++)
echo $str_array[$i]."<br/>";
?>
I'm getting errors decoding JSON string.
ERROR:
Uncaught SyntaxError: Unexpected token {
My php code:
<?php
$socket = $_GET["socket"];
$bd = new PDO("mysql:host=localhost;dbname=gestao_utilizadores" , "root" , "");
$getComponentes = $bd->prepare("SELECT * FROM componentes WHERE ( Socket=:socket )");
$getComponentes->bindValue(':socket' , $socket);
$getComponentes->execute();
$resultado = $getComponentes->fetchAll();
For ($i = 0; $i < $getComponentes->rowCount() ; $i++) {
$componentes = json_encode(array('tipo' => $resultado[$i]["Tipo"] , 'nome' => $resultado[$i]["Nome"] , 'socket' => $resultado[$i]["Socket"]));
echo $componentes;
}
?>
My Javascript code:
$.ajax({
url: 'compatibilidades.php',
data: {
socket: $("#board option:selected").attr('value')
},
success: function(dadosRecebidos) {
teste = JSON.parse(dadosRecebidos);
alert(teste);
}
});
The error is on javascript or PHP?
<?php
$socket = $_GET["socket"];
$bd = new PDO("mysql:host=localhost;dbname=gestao_utilizadores" , "root" , "");
$getComponentes = $bd->prepare("SELECT * FROM componentes WHERE ( Socket=:socket )");
$getComponentes->bindValue(':socket' , $socket);
$getComponentes->execute();
$resultado = $getComponentes->fetchAll();
$arr = array();
for ($i = 0; $i < $getComponentes->rowCount() ; $i++) {
$componentes = array('tipo' => $resultado[$i]["Tipo"] , 'nome' => $resultado[$i]["Nome"] , 'socket' => $resultado[$i]["Socket"]);
array_push($arr, $componentes);
}
echo json_encode($arr);
?>
Output the JSON only once, otherwise you end up with an output of several JSON strings, something like
{"key1": "value1", "key2": "value2"}{"key3": "value3"}
and that's not valid JSON