Trying to get integer out of json for current time comparison - php

<?php
date_default_timezone_set('America/Los_Angeles');
$date = date('Gi', time());
?>
<script type="text/javascript">
var locTime = <?php echo json_encode($date) ?>;
var jTime = null;
$.getJSON( "urltojson", function(result) {
console.log("sucess1");
jTime = result["crossroads"]["monday"][0];
console.log("sucess2");
console.log(jTime)
})
</script>
json -
{ "crossroads":
{
"monday": [
{"breakfastopen": 700},
{"breakfastclose": 1100},
{"lunchopen": 1100},
{"lunchclose": 1400},
{"dinneropen": 1700},
{"dinnerclose": 2100}
]
}
}
in console jTime output is always
Object {breakfastopen: 700}
How do i get jTime to trim down and show only '700'?
What I'm trying to do is get the local hours to compare with the integer in json array. So far i have no luck of brining the json variable to jTime and have it compare against locTime.

It should be returning an object so to get access it should be
data.crossroads.monday[0].breakfastopen
{} denote objects [] are arrays

Related

Json Returning [object object] instead of values

I am trying to extract the values ​​of a json but when I return it I get an object object.
Something I did wrong in decoding? this is the decoding code in php
<?php $contenido=file_get_contents("https://www.deperu.com/api/rest/cotizaciondolar.json");
$info = json_decode($contenido,true);
$cadena=array(
0=>$info['cotizacion'],
);
echo json_encode($cadena);
?>
this is the function code
<script>
$(function() {
$("#btnbuscar").on('click',function(){
var direccion='servicio.php';
$.ajax({
type:'get',
url:direccion,
success:function(datos){
var campo=eval(datos);
alert(datos[0]);
}
});
return false;
});
});
</script>
Uwhen you write this:
$cadena=array(
0=>$info['cotizacion'],
);
echo json_encode($cadena);
Your $info is an array, and cadena is an array, too. So you can direct point $cadenra to the array like this:
$cadena= $info['cotizacion'];
echo json_encode($cadena);
Or fix your js like this:
alert(datos[0][0]);
Here is a simple way to read your JSON without Ajax but with using $.getJSON
On your PHP file since you want to get only "cotization" data change: $cadena=array(0=>$info['cotizacion'] to $cadena=array(0=>$info['cotizacion'][0] and you can remove [0] if you are planning to have and to loop on multiple "cotizacion"
On your javascript use:
$.getJSON("servicio.php", function(data) {
var items = [];
$.each(data[0], function(key, val) {
(key + '=' + val);
});
});
There are several solutions, but don't get wrong in a javascript/jquery while calling a json chain.
For example:
<?php
// Page : service.php
$json = '{
"service": "Reference dollar exchange rate",
"website": "website.com",
"link": "https://www.website.com/gearbox_type/",
"quotation": [{
"buy": 3.419,
"sale": 3.424
}]
}';
// $json = file_get_contents("https://www.website.com/api/example.json");
$info = json_decode($json,true); // convert array
$cadena=array(
0=>$info['quotation'][0],
);
echo json_encode($cadena); // convert json
// get-> [{"buy":3.419,"sale":3.424}]
echo json_encode($cadena[0]); // convert json
// get-> {"buy":3.419,"sale":3.424}
?>
// Javascript
// To better use your function I would have to do a cleanup of the code with JSON.parse
<script>
$(function() {
/*
* Check yes and Json and convert json string
* Analyze the data with JSON.parse () and the data becomes a JavaScript object.
* Ex. var obj = '{hello:'mitico'}' -> convert object
* $.clean_string_json(obj) return-> {hello:'mitico'}
* $.clean_string_json('text' + obj) return-> {}
* $.clean_string_json('text' + obj,false) return-> false
* $.clean_string_json('text' + obj,true) return-> true
*/
$.clean_string_json = function (str,xreturn) {
try {
return JSON.parse(str);
} catch (e) {
return xreturn === false ? false : xreturn || {};
}
};
$("#btnbuscar").on('click',function(){
$.ajax({
type:'get',
url: 'service.php',
success:function(datos){
var campo= $.clean_string_json(datos);
alert(datos[0]); // return -> {"buy":3.419,"sale":3.424}
}
});
return false;
});
});
</script>
Welcome to stackoverflow! We hope you like it here.
As already pointed out by #Anurag Srivastava, call the url directly and you'll get json back, you do not need a proxy.
const jUrl = "https://www.deperu.com/api/rest/cotizaciondolar.json";
$.get(jUrl)
.then(({cotizacion}) => console.log(cotizacion));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to solve error Undefined index in php (laravel)

I am sending arrays from View to Controller using Post Method. This is my code.
Controller: Session::put('isCheck', $isCheck);
this is how i am assigning value to isChecked array.
var isChecked = [
<?php
$isCheck = "";
if (Session::has('isCheck')) {
$isCheck = Session::get('isCheck');
}
foreach ($isCheck as $isCheck) {
$status = $isCheck;
?>
<?php echo $status; ?>,
<?php } ?>
];
View:
$("#target").click(function () {
var postTo = '<?php echo action('sample#postView'); ?>';
var data = {
isChecked: isChecked,
duplicateIsChecked: duplicateIsChecked
};
jQuery.post(postTo, data,
function (data) {
alert(data);
});
});
isChecked and DuplicateIsChecked are my 2arrays.
In controller I am writing this code:
$duplicateIsChecked = $_POST['duplicateIsChecked'];
$isCheck = $_POST['isChecked'];
But i am getting Undefined index duplicateIsChecked error. Help me
Have you checked the header of your Ajax call to make sure its sending any data? In the code you posted, you're assigning variables to the two values in data but you didn't show where you are declaring those variable values.
You can't pass a javascript array to php like that, you have to convert the array into JSON and send it.
so it should be
var data = JSON.stringify({
isChecked: isChecked,
duplicateIsChecked: duplicateIsChecked
});
To get the JSON payload in controller, you can use
$payload = Input::json()->all();
then to access the attribute, you can reference it as
$payload['duplicateIsChecked'] & $payload['isChecked']

Get json from php session instead of json file

I have this jquery function
function updateStatus(){
$.getJSON("<?php echo $_SESSION['filnavn']; ?>", function(data){
var items = [];
pbvalue = 0;
if(data){
var total = data['total'];
var current = data['current'];
var pbvalue = Math.floor((current / total) * 100);
if(pbvalue>0){
$("#progressbar").progressbar({
value:pbvalue
});
}
}
if(pbvalue < 100){
t = setTimeout("updateStatus()", 500);
}
});
}
Is it possible to get the JSON from a PHP session variable instead of a json file?
As I have understood I can get the session data from the session like this:
//json test
var jsonstr = $_SESSION['json_status'];
//parse json
var data = JSON.parse(jsonstr);
But I do not know how I can do that with out the getJSON function?
You're reading too much into it. .getjson is just a $.ajax() call that EXPECTS to get a json reponse from the server. That's all.
It doesn't matter WHERE PHP gets data from, as long as it spits out json text.
Whether that json text was just retrieved from a file/db, or dynamically generated with json_encode(), as long as the browser receives json text, things will "work".
Your best bet here is to create a php file that can act as the target of getJSON that returns the json from your session.
<?php
session_start();
if (isset($_SESSION["filnavn"])){
echo $_SESSION["filnavn"];
// Or, if the key contains an object instead of a json string, use
// echo json_encode($_SESSION["filavn"]);
} else {
// echo the json you want here if the session variable is not set
echo "{}";
}
?>
Then in your jquery code change the getJSON to this
$.getJSON("/path/to/php/file.php", function(data){...});

convert a value from json_decode to a string

how do i convert my value from json_decode to string so i can pass in a the string value to check if an email exists here is my code.
my json is in this format:
{email:'test#test.com' }
PHP:
$var = json_decode($_REQUEST["email"], true);
$result = $membership->CheckEmailAddress($var); // get $var to become a string
It looks pretty ugly im just starting php and Im not getting very far aye lol.
jquery:
$('#checkemail').click(function () {
var json = {
email: $('#email').val()
};
$.post('http://' + location.host + '/buyme/include/getemailaddress.php', {
'email': 'test#yahoo.co.nz'
}, function (res) {
var obj = JSON.parse(res);
alert(obj.message)
});
});
also how do I put my json variable in my $.post function cose thats the value I want to put there
what value in $_REQUEST["email"] if it's a json value you are showing above then try
your $var is a json object you can fetch email value like not use $var it's an array
tried this :-
$val = json_encode(array('email' =>'test#test.com'));
echo $val; //output {"email":"test#test.com"}
$var = json_decode($val, true);
print_r($var); // output Array ( [email] => test#test.com )
echo $var['email']; //output test#test.com

Pass a PHP array to a JavaScript function [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I am trying to get a PHP array variable into a JavaScript variable.
This is my code:
<html>
<head>
<script type="text/javascript">
function drawChart(row,day,week,month,date)
{
// Some code...
}
</script>
</head>
<body>
<?php
for($counter = 0; $counter<count($au); $counter++)
{
switch($au[$counter]->id)
{
case pageID.'/insights/page_active_users/day':
$day[] = $au[$counter]->value;
break;
case pageID.'/insights/page_active_users/week':
$week[] = $au[$counter]->value;
break;
case pageID.'/insights/page_active_users/month':
$month[] = $au[$counter]->value;
break;
}
}
?>
<script>
drawChart(600/50, '<?php echo $day; ?>', '<?php echo $week; ?>', '<?php echo $month; ?>', '<?php echo createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day')))); ?>');
</script>
</body>
</html>
I can't get value of the PHP array.
How do I fix this problem?
Use JSON.
In the following example $php_variable can be any PHP variable.
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
In your code, you could use like the following:
drawChart(600/50, <?php echo json_encode($day); ?>, ...)
In cases where you need to parse out an object from JSON-string (like in an AJAX request), the safe way is to use JSON.parse(..) like the below:
var s = "<JSON-String>";
var obj = JSON.parse(s);
You can pass PHP arrays to JavaScript using json_encode PHP function.
<?php
$phpArray = array(
0 => "Mon",
1 => "Tue",
2 => "Wed",
3 => "Thu",
4 => "Fri",
5 => "Sat",
6 => "Sun",
)
?>
<script type="text/javascript">
var jArray = <?php echo json_encode($phpArray); ?>;
for(var i=0; i<jArray.length; i++){
alert(jArray[i]);
}
</script>
Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.
drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))
This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here
$employee = array(
"employee_id" => 10011,
"Name" => "Nathan",
"Skills" =>
array(
"analyzing",
"documentation" =>
array(
"desktop",
"mobile"
)
)
);
Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.
{
"employee_id": 10011,
"Name": "Nathan",
"Skills": {
"0": "analyzing",
"documentation": [
"desktop",
"mobile"
]
}
}
On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.
$.ajax({
type: 'POST',
headers: {
"cache-control": "no-cache"
},
url: "employee.php",
async: false,
cache: false,
data: {
employee_id: 10011
},
success: function (jsonString) {
var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
});
In the following example you have an PHP array, then firstly create a JavaScript array by a PHP array:
<script type="javascript">
day = new Array(<?php echo implode(',', $day); ?>);
week = new Array(<?php echo implode(',',$week); ?>);
month = new Array(<?php echo implode(',',$month); ?>);
<!-- Then pass it to the JavaScript function: -->
drawChart(<?php echo count($day); ?>, day, week, month);
</script>

Categories