How can I access PHP array inside my Javascript? - javascript

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.

Related

Substring js in php

enter code here
I'm trying to get out ID from link:
www.imdb.com/title/tt5807628/ - > tt5807628
My code in javascript:
var str = "www.imdb.com/title/tt5807628/";
var n = str.search("e/tt");
var res = str.substring(n+2, n+30);
var ukos = res.search("/");
var last = res.substring(0, ukos);
I would like to get the same effect in PHP, how to do it?
Based off my comment here, the following code will just give you the ID:
$id = explode("/", "www.imdb.com/title/tt5807628/")[2];
We use the explode(delimiter, string) function here to break the string at each of the slashes, which creates an index of strings that looks like this:
array (
0 => "www.imdb.com"
1 => "title"
2 => "tt5707627"
)
So, as you can see array index 2 is our ID, so we select that after we break the string (which is the [2] at the end of the variable declaration), leaving us with a variable $id that contains just the ID from the link.
edit:
You could also use parse_url before the explode, just to ensure that
you dont run into http(s):// if the link changes due to user input.
- Keja
$id = explode("/", parse_url("www.imdb.com/title/tt5807628/", PHP_URL_PATH))[2];
With explode function then you can see each part by looping through the array
$varArray = explode( '/', $var );
You can use preg_match as well:
preg_match('~www\.imdb\.com/title/([^/]*)/~', 'www.imdb.com/title/tt5807628/', $matches);
$id = $matches[1];

Getting error in type conversion php?

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.

How to access JSON array in Javascript

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.

Save javascript value as plaintext in DB

This is the problem I get, for example, when an user inputs <script>top.location.href=’http://www.google.nl’;</script>
I want my application to echo it as plain text. Now, this actually works with
htmlspecialchars()
This example works for me:
$test = "<script>top.location.href=’http://www.google.nl’;</script>";
echo htmlspecialchars($test);
But, when the user submits the form, the data goes to my DB and then returns to a 'dashboard'.
The value is now ''.
Is there a way how I can save the data safe into my DB?
I add the values into the DB for my C# application in this way via SDK:
$onderwerp = htmlspecialchars(stripslashes(trim($_POST['onderwerp'])), ENT_QUOTES,'UTF-8',true);
$omschrijving = htmlspecialchars(stripslashes(trim($_POST['omschrijving'])), ENT_QUOTES,'UTF-8',true);
$im = array('description' => mysql_real_escape_string($onderwerp),
'message' => mysql_real_escape_string($omschrijving) ,
'relation' => $_SESSION['username'],
'messageType' => 70,
'documentName' => $_FILES["file"]["name"],
'documentData' => base64_encode(file_get_contents($_FILES["file"]["tmp_name"])));
$imresponse = $wcfclient->CreateInboundMessage($im);
echo $imresponse->CreateInboundMessageResult;
And then call them at my dashboard in this way:
$roc = array('relation' => $_SESSION['username']);
$rocresponse = $wcfclient->ReadOpenCalls($roc);
foreach ($rocresponse->ReadOpenCallsResult as $key => $calls){
echo $calls->Description;
}
can you please check mysql-real-escape-string
mysql_real_escape_string() :
The mysql_real_escape_string() function escapes special characters in a string for use in an SQL statement
Also CHeck SQL Inject :SQL Injection
Example
<?php
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
$item = "Zak's and Derick's Laptop";
$escaped_item = mysql_real_escape_string($item);
printf ("Escaped string: %s\n", $escaped_item);
?>
Ouput :
Escaped string: Zak\'s and Derick\'s Laptop
Yes, read about mysqli_real_escape_string.

How to seperate the datas when jquery get them from mysql?

ChkNewRspLive.php
<?php
$query3 = "SELECT msgid, id FROM rspnotificationlive WHERE username='{$username1}' ORDER BY id LIMIT 99";
$result3 = mysql_query($query3,$connection) or die (mysql_error());
confirm_query($result3);
$numrspmsg = mysql_num_rows($result3);
echo $numrspmsg . "|";
while($userinfo3 = mysql_fetch_array($result3)){
$rspmsgid= $userinfo3['msgid'];
$msgid= $userinfo3['id'];
echo $rspmsgid . ", ";
}
?>
index.html
<script type="text/javascript">
$.get("ChkNewRspLive.php?username=" + username, function(newrspmsg){
var mySplitResult = newrspmsg.split("|");
var rspMsgCount = parseFloat(mySplitResult[0]);
var rspMsgids =(mySplitResult[1]);
var Msgids = ??//how to get this result from ChkNewRspLive.php ?
});
</script>
As you can see, I used "|" to separate $rspmsgid and $numrspmsg. I also use "," to separate multiple $rspmsgid. How if I want to separate another data $msgid? How to do that?
If I use | to separate $rspmsgid and $msgid, there will be many sign of | because they both are in the while loop.
JSON encode your content.
In your php, change your code to something like:
$json = array();
while($userinfo3 = mysql_fetch_array($result3)){
$rspmsgid= $userinfo3['msgid'];
$msgid= $userinfo3['id'];
$json[] = array($rspmsgid,$msgid);
}
echo json_encode($json);
and then use $.getJson in your javascript.
You won't have to define the number of mysql_rows either, as you can just get that in javascript by using .length on the json data.
edit and escape your string before using it in your SQL!
You are already using the .split() method to seperate the other string. Apply it to the other part and let it split by ", " or just use another | instead of the , and you will have it split into three parts instead of two.
However I suggest you have a look at JSON. This should be the better solution if it gets more complicated.

Categories

Resources