I have this array ($test) in PHP
array (size=4)
1 => string 'test1#mail.example' (length=17)
2 => string 'test2#mail.example' (length=17)
3 => string 'test3#mail.example' (length=17)
4 => string 'test4#mail.example' (length=17)
And want to pass it to javascript. My goal is to use this in a AJAX query.
So I did the following
var test = "<?php echo json_encode($test); ?>";
$.post("../path/to/file.php",
{
test: test,
},
function(data,status)
{
...
});
But the following is triggering everytime
SyntaxError: missing ; before statement
var test = "{"1":"test1#mail.example","2":"test1#mail.
Don't enclose the json output in quotes. It's unecessary:
var test = <?php echo json_encode($test); ?>;
json_encode() will already be adding any necessary " characters, and your extra " are breaking the syntax, e.g.
php:
$foo = 'ab"c';
json_encode($foo) -> "ab\"c";
js:
var test1 = <?php echo json_encode($foo); ?>;
var test2 = "<?php echo json_encode($foo); ?>";
which comes out as:
var test1 = "ab\"c"; // this line is ok
var test2 = ""ab\"c""; // this line is fubar
^--start string
^--end string
^^---undeclared/undefined variable
Related
it seems to be a really easy question, but I am a little bit struggling: I am receiving a JSON String via JavaScript. Now I would like to iterate through the element. The resulting string has this form: {"title":value,"title2":value}
How can I iterate through this JSON string without knowing the key and value? I would like to get this output:
title -> value
title2 -> value2
I tried it this way:
$json = file_get_contents('php://input');
$array = json_decode($json,true);
$response = "Test";
foreach($array as $key=>$val) {
$response = $response. "$key : $val";
}
echo json_encode($response);
It only returns "Test". If I change it to echo json_encode($array), it returns the mentioned JSON String.
You mention javascript and php in your question, so I'm going to answer for both. Here is JS, two different ways. I believe that foreach is being deemphasized in favor of the (of) construct now, but I don't work primarily in JS:
var json = '{"title": 12, "title2": "text"}';
var data = JSON.parse(json);
Object.keys(data).forEach(function(key) {
console.log(key + ' -> ' + data[key])
})
for(key of Object.keys(data)) {
console.log(key + ' -> ' + data[key]);
}
And for PHP:
You can parse the json string into an array using json_decode:
$json = '{"title": 12, "title2": "text"}';
$arr = json_decode($json, true);
foreach($arr as $key=>$val) {
echo "$key : $val";
}
true parses it into an array instead of a std object.
https://www.php.net/manual/en/function.json-decode.php
Because of response's format you must decode the decoded format in order to take the object as you want
$json = '{"title": 12, "title2": "text"}';
$encoded=json_encode($json);
$decoded=json_decode($encoded);
$ddecode=json_decode($decoded);
foreach($ddecode as $key=>$val) {
echo "$key -> $val";
}
Output :
title -> 12 title2 -> text
I am trying to convert a PHP function to javascript, but i cant read the following line of codes:
$sha_string .= "$key=$value$ipn_passphrase";
and
$sha_sign = strtoupper(hash("sha512", $sha_string));
Complete function:
function digistore_signature( $ipn_passphrase, $array)
{
unset($array[ 'sha_sign' ]);
$keys = array_keys($array);
sort($keys);
$sha_string = "";
foreach ($keys as $key)
{
$value = html_entity_decode( $array[ $key ] );
$is_empty = !isset($value) || $value === "" || $value === false;
if ($is_empty)
{
continue;
}
$sha_string .= "$key=$value$ipn_passphrase";
}
$sha_sign = strtoupper(hash("sha512", $sha_string));
return $sha_sign;
}
the $array is the body of a POST request.
the $passphrase is a string
.= in PHP is a simple concatenation. it is similar to the programming concept of +=. It's easy to understand with an example
<?php
$a = "hello";
$a .= " "; //now $a = "hello "
$a .= "world"; // now $a = "hello world"
"$key=$value$ipn_passphrase"; is called an in-place variable substitution in PHP. You can check the PHP Doc for more. You can simply consider it as the value $key, $values and $ipn_passphrase is replaced by the values of those variables accordingly and it forms a new string variable $sha_sign.
$sha_sign = strtoupper(hash("sha512", $sha_string)); is a simple statement where you pass the algorithm sha512 and $sha_string to the function hash() and store the result back in $sha_string variable.
I wrote this code:
$userAddresses = $database->getUsers("SELECT * FROM Users");
$address = array();
foreach($userAddresses as $user){
array_push($address, array("address"=> $user['address'],
"zipcode" => $user['zipcode']));
}
$locations = array(
"locations" => $address
);
$jsonLocations = json_encode($locations);
This code returns this json object:
{"locations":[
{"address":"Sneekermeer 25","zipcode":"2993 RL"},
{"address":"Boeier 13","zipcode":"2992 AK"}]}
I want to get the length of this array inside JavaScript. So I did this:
var address = '<?php echo $jsonLocations ?>';
After that I called console.log(address.length); to check the length but some how it counts all the chars (108 I think) in the address variable and returns that as length. address.locations.length also doesn't work.
Could someone help me out?
You can use JSON.parse()
var address = JSON.parse('<?php echo $jsonLocations ?>');
console.log(address.length); // will give you length;
Thats because the string needs to be decoded to an object. You can do this one of two ways.
Non recommended:
var address = <?= $jsonLocations ?>;
Or more correctly and safer:
var address = JSON.parse('<?= addslashes(json_encode($jsonLocations)) ?>');
Do not forget the call to addslashes to prevent any single quotes in your array from breaking the javascript string.
You can either remove the quotes around var address = '<?php echo $jsonLocations ?>'; (i.e var address = <?php echo $jsonLocations ?>;) or use JSON.parse to parse it as a string to an object.
I have tried the below and its working
var address = '{"locations":[{"address":"Sneekermeer 25","zipcode":"2993 RL"},{"address":"Boeier 13","zipcode":"2992 AK"}]}';
address = JSON.parse(address);
console.log(address.locations.length);
I stored a Javascript value to a PHP variable. When I use var_dump to print it, var_dump returns int(0). It should display int(10). I am using this code:
<script type="text/javascript">
var a = "Hello world: 12345";
var b = a.replace ( /[^\d.]/g, '' );
</script>
<?php
$identity = '<script type="text/javascript">document.write(b)</script>';
var_dump($identity);
echo "<br/>";
$identity = preg_replace('/[^\d]/', '', $identity ); //removes everything except digits
$ord = (int)$identity;
var_dump($ord);
?>
Where have I gone wrong?
Where have i gone wrong ?
JavaScript code doesn't evaluate inside a php script, pretty basic.
You're trying to convert a string to int but php won't allow you to do that when the string contains letters, or anything different from digits.
If you use:
$identity = '<script type="text/javascript">document.write(10)</script>';
$identity = preg_replace('/[^\d]/', '', $identity ); //removes everything except digits
$ord = (int)$identity;
var_dump($ord);
php will convert the string to int without errors.
I have problem when I want to separate my string in JavaScript, this is my code :
var str= 'hello.json';
str.slice(0,4); //output hello
str.slice(6,9); //output json
the problem is when i want to slice second string ('json') I should create another slice too.
I want to make this code more simple , is there any function in JavaScript like explode function in php ?
You can use split()
var str = 'hello.json';
var res = str.split('.');
document.write(res[0] + ' ' + res[1])
or use substring() and indexOf()
var str = 'hello.json';
document.write(
str.substring(0, str.indexOf('.')) + ' ' +
str.substring(str.indexOf('.') + 1)
)
The php example for explode:
$pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(":", $data);
echo $user; // foo
echo $pass; // *
The Javascript equivalent (ES2015 style):
//Example 1
let pizza = "piece1 piece2 piece3 piece4 piece5 piece6";
let pieces = pizza.split(" ");
console.log(pieces[0]);
console.log(pieces[1]);
//Example 2
let data = "foo:*:1023:1000::/home/foo:/bin/sh";
let user, pass, uid, gid, gecos, home, shell;
[user, pass, uid, gid, gecos, home, ...shell] = data.split(":");
console.log(user);
console.log(pass);