I have a Laravel web app and want to access my Laravel Helper from any .js file.
In normally I accessed helper from script in blade.php file like this:-
<script>
function getSiteSettings() {
return JSON.parse('<?php echo json_encode(Helper::getSettings()) ?>');
}
</script>
But I want to access this from my script.js file. Is it possible?
I have tried with localStorage and get it very easily but problem is, in site settings have some secured data.
And if possible to hide localStorage data then my problem will be solved.
I found the answer. Basically, there is no direct way to write PHP code in the .js file. Here is 3 short way to get PHP/Laravel variable or Laravel Helper.
Solution 1. Call an ajax and get the return the value from js and use it as needed.
$(function() {
// ajax call
});
Solution 2. Any Laravel Helper/Var can be accessible from a blade file, like this:
<script>
let name = "{{ \Helper::get_name() }}";
</script>
and use this name anywhere in js.
Solution 3. The last and best way which I have been using is:
Add the external script in the blade and add a getter and setter method into the script so that you can set the value from the blade file inside the js.
// in external/script.js script
var GetLaravelHelper = function () {
let options = {
name_from_laravel : ''
}
return {
init: function(){
// code for on load
},
set_options: function(data){
Object.assign( options, data );
},
get_options: function(){
return options;
}
}
}();
window.GetLaravelHelper = GetLaravelHelper; // You can get acces this GetLaravelHelper into balde file where you imort this js
document.onload(function(){
GetLaravelHelper.init();
})
Then in blade, you can set any value into the Object like this:
<script src="external/script.js"></script>
<script>
GetLaravelHelper.set_options({
name_from_laravel: "{{ config('app.name') }}", // or anything from laravel/php
})
</script>
Hope it will help you a lot. Happy Coding <3
I think your best bet is to do what you're doing right now.
Or, Create a resource endpoint that can return JSON of these settings on page load in your script.js file:
// script.js
document.addEventListener("DOMContentLoaded", function() {
// make an ajax request here and load your setting in a js variable
});
// if using jquery
$(function() {
// make an $.ajax request here and load your setting in a js
})
The easiest solution will be call an api using Ajax or Axios(is using vue) inside the getSiteSettings function and in the response of the api you return the data.
Related
I want to pass data to the js file. however cant get is to work.
js='article.js';
function loadjs(js){
$.get(js,{ name: "test" });
}
article.js
alert(name);
if i do alert('test'); i get a response from the file so i know it works.
also cant use globals.
is there a simple way to send the data to the file and show it?
EDIT to clarify
(yes i can use angelar but i dont)
Onload it triggers 'pagina' with all short of variables. (its dynamic).
all the 'php/html' files are loaded.
and you get what you can see in the link. example
hoverever when i click on a row i want function pagina(); to load the content of the row so far so good. however to show the data that i want. I want to send a ID to the JS file and use a $.post (php) in the JS file to get data json. if i set a ID in $.post id=1 directly its works.
so to not let it be more confusing. i want to send a id to a js file JS $.get or $.getScript.
function pagina(menu,frame,vars,crum,js,togglezoeken,voorwaarden){
'use strict';
if(!menu){$('#frame').show();}
if(menu){
$('#loader-zoeken').hide();
$('#loader-bijwerken').hide();
$('#loader-pagina').show();
$('#menu').hide();
$('#frame').empty();
$('#menu').load(menu+vars,{noncache: new Date().getTime()}, function() {$('#menu').foundation();});}
if(crum==1){$('#breadcrumbs').load('/opbouw/frames/breadcrumbs.php?'+vars,{noncache: new Date().getTime()}, function() {});}
$('#frame').load(frame+vars+'&crum='+crum,{noncache: new Date().getTime()}, function() {
if(togglezoeken){$('#uitgebreidzoeken').toggle();}
if(crum==1){$('#breadcrumbs').show();}else{$('#breadcrumbs').hide();}
if(js){
$.get( js,{ name: "test" });
}
else{
$('#loader-pagina').hide();
$('#menu').show();
$('#frame').show();
}
//if(voorwaarden==1){popup('/opbouw/frames/voorwaarden.php','','/opbouw/js/voorwaarden.js');}
$('#frame').foundation();
});
}
You can't do it that way. $.get is used for AJAX/HTTP(s) requests and your file in that way won't accept the data sent to it.
To achive this you have to use a server-side endpoint on your article.js.
Lets say:
function loadjs( js ) {
$.get(js, { name: "test" });
}
And you make a call of loadjs function:
loadjs('article.js');
On your server you have to have an server-side endpoint directing to a request: /article.js:
You can achieve this by using PHP or express for node.js:
router.get('article.js', function(req, res, next) {
res.json( req.query.data );
});
Or in PHP (note in Apache you have to use mod_rewrite and enable it with .htaccess or in your virtual host configuration):
$req = $_SERVER['REQUEST_URI'];
if($req == 'article.js') {
echo json_encode(array('data' => $_GET['data']));
exit(0); // end the script here
}
In either way used from above you have effectivelly sent a data to your script / endpoint and you can handle it further.
Although your loadjs function just sends a request and doesn't handle a response, you can do the following with a callback function in $.get:
$.get(js, { name: "test" }, function(data) {
alert(data); // you will alert the data from the JSON response
});
Sadly, you haven't described what you actually need and this is as far as I can help you with so far.
the following JavaScript is working perfect in side the test.blad.php file
but when i made external test.js file at the browser i get some thing like
http://localhost:8000/%7B%7Burl('/barcode')%7D%7D?j_barcode=112234
instead of
http://localhost:8000/barcode?j_barcode=112234
the code in test.js file is :
$(document).ready(function(){
$('#barcode').keyup(function(event){
if(event.keyCode == 13){
var j_barcode = $('#barcode').val();
$.get("{{url('/barcode')}}", {j_barcode:j_barcode}, function(data) {
console.log(data) ;
//success data
$.each(data,function(i, obj){
document.getElementById("item").value =obj.itemName;
document.getElementById("itemId").value = obj.id;
console.log(data) ;
});
});
}
});
});
and the route.php
Route::get('/barcode' , 'testController#getBarcode');
at last i decleared the test.js in test.blade.php as
<script type="text/javascript" src="/hsm/js/test.js" ></script>
You can not use blade or php code inside files which are not interpreted by php.
The simplest way, as already suggested by #dev-null is to hardcode that url. But that generates problems when you're on a sub page like "/articles/2015" since it will then try to call "/articles/barcode".
You will have to find a way to pass the site root url to your js file.
The way I always solve this is to define a global variable in my main template with all the php interpreted values required in js.
var App = {
root: '{{ url('/barcode') }}',
texts: {
// some translated texts for js
}
};
That way you can easily access it in all your js files:
$.get(App.root + '/barcode')...
Note: If you use named routes like me you will have to add each URL separately instead of just the root.
After some research, this is my solution:
Step 1. In the blade file, add a yielded section, immediately (just to keep your scripts neat) before referring to external .js file, do something like following,
#section('js_after')
<script>let dataUrl = "{{ route('subcat') }}"</script>
<!--Then external javascript file -->
<script src="{{ asset('js/pages/somescript.js ') }}"></script>
#endsection
Step 2. In your somescript.js file, you may refer and manipulate with this pre-defined variable dataUrl, such as,
var url = dataUrl+'?someParam='+id
$.get(url)
reference: https://stackoverflow.com/a/59994382/3107052
This is a complex issue and I am wondering if this is more related with JSONP (JSON + padding) or not.
So there is a file called example.php
<script src="jquery.js"</script>
<script src="example.js" onload="getInfo();"></script>
<p class="one"></p>
Now in the example.js file, I use the getJSON method:
$(document).ready(function() {
function getInfo() {
$.getJSON("URL", function(data) {
var name = [parses through the json data];
$("p.one").html(name);
This does't work however if it is not involving an external JSON file it works.
Here is a previous question that was answered: Best way to access external JavaScript file and place contents in div?
Curious to know if anyone else has faced this problem and I haven't been able to find anything by Google or on StackOverflow on this.
Change your script calling syntax as follows. Remove onload attribue. There is no attribute onload for script tag
<script src="example.js"></script>
And, your example.js file look like this. You may call the getInfo() method in that file also
$(document).ready(function() {
function getInfo() {
$.getJSON("URL", function(data) {
var name = [parses through the json data];
$("p.one").html(name);
});
}
getInfo();
});
At my Ajax response there is two variable: js, html.
The js variable contents Javascript in tag script: //Some code
And html contents HTML template.
How I can execute js code for html template from the successful response Ajax?
I tried this solution:
$('head').append(response.js); // not works
The full Ajax request:
getFormShare: function(type){
var posting = $.post('/share/getFormShare', { type : type } );
posting.done(function( response ) {
response = $.parseJSON(response);
$("head").append(response.js);
$('.ShareBlock #block').html(response.html).show();
initFileUpload(config);
initEditor();
});
}
The PHP side:
$js = $this->listdata->WrapperJavaScript($specialization, array('name_field' => 'type[]', 'tab' =>'tab', 'div_element' => '.specMain', 'label' => 'Category', 'autosearch' => 'true'));
$html = $this->load->view('social/forms/video', $this->data, true);
echo json_encode(array('html' => $html, 'js' => $js)); die();
You can use .getScript() and run your code after it loads:
$.getScript("my_lovely_script.js", function(){
alert("Script loaded and executed.");
// here you can use anything you defined in the loaded script
});
You can see a better explanation here: How do I include a JavaScript file in another JavaScript file?
Edit:
Since you're returning actual javascript and would like to execute it, you can simply do this in your ajax response:
$.get(url,function(data){ $("body").append(data); });
Edit:
And with help from Mike's answer, you can use eval() to run the script if you don't have script tags in your response. His answer gives more info on this.
You can utilize javascript's eval to run string as code.
Keep in mind your string needs to be pure JS, no html or other elements to it.
example
eval("function foo() {console.log('bar');}");
//this call will create/instantiate a function called foo
As the title says, I am trying to dynamically load content in a view using ajax requests. I know this can be done if you are using html elements e.g. ("#div_place").html(<p>...). The problem lies when I would like to load some php/blade objects into a div for instance. Is this possible or is there a different way to go about achieving the result I want.
This is pretty straightforward. Assuming you're using jQuery...
create a route that will respond to the AJAX call and return an HTML fragment
Route::get('test', function(){
// this returns the contents of the rendered template to the client as a string
return View::make("mytemplate")
->with("value", "something")
->render();
});
in your javascript:
$.get(
"test",
function (data) {
$("#my-content-div").html(data);
}
);
After some digging some more I found this which helped me to solve the problem.
You have to use the .load("url/page/...") via jquery and then set a route in the routes.php file that displays a view with the data that needs to be loaded e.g.
Route::get('/url/page/...', function(){
return View::make('test');
});
This returns the necessary php code which needed to be loaded dynamically, cheers.