JSON decode info from php - javascript

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

Related

Creating a REST API without model with Laravel 9

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

Break an array inside array php

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/>";
?>

How to return json string from php array

I am doing something i don't understand how. written a php code in O.O.P and the value gotten from it are objects. but i want to convert this O.O.P object to JSON data to be used in by javascript. so I converted my converted my objects to array on the php end. the try to use the json_encode function on it the script just keep returning errors. so i tried using a function i scope out, it worked but the js keeps on rejecting the data.
Below is the JS file
var ajax = new XMLHttpRequest();
ajax.open('GET','user.php',true);
ajax.setRequestHeader("Content-type","application/json");
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status ==200){
var data = JSON.parse(ajax.responseText.trim());
console.log(data);
console.log(data[username]);
}
}
ajax.send();
it will return this error "SyntaxError: JSON.parse: bad control character in string literal at line 1 column 129 of the JSON data"
without the JSON.parse it return undefind fro the data.username console log. Below is the PHP SCRIPT
//header("Content-type: application/json");
require_once 'core/init.php';
function array2json($arr) {
/*if (function_exists('json_encode')) {
echo "string";
return json_encode($arr);
}*/
$pars = array();
$is_list = false;
$keys = array_keys($arr);
$max_length = count($arr) - 1;
if (($keys[0] == 0) and($keys[$max_length] == $max_length)) {
$is_list = true;
for ($i = 0; $i < count($keys); $i++) {
if ($i != $keys[$i]) {
$is_list = false;
break;
}
}
}
foreach($arr as $key => $value) {
if (is_array($value)) {
if ($is_list) $parts[] = array2json($value);
else $part[] = '"'.$key.
':'.array2json($value);
} else {
$str = '';
if (!$is_list) $str = '"'.$key.
'"'.
':';
if (is_numeric($value)) $str. = $value;
elseif($value === false) $str. = 'false';
elseif($value === true) $str. = 'true';
else $str. = '"'.addslashes($value).
'"';
$parts[] = $str;
}
}
$json = implode(',', $parts);
if ($is_list) return '['.$json.
']';
return '{'.$json.
'}';
}
$user = new User();
$json = array();
if (!$user - > is_LOggedIn()) {
echo "false";
} else {
foreach($user - > data() as $key => $value) {
$json[$key] = $value;
//$json =json_encode($json,JSON_FORCE_OBJECT);
//echo $json;
}
/*$details = '{"'.implode('", "', array_keys($json)).'"';
$data = '"'.implode('" "', $json).'"}';
die($details.' / '.$data);*/
$json = array2json($json);
print $json;
}
PLEASE HELP ME OUT TO SORT THIS ERROR THANK YOU.
You need to set the response headers, and ensure you are not violating CORS:
/*
* Construct Data Structure
*/
$response =
[
'value1',
'value2'
];
/*
* Format Data
*/
$jsonResponse = json_encode ( $response, JSON_PRETTY_PRINT );
/*
* Prepare Response
*/
header('content-type: application/json; charset=UTF-8');
/*
* ONLY if you want/need any domain to be able to access it.
*/
header('Access-Control-Allow-Origin: *');
/*
* Send Response
*/
print_r ( $jsonResponse );
/*
* Return with intended destruction
*/
die;
Just use the json functions json_encode and json_decode to convert arrays into json string or vice versa:
$myArray = array("value1", "value2");
echo json_encode($myArray);

php pass json to angularjs

this is my php code,
$count=mysql_num_rows($query);
if ($count > 0) {
// output data of each row
$foodList[] = array();
while($row =mysqli_fetch_assoc($result))
{
$foodList[] = $row;
}
} else {}
echo json_encode($foodList);
this is my js code:
var $promise = $http.post('foodList.php');
$promise.then(function(msg){
var foodList = msg.data;
if (foodList)
{
//$scope.foodList = foodList;
alert(foodList);
}
else
{
//$scope.msg = "Error user name or password";
}
this is output:
$promise.then(function(msg){*msg = Object {data: Array[1], status: 200, config: Object, statusText: "OK"}*
var foodList = msg.data;*foodList = [Array[0]]*
So: actually 3 data in my data base, but in output just only Array[1]?
How to fix it ?
THX
Your count the $query variable so in your while loop use $query variable
<?php
$count=mysql_num_rows($query);
if ($count > 0) {
// output data of each row
$foodList = array();
while($row =mysqli_fetch_assoc($query))
{
$foodList[] = $row;
}
}
echo json_encode($foodList);
?>
Your php syntax and the usage of commands are wrong in some places. Here is the corrected code. Please compare and see the difference.
$count=mysql_num_rows($result);
if ($count > 0) {
// output data of each row
$foodList = array();
while($row =mysqli_fetch_assoc($result))
{
array_push($foodList, $row);
}
}
echo json_encode($foodList);
This should work if you are selecting the rows correctly.

SyntaxError: Unexpected token l in ajax call

I am trying to fetch a data from the server data base and pass it to the ajax to create a database table and its data in the local android database. But when an ajax call is make it give following error.
LogCat:
01-30 10:58:45.888: D/CordovaLog(31914): Server is not responding... Please try again: SyntaxError: Unexpected token l
01-30 10:58:45.888: I/Web Console(31914): Server is not responding... Please try again: SyntaxError: Unexpected token l at file:///android_asset/www/home.html:513
here is the ajax code:
$.ajax({
url : urlServer + 'getTableData.php',
// type: 'POST',
contentType : 'application/json',
beforeSend : function() {
$.mobile.loading('show')
},
complete : function() {
console.log("ajax complete");
createTable();
},
dataType : 'json',
data : {userId: user_id},
success : function(data) {
if (data != null)
{
dynamic_tabledetails = data.Table_details;
dynamic_selectQuery = data.SelectTableQuery;
table_data = data;
getTabledetails(dynamic_tabledetails);
}
else
{
alert("Error Message");
}
},
error : function(xhr, ajaxOptions, thrownError) {
console.log("Server is not responding... Please try again: "+thrownError);
}
});
Here is the php code:
<?php
require_once ('connect.php');
$userID= $_REQUEST['userId'];
$data = array ();
$listtables = array();
$Tabledetails = array();
$select_table = '';
$tab_name = array();
$getlistTables = 'SHOW TABLES FROM sacpl_crm_dev ';
$resultsListTables = mysql_query($getlistTables);
echo 'length of the tables name: '.$resultsListTables.' ';
while ($row = mysql_fetch_array($resultsListTables))
{
if(strpos($row[0],'_trail') == false)
{
$temporarydata = array();
$TableName = new ArrayObject();
$getTabledetails = 'show columns from '.$row[0].'';
$resultdetails = mysql_query($getTabledetails);
$TableName['tablename'] = $row[0];
$tab_name[] =$row[0];
$column = array();
$delete_field = '';
$comp_codeField = '';
while($rows = mysql_fetch_array($resultdetails))
{
$column_list =new ArrayObject();
$column_list['FieldName'] = $rows['Field'];
$column_list['Default'] = $rows['Default'];
if(strpos($rows['Type'],'(') == false)
{
$column_list['dataType'] = $rows['Type'];
$column_list['dataType_limit'] ='';
}
else
{
$type = explode('(',$rows['Type']);
$column_list['dataType'] = $type[0];
$column_list['dataType_limit'] = '('.$type[1];
}
if($rows['Field'] == 'deleted')
{
$delete_field = 'deleted = 0';
}
if($rows['Field'] == 'userId')
{
$userIdField = $rows['Field'].'="'.$userId.'"';
}
$column_list['Extra'] = $rows['Extra'];
$column_list['Null_value'] = $rows['Null'];
$column_list['Key_value'] = $rows['Key'];
$column[] = $column_list;
}
$TableName['column_details'] = $column;
$Tabledetails[]=$TableName;
if($userIdField == '' && $delete_field !='')
{
$select_table = 'select * from '.$row[0].' where '.$delete_field.'';
}
else if($userIdField != '' && $delete_field =='')
{
$select_table = 'select * from '.$row[0].' where '.$userIdField.'';
}
else if($userIdField != '' && $delete_field !='')
{
$select_table = 'select * from '.$row[0].' where '.$userIdField.' and '.$delete_field.'';
}
else{
$select_table = 'select * from '.$row[0].'';
}
$select_query[] = $select_table;
$resultTableData = mysql_query($select_table);
while ($row1 = mysql_fetch_array($resultTableData))
{
$temporarydata[] = $row1;
}
$data[$row[0]] = $temporarydata;
}
}
$data['Table_details'] = $Tabledetails;
$data['SelectTableQuery'] = $select_query;
mysql_close($con);
require_once('JSON.php');
$json = new Services_JSON();
echo ($json->encode($data));
?>
Comment out the line:
echo 'length of the tables name: '.$resultsListTables.' ';
Also, when outputting JSON for an AJAX call, it's important to set the Content-type header using:
header('Content-type: application/json; charset=utf-8',true);
This php code doesn't seem to have syntax error. the problem probably lies on the included php's: "connect.php" and "JSON.php". could you please post them too so we can find the error.
Link this into the beginning of your PHP-file:
header("Content-Type: text/javascript; charset=utf-8");

Categories

Resources