JS file couldnt access laravel variable - javascript

I am passing an array from my controller.
Now, I put this code inside my Laravel 6.* Blade View,
<script>
var app = <?php echo json_encode($array); ?>;
</script>
This works just fine.
However, if I put the same piece of line (or any of the following lines) inside my custom app.js file, this doesn't work.
var app = <?php echo json_encode($array); ?>;
var app = {!! json_encode($array->toArray()) !!};
var app = '<?php echo json_encode($array); ?>';
Each time I am getting an invalid syntax error.
I am not sure if this is a valid ques for StackOverflow, but I have already tried all other similar solutions and none of them is working for me.

That's because you have no access to write php code in js file or you can use Ajax to get php variable.
In your statement if you put your code in your blade file before including app.js file you will be able to get app variable in your js file.
Ex:
<script>
var app = #json($array)
</script>
<script src="path to your app js file"></script>
And now in your app js file if you print app variable you will see the result
console.log(app); in your app.js file

One thing you can do is to move javascript to template and create route to it as:
Route::get('/app.js', function () {
$result = view('app', ['array' => [1,2,3,5,8]]);
return Response::make($result, 200)
->header('Content-Type', 'application/javascript');
});
Then in resouces\views
<script>
var app = <?php echo json_encode($array); ?>;
</script>
Common way of doing this is to create end point that returns json only and then use e.g. fetch api or axios library on client side.
Something like this:
Route::get('/app', function () {
return [1,2,3,5,8];
});
<script>
fetch(endPointUrl("/app")).then(response => {
console.log(response);
}).catch(error => {
console.error(error);
})
</script>
Where endPointUrl is just a helper function that creates full url.

Related

How to write get text in grid.js using php tag

I want to write get-text for language conversion with the help of php tag.
I try to use gettext php tag in grid.js but it's not working for language translation.
I have try this code for use gettext in generate_grid.js
Code:
word_hello = "<?php echo gettext("hello"); ?>"
alert(word_hello);
Using this code grid loading stopped so how I can use get text in jquery.
Using gettext flexigrid load without any error.
We have tried to another solution like call javascript function to header.php file like below.
word_hello = header_fcuntion('hello');
alert(word_hello);
In header.php we do like this.
function header_fcuntion(txt){
var new_txt = "<?php echo gettext('"+txt+"'); ?>";
alert(new_txt);//Response in English Language hello
}
But we try like put static hello that time it alert in converted language in header.php file.
function header_fcuntion(txt){
var new_txt = "<?php echo gettext('hello'); ?>";
alert(new_txt);//Response in Convert Language hello
}
So is there anything wrong to call function in php file?

How to pass string from php to js

For example i have test.php thats receiving some data based on GET method.
Result is defined as string, for example $kript.
Now i need to pass that specific string value to external js file (main.js) to use it as data insessionStorage.
PHP:
How to i pass php string value to external js?
<?php
if(isset($_GET["token"]) && isset($_GET["r"]))
{
$token = $_GET["token"];
$r = $_GET["r"];
$kript = 'r='. $r .';token=' . $token;
}
?>
Ok, i got it.
All i needed to do in test.php is:
<script type="text/javascript">var stoken2 = "<?= $kript ?>";</script
<script src="main.js" type="text/javascript"></script>
And in main.js i can use stoken2 as value of $kript from php.

How to Pass PHP Session Variable to external JS file in Symfony

Currently I am working in One PHP Symfony Project Regarding the Performance Evaluation of an Employee.
So I need to know how we can get PHP session variable of an employee (Employee Role) Please see the php file ( $role = $_SESSION['empRole']; ) to an external js file.(js file also attached). I am using PHP Symfony framework.
Actually I need to check who is logged in to the website.if it is admin/core members / Hr.
I need to apply validation to some fileds only when the Coremembers login the website.
Here is the code section that I need to pass $role to External JS file(in pastebin)
public function executeIndex(sfWebRequest $request) {
if (isset($_SESSION['empId'])) {
$role = $_SESSION['empRole'];
if ($role == "admin") {
$empId = $this->getUser()->getAttribute('empId');
$team_members = GroupwareEmployeesPeer::getAllSubordinatesId($empId`enter code here`);
$nc = new Criteria();
$nc->add(PeD`enter code here`ates`enter code here`Peer::NAME, 'Dashboard');
$resultset = PeDatesPeer::doSelect($nc);
So Can you guys give me a solution regarding this, since I am stuck with this for a long time.
Please see thepastebin code for php and external js file.
https://pastebin.com/kbkLjSFa - PHP File.
https://pastebin.com/M60Rg64U - JS file
Yes you can get the php variable into the js file.
Method I:
Rename your .js file to .js.php and pass the php variable as a query string to this file where you link this file in your page.
So, if you have some test.js file, rename it to test.js.php and use it in your page like this
<script src="test.js.php?session_var=<?= $your_var_here;?>&any_var=<?= $any_php_var;?>"></script>
And in your js file, retrieve the values from query string parameters
So inside test.js.php, you can simply
var some_var = "<?= $_GET['session_var']";
var any_var = "<?= $_GET['any_var'];?>";
//rest of your logic goes here
Method II:
Use an AJAX request.
var some_var, another_var;
$.ajax({
url : '/url-which-returns-session-vars', //return the session data in json from this url
asnyc : false,
dataType : 'json',
success : function(res){
some_var = res.some_var;
another_var = res.another_var;
}
});
//rest of the logic goes here.
Both of these methods work. But I prefer the first method, since I don't have to write extra code.
Edit:
Suppose the response of the ajax call looks like this
{
some_var : 'value here',
another_var : 'another value here'
}
So res in the success function argument contains this response and since the response is a JSON you can access these values using the . notation.
Thus,
some_var = res.some_var;
another_var = res.another_var;
and since these variables are global variables, you can use them anywhere in your code in this file.
?> <script> var php_variable = '<?php $variable ?>'; </script> <?php
Global variable should be declared before external js file include . in js file access it using this variable name php_variable
After the above code . jquery external file should be included here
<script src="external.js" ></script>
external.js
consol.log(php_variable);

php json_encode is not working in gulp

I am using laravel 5.2 , I am using like below
var data = <?php json_encode($data['value']); ?>
when I am using JavaScript code below in the blade file, then its working fine, but when I am using the code as a separate file and trying to gulp that , then it is not working , my data is not loading
var data = "<?=json_encode($data['value']);?>"
or
var data = "<?php echo json_encode($data['value']);?>"
You are not echoing out the value, your var is null
Other mate already provided the correct solution specially #user1779617, now i am explaining with a basic example:
<?
// a simple array
$data['value'] = array(1=>'test');
$encodedData = json_encode($data['value']);
?>
<script type="text/javascript">
var data = <?=$encodedData?>;
console.log(data); // Object { 1="test"}
</script>
If you have posted original code than you have an error in your javascript, you miss the ending termination semicolon (;) plus you need to echo the result as other mentioned in answers.
UPDATE 1
if you are still facing the same issue than use JSON.parse in javascript
<script type="text/javascript">
var data = JSON.parse( ' <?=$encodedData?>');
console.log(data); // Object { 1="test"}
</script>

Run JavaScript from PHP from Ajax

Is it possible to run a JavaScript function from PHP using an Ajax call.
For example, if I have a html page in php with an ajax call. The ajax post gets sent to a php engine:
index.php
<script>
Ajax.post('http://example.com/ajaxEngine.php', { data: "someData" });
</script>
Then in the PHP engine, can I run a JavaScript function like this:
ajaxEngine.php
<?php
$data = $_POST['data'];
?>
<script type="text/javascript">
var php_var = "<?php echo data ?>";
function doSomething(php_var) {
// do something with data
}
</script>
Lastly, If the JavaScript function needs to return a value, how would you then transfer that back to php? Could I post to the same page and then get it as a variable with PHP?
Short answer: No.
Your code in ajaxEngine.php would just output that snippet of javascript. This will be transfered back to your page, so you could insert it into a script tag or eval it, if you like it to execute. But this would then happen on the client side not on your server. The script would have the dynamic data from the php, though. So if this is everything you need, it would work that way.
Beware: That would NOT hide your script. It would be visible for any client.
Try this function
function includetext(text,onlyone)
{
var d=document.createElement('script');
if(onlyone)
{
var ds=document.getElementById('onlyonesscript');
if(ds)
removeElement(ds);
d.id='onlyonesscript';
}
d.innerHTML=text;
document.body.appendChild(d);
}
text - returing text of script from ajax.
onlyone use for just one script node, this will help you.
ajaxEngine.php
<?php
$data = $_POST['data'];
?>
var php_var = "<?php echo data ?>";
// do something with data

Categories