How to get the laravel route name on js - javascript

Hello guys I have search and I didnt find anything, do you know how to get a laravel route name on js?
For example on php we can do $name = Route::currentRouteName();

In your layout.blade.php
<body data-page="{{ Route::currentRouteName() }}">
#yield('content')
<script>
var currentRouteName = document.body.dataset.page;
</script>
</body>
If you for some reason don't like injecting stuff in your DOM just to read it with JavaScript, you can do something else:
routes/web.php
Route::get('your-route', function() {
return response()
->view('your-view', compact('your-data'))
->header('route-name', 'your-route');
})->name('your-route');
your-view.blade.php
var req = fetch(document.location, {
'method': 'OPTIONS'
}).then((res) => alert(res.headers.get('route-name')));

Take a look at Ziggy, this npm package helps to integrate Laravel named routes with your frontend, with it you can easely get current route name and even acces routes for all your application endpoint just like you would do with Laravel:
https://github.com/tighten/ziggy
Examples From the Documentation:
//app.js
//get current route name
// Route called 'events.index', with URI '/events'
// Current window URL is https://ziggy.test/events
route().current(); // 'events.index'
// routes/web.php
Route::get('posts/{post}', fn (Request $request, Post $post) => /* ... */)->name('posts.show');
// app.js
route('posts.show', 1); // 'https://ziggy.test/de/posts/1'

Related

Check if the value of the local storage is equal or not to that of a Php variable

hello I have this php file with the name ** request.php ** that has this Code:
<?php
$Password_user = 'AIzaSyA';
?>
and I have a Index.html file, and I also have a Local Storage with that name user_pass so I created a variable with the name get_spass that looks like this:
var get_spass= localStorage.getItem('user_pass');
so how can i create a request in Ajax that is able to check if the value of the Storage location is equal or not gives it Variable ** Password_user of request.php?
You have to change your php file to:
<?php
$Password_user = 'AIzaSyA';
echo $Password_user;
?>
In your html file you can fetch the file and check the password value with this code:
var get_spass= localStorage.getItem('user_pass');
var passIsCorrect = checkPassword(get_spass);
if (passIsCorrect) {
//do stuff...
}
async function checkPassword(get_spass) {
const passwordPhp = await fetch("request.php");
if (get_spass === passwordPhp) {
return true;
}
return false;
}
Note that everyone can get the request.php content. If the password need to be secret you have to implement some sort of authentication to assure the request.php file can be read only by authorized users or person.

Pass data between two HTML pages (Google Apps Script)

I'm trying to pass var 'id' from the page 'a.html' to 'b.html'. The var content comes from 'code.gs' as below:
code.gs
function data(){
var id = 1;
return id;
}
Next, I get this var and I show it in 'a.html':
a.html
<?
var id = data();
?>
<h1><?= id ?></h1>
Go to B.html
By clicking 'Go to B.html', the system directs the user to there. I need to bring the same value of var 'id' from the page 'a.html' to 'b.html'.
Ps: searching for a little, I saw that there's a kind to send this var by the command 'localStorage', but it's not working for me. :(
Can anybody help me?
Use localstorage
a.html
localStorage.setItem('id',1)
b.html
var id = localStorage.getItem('id')
the other way is to put it in a js file and import it in both html
Storing & Retrieving html data on the server
Client Side JavaScript:
<script>
function saveId(v) {
google.script.run.saveKeyValue({key:'id',value:v});
}
function getId() {
google.script.run
.withSuccessHandler(function(v){
alert('The value is ' + v );
})
.getKeyValue('id');
}
</script>
Server Side Google Apps Script:
function saveKeyValue(obj) {
PropertiesService.getScriptProperties().setProperty(obj.key,obj.value);
}
function getKeyValue(key) {
return PropertiesService.getScriptProperties().getProperty(key);
}
You could also replace PropertiesService with CacheService.
Client To Server Communications
Properties Service

Flaskr url_for with javascript variable as parameters is not working to python

I'm trying to use flask with url_for. The problem is that when I try to launch an alert with the value of the javascript variable everything seems ok, but when I try to launch a alert with the url_for the content of the variable is not printed. What I'm doing wrong? or What is missing in my code?
How can I pass a JavaScript variable into the url_for function?
html code:
<a class="dissable_user_btn" data-user_id="{{user.id}}" href="#" title="Change Status"><i class="fa fa-plug"></i>
</a>
JS Code:
<script type="text/javascript">
$(document).ready(function(){
$('.dissable_user_btn').click(function( event ) {
var user_id = $(this).data("user_id")
alert(user_id) //everything ok
alert ('{{url_for('.dissable', _id=user_id)}}'); //dont print the valur of user_id
</script>
Short answer: you can't. Flask & Jinja2 render the template on the server side (e.g. Flask is translating all of the {{ }} stuff before it sends the HTML to the web browser).
For a URL like this where you're including a variable as part of the path you'd need to build this manually in javascript. If this is an XHR endpoint I'd recommend using GET/POST to transfer the values to the server as a better best practice than constructing the URL this way. This way you can use Jinja:
$(document).ready(function(){
var baseUrl = "{{ url_for('disable') }}";
$('.dissable_user_btn').click(function(event) {
var user_id = $(this).data("user_id");
// first part = url to send data
// second part = info to send as query string (url?user=user_id)
// third parameter = function to handle response from server
$.getJSON(baseUrl, {user: user_id}, function(response) {
console.log(response);
});
});
});
I found another solution for this. My problem started when I needed to pass a variable with space.
First I created a function to remove trailing and leading spaces
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');}
After that, I used the function and encoded the URL
<script type="text/javascript">
$(document).ready(function(){
$('.dissable_user_btn').click(function( event ) {
var user_id = $(this).data("user_id")
alert(user_id)
user_id = strip(user_id).replace(" ","%20");
alert ('{{url_for('.dissable', _id='user_id')}}.replace('user_id',user_id);
</script>
It worked pretty nice for me!
This is how I applied to my problem
<script>
function strip(str) {
return str.replace(/^\s+|\s+$/g, '');}
$(document).ready(function() {
$('#exportcountry').click(function() {
var elemento = document.getElementById("countryexportbtn");
var country = strip(elemento.textContent).replace(" ","%20");
$('#exportevent').load("{{ url_for('get_events',country = 'pais') }}".replace('pais',country));
});
});
</script>

Is there a very simple way to update a page in Perl Dancer using jQuery/AJAX?

I have the following code in my main Dancer app .pm:
package Deadlands;
use Dancer ':syntax';
use Dice;
our $VERSION = '0.1';
get '/' => sub {
my ($dieQty, $dieType, $bonus);
my $button = param('button');
$dieQty = param('dieQty');
$dieType = param('dieType');
$bonus = param('bonus');
if (defined $dieQty && defined $dieType) {
return Dice::Dice->new(dieType => $dieType, dieQty => $dieQty, bonus => $bonus)->getStandardResult();
}
template 'index';
};
true;
Here is my JavaScript:
$(document).ready(function() {
$('#standardRoll').click(function() {
$.get("/lib/Deadlands.pm", { button: '1', dieType: $("#dieType").val(), dieQty: $("#dieQty").val(), bonus: $("#bonus").val() }, processData);
function processData(data) {
$("#result").html(data);
}
});
});
I have a div in my web page called result that I want to be updated with the die roll result from Perl. Dancer keeps coming back with a 404 error in the command window when I push the submit button.
/lib/Deadlands.pm needs to be the URL of your route (probably / in this case), not the filesystem path of your Perl module.
Your AJAX request needs to point to a URL that actually exists, not a filename that has nothing to do with the web. Looks like $.get('/', ...) would do in this case.

Why is the URL 404 not found with Django?

I have written a Django script that runs a Python parser to web s*e. I am sending the request to the Django script via AJAX. However, when the Ajax runs, it comes back as 404 not found for the URL. Why is this happening?
My code is below:
Ajax (with jQuery):
//send a `post` request up to AWS, and then
//insert the data into the paths
$.post('/ca', function(data){
//evaluate the JSON
data = eval ("(" + data + ")");
//insert the vars into the DOM
var contentOne;
contentOne = data.bridge_time;
contentOne += 'min delay';
$('#timeone').html(contentOne);
var contentTwo;
contentTwo = data.tunnel_time;
contentTwo += 'min delay';
$('#timetwo').html(contentTwo);
//if this falls through, push an error.
var tunnel_time = data.tunnel_time;
var bridge_time = data.bridge_time;
var tunnel = document.getElementById('tunnel');
var bridge = document.getElementById('bridge');
var tunnelText = document.getElementById('timeone');
var bridgeText = document.getElementById('timetwo');
//algo for the changing icons. Kudos to Vito
if(tunnel_time<bridge_time){
tunnel.src="tunnel3.png";
bridge.src="bridge2r.png";
}else if( bridge_time<tunnel_time){
bridge.src="bridge21.png";
tunnel.src="tunnel2r.png";
}else{
bridge.src="bridge2n.png";
tunnel.src="tunnel2g.png";
}
$.fail(function() {
alert("We're sorry. We are having an error. Check back later.");
});
});
My urls.py:
from django.conf.urls.defaults import *
from views import views
urlpatterns = patterns('',
(r'^/us', views.american_time),
(r'^/ca', views.canadian_time),
)
My urls.py and my views.py are in the same folder, if that makes any difference. They are just titled views.py and urls.py. Thank you!
Try
from django.conf.urls.defaults import *
from views import views
urlpatterns = patterns('',
(r'^/us/$', views.american_time),
(r'^/ca/$', views.canadian_time),
)
Also you have to add the trailing slash in your JavaScript.
I just resolved this: there was an error in my urls.py. My system was having trouble with the .defaults that is was supposed to import from. Also, I didn't have a Django project set up, so It wouldn't import the views.

Categories

Resources