getJSON url method doesn't work when called from external javascript - javascript

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();
});

Related

How can I access Laravel Helper from Javascript?

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.

How can i call a javascript function from a file for pug?

Heres my code but removed some changed code to something smaller!
Javascript code:
// /JS
function callme() {
var test = 1
alert(test);
}
Pug code:
// /first.pug
var funct = require('../JS');
button(onclick='clickme()') click
script.
function clickme() {ยจ
// trying to call callme function from my javascript file but i really dont know how.
callme();
}
Sorry about this question i dont use pug but this was already made with pug so i cannot go changing it since it has alot more code but didnt post all not needed code here.
Pug has no capability to directly run JavaScript. It is used to generate HTML.
You are already generating HTML with embedded client-side JavaScript.
You need to write the HTML to include the external JavaScript.
i.e. <script src="/url/to/JS.js"></script>
In Pug that would be:
script(src="/url/to/JS.js")
Make sure your HTTP server gives the JS a public URL!

MVC controller method not being triggered by jquery in the view

I have the following method in a controller called "ProductController":
public ActionResult LoadProducts(int prodID)
{
return View();
}
I'm trying to trigger it from a view cshtml page this way:
#section Scripts {
<script type="text/jscript">
$('#MyProducts').change(function () {
var selectedID = $(this).val();
$.get('/Product/LoadProducts/' + selectedID, function (data) {
window.alert(selectedID);
});
});
</script>
}
<div>
#using (Html.BeginForm("Update", "Product", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
#Html.DropDownList("MyProducts",
(IEnumerable<SelectListItem>)ViewBag.MyProducts as
IEnumerable<SelectListItem>, "Select")
}
</div>
The call to the jquery works when I change the value in the drop down, as I tested it via the popup box, but getting it to trigger the action method in the controller is not working.
Thanks.
In your controller, you can use HttpGetArribute to define the route. Without specifying the route, the parameter is considered as optional and it should be called as Product/LoadProducts?prodId=1. Example of HttpGetAttribute:
[HttpGet("[controller]\[action]\{prodId}")]
public ActionResult LoadProducts(int prodID)
{
return View();
}
set Url by Url.Action
var Url='#(Url.Action("ActionName","ConttrolerName"))';
and Put the variable name of the sent with the same variable received
SelectedID to ProdID
<script type="text/jscript">
$('#MyProducts').on("change",function () {
var Url='#(Url.Action("LoadProducts","Product"))';
var SelectedProdID = $(this).find("option:selected").val();
$.get( Url,{prodID:SelectedProdID}, function (data) {
window.alert(selectedID);
});
});
</script>
Suggestion: use script type="text/javascript". I am not an expert on which browsers support "jscript" but after 20 years of development I can assure you all browsers support javascript.
Also, I would discourage you from using the code which Farhad Bagherlo posted. If at all possible you should avoid using razor code inside your script tag because you may want to move this code into separate JS files or later on refactor to use TypeScript. Also, why invoke a method on the server to get an endpoint/url if you already know the path which is needed. seems wasteful. However, you could use the method he outlined to ensure that you are actually giving the correct URL. If his code works then what is the value of "Url"? (also, the client side standard for naming variables is camelCase, so url should be lower.)
If you are debugging your code and set a breakpoint in your controller. then you should be able to get it to break on that line by simply navigating to that route.
If you go to http://localhost:post/Product/LoadProducts/1 does it actually break on that line in Visual Studio?
Edit: #Transcendent is correct and would get my vote, need to understand how routing is defined vs arguments/parameters passed to the action method. Nice call Transcendent!
I agree with Collin on that using razor in your javascript marries them and that can be a pain if you try to split the js into its own file. I recently had to go through it.
Edit: This is just to show how to use Url.Action and still be able to separate js into a separate file by the use of data property in the div
What I suggest is doing something like:
#section Scripts {
<script type="text/javascript">
$('#MyProducts').change(function () {
var url = $('#mydiv').data('url') + '?prodId=' + selectedID;
var selectedID = $(this).val();
$.get(url, function (data) {
window.alert(selectedID);
});
});
</script>
}
<div id="mydiv" data-url="#(Url.Action("ActionName","ConttrolerName"))">
#using (Html.BeginForm("Update", "Product", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
#Html.DropDownList("MyProducts",
(IEnumerable<SelectListItem>)ViewBag.MyProducts as
IEnumerable<SelectListItem>, "Select")
}
</div>

Laravel 5 External JavaScript Files_ JavaScript stack

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

Javascript function not changing <pre> innerHTML?

So I have a simple setup going here where I load up a file (A blender .obj file) and display it. Then I call this function:
function parseFile(){
var fileText = $('#file').html();
var fileLine = fileText.split("\r\n");
$('#file').html(fileLine[5]);
}
Which should make it so it displays the 6th line of the file, but it still displays the whole file. How do I make it split the lines like they are in the actual file?
Edit: Just so everyone know's I'm loading the file like this: $('#file').load('model.obj');
The call to .load() is asynchronous. The method will return, but the content will be available somewhen in the future. You'll need to use a callback:
$('#file').load('model.obj', function(response, status) {
alert("Now the file is loaded");
parseFile();
});
alert("Loading the file just began, nothing available by now");
Or more narrative, using the deferred interface:
$('#file').load('model.obj').then(parseFile);
If you need/want to parse the server response anyway, it might be a better to use $.ajax() directly instead of loading it into a innerHTML and reading from there... You even could use a dedicated dataFilter for the blender.obj file type.
Maybe it is only a problem with '\n'
Try this :
var fileLine = fileText.split("\n");
Try wrapping your call like this $(parseFile()); and make sure your HTML actually contains an element with the id of file.

Categories

Resources