After a call to a php method that loads a value from a table, I am expected to be returned the number 10 but instead I get returned the following weird string:
string(1) "9" 10
How can I extract the value 10 alone? What kind of index does "9" represent?
I have tried also with echo json_encode($newNo); in php but it shows an error.
html:
document.getElementById("output").value = this.responseText; //string(1) "9" 10
php:
$number = 9;
$newNo = $number + 1;
echo $newNo;
Related
I'll be obtaining jsvariable from on onclick javascript from the user. The user will input how much money they are spending in $xx.xx amount. It will come in, in string form. I need to do math on the amount, so I need it as a float.
I set it to a string as an example. I extract it from javascript into a php string variable:
<script> var jsvariable = "2.25"; </script>
<?php $x = "<script>document.writeln(jsvariable);</script>";
echo $x; var_dump($x); ?>
The echo $x shows 2.25. The var_dump shows that $x is a string(38) "2.25 "
So it's showing the $x variable now in php to be a 38 char string but it contains only 5 characters.
Then I try converting it with settype function. Also try re-casting it. It's not converting it.
<?php
settype($x, "float");
echo "After settype x is "; echo $x; var_dump($x);
$y = (float)$x ;
echo " y cast y is "; echo $y; var_dump ($y);
?>
After settype x is 0 float(0)
After casting y is 0 float(0)
How do I convert the $x string into a float number that's the right value of 2.25 ?
Just cast it like this: $y = (float)$x. You might want to check out type juggeling as well as String conversion to numbers.
I have a very simple PHP array
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
PHP
If I dd($array); out I got
array:3 [▼
"a" => "1"
"b" => "2"
"c" => "3"
]
If I decode dd(json_encode($array));, I got this
"{"a":"1","b":"2","c":"3"}"
JS
I want to be able to access this variable in my Javascript, So I've tried
1
console.log($array);
I got
$array is not defined
2
I'm using Laravel. {{ }} == echo
console.log('{{$array}}');
I got
500 Internal Error
htmlentities() expects parameter 1 to be string, array given (View: /Users/bheng/Sites/portal/resources/views/cpe/index.blade.php)
3
console.log('{{ json_encode($array)}}');
I got
The page to load, but the data is very bad looking
{"a":"1","b":"2","c":"3"}
4
console.log(JSON.parse('{{ json_encode($array)}}'));
I got
Uncaught SyntaxError: Unexpected token & in JSON at position 1
5
console.log(JSON.parse('{{ json_decode($array)}}'));
I got
json_decode() expects parameter 1 to be string, array given
6
console.log('{{ json_decode($array)}}');
I got
json_decode() expects parameter 1 to be string, array given
GOAL
I just want to be able to access my array as Javascript Array or JSON in the Javascript.
Can someone please fill me in on this ?
In Blade, {{ $variable }} will output an escaped version of the string, passed through htmlentities() to make it safe for use in HTML. You want an unescaped version. You can use {!! $variable !!} for that:
console.log({!! json_encode($array) !!});
You don't need to add quotes around it, json_encode() outputs a valid javascript object. It will add quotes where necessary, if you add them yourself you will get the JSON string in your javascript, instead of the JSON object.
In Laravel you can use {!! !!} to skip entity escaping
console.log({!! json_encode($array) !!});
Just echo it as json data and use it in javascript.
<?php
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
?>
<script>var jsArr = <?=json_encode($array);?>;
alert(jsArr);</script>
EDIT because of clarification that you're using blade. Then it should be:
<?php
$array = [];
$array['a'] = '1';
$array['b'] = '2';
$array['c'] = '3';
?>
<script>var jsArr = {!! json_encode($array) !!};
alert(jsArr);</script>
{ ... } is an escaped version of your string. But you need the unescapt string. This can be achieved by using {!! ... !!}.
First, you have to understand that PHP run on server side and javascript on client side, as PHP make the response you should print a script like this:
echo "<script>
var sheison = JSON.parse(".dd(json_encode($array)).");
console.log(sheison);
</script>";
I didn't test the code, is just the idea.
I am trying to get the browser timezone via JavaScript and capture it in a php variable with ob_start() and ob_get_clean. The value set by ob_get_clean shows as a string, but when I try to cast it to an int in php, the value goes to 0.
It doesn't matter how I cast this string, (int) $offset or intval($offset) or $offset * 1 the string starts as 420, but the result of casting it to an integer changes the value to integer 0.
<?php
ob_start();
?>
<script>
var d = new Date();
document.write(d.getTimezoneOffset());
</script>
<?php
$offset = trim(ob_get_clean()); // timezone offset Colorado = 420 minutes
echo $offset; // 420
echo gettype($offset); // string
$offset += 0;
echo gettype($offset); // integer
echo $offset; // shows 0 - I expect the value to be 420
I expect $offset to be an integer with a value of 420. Now it I try similar code with a regular string, I get the expected results.
$strnum = '530';
echo gettype($strnum); // string
$strnum += 0;
echo gettype($strnum); // integer
echo $strnum; // 530
?>
I can't see why the two examples don't work the same.
You can't to this, you can't catch the JS script output in php, you need to pass it throught ajax call. Check the SOURCE OUTPUT of the page and not the screen output.
screen output (in my case):
-60 string integer 0
REAL OUTPUT (SOURCE):
<script>
var d = new Date();
document.write(d.getTimezoneOffset());
</script>
string
integer
0
why u not use cast (int) or intval() function
example :
$var = (int) $yourstring
OR
$var = intval($youtstring)
Try this out
$offset = 'timezone offset Colorado = 420 minutes';
preg_match_all('!\d+!', $offset, $matches);
echo $offset; // 420
print_r( $matches); //array
echo $matches[0][0]; //420
$matches[0][0] += 1;
echo $matches[0][0];
Am using $.get to send some values when decoding them in php they are all converted to strings even though they are numbers.
CODE:
var id_from = 19;
var id_to = 19;
$.get("save.php",{id_from:id_from,id_to:id_to }, function(){
console.log(result)
});
On the save.php
<?php
var_dump($_GET)
?>
Am getting
array(2) {
["id_from"]=>
string(1) "1"
["id_to"]=>
string(1) "4"
}
How can i get the values as integers since they are output as strings
try this:
PHP
By typecasting you can do this.
$value = "4";
$val = (int) $value;
echo var_dump($value); //string(1) "4"
echo var_dump($val); // int(4)
You can use the intval() function to convert it to int
<?php
echo intval($_GET['id_from'])."|".$_GET['id_from'];
?>
You can type cast in PHP Server side.
$id_from = (int) $_GET['id_from']
How do i get "LSZ09".
var el1=data[0];
alert(el1);
This gives me "a" from array, as position 1 gives me r, 2 r, 3 a, 4y ,..
The array is received through a " echo json_encode($punten); "
Also when i try
var jsonDataArray = JSON.parse(data);
I get a syntax error:
SyntaxError: JSON.parse: unexpected character
Code:
$.ajax({ url: 'getPunten.php',
data: {statnam: jSelectedStation[0]},
type: 'get',
success: function(data) {
Received from php script, with last line being: echo json_encode($punten);
[{"STATDEV":"LSZ09 ","0":"LSZ09 ","DEVPKT":"1","1":"1","PKTTYP":"S","2":"S","KARTNR":"0","3":"0","BITNRK":"1","4":"1","BITSTATUS":"0","5":"0","TYPE":"I ","6":"I "},{"STATDEV":"LSZ10 ","0":"LSZ10 ","DEVPKT":"1","1":"1","PKTTYP":"S","2":"S","KARTNR":"0","3":"0","BITNRK":"2","4":"2","BITSTATUS":"0","5":"0","TYPE":"I ","6":"I "}
php:
$db = new PDO ("xxxx");
$qry="SELECT r.refnam, r.zustnr FROM refdev r INNER JOIN (SELECT refnam, COUNT(*) cnt FROM refdev rc GROUP BY refnam) rc ON rc.refnam = r.refnam LEFT OUTER JOIN texte t ON r.sigtnr = t.textnr WHERE rc.cnt = $aantal AND t.tstring LIKE '%$tekst%' ORDER BY r.refnam, r.zustnr";
$filterQry = $db->query($qry);
$filtered = $filterQry->fetchAll();
echo json_encode($filtered);
If that php you've shown is the one you're using,no, it won't work.
You see, the text that gets passed to the javascript includes the results of both var_dump and echo.
Consider the following php code:
<?php
$filtered = array(1,2,3);
var_dump($filtered);
echo json_encode($filtered);
?>
What do you think the result of this is? Hint: it's not what you've been expecting.
You seem to be expecting it to be
[1,2,3]
Well, it is - at least in part. That's the output of the last line only. But we've not considered the middle line var_dump($filtered); - the code that will output something similar to the code you've labelled with Received from php script, with last line being: echo json_encode($punten);
The output of my snippet is actually:
array(3) { [0]=> int(1) [1]=> int(2) [2]=> int(3) } [1,2,3]
That's why you're getting the first 5 elements containing 'a' 'r' 'r' 'a' 'y'!!
Its also why the call to JSON.parse(data); fails - "arrray(3)" isn't valid json.
Hint: when you navigate to the php script with a browser, what you see there is what will be retrieved with an ajax call.