I want to insert a var declared in javascript into my path to redirect my page.
My code is:
var id = $(this).attr('data-id');
windows.location = {{ path("mylink", {id: id}) }};
But I can't know how can insert my var id into path, because when I try this I get error, I'm trying to parse this with +' myvar '+ so concatenating text but I can't.
How can I concatenate or add my var into path?
Thanks!
Because PHP is executed on server side, you need to bypass by this way:
var id = $(this).attr('data-id');
var path = {{ path("mylink", {id: 0420}) }};
windows.location = path.replace("0420", id);
There is a way to do this without having to use javascript replace function. However, it requires some work.
Create Twig extension to decode URL:
namespace AppBundle\Twig\Extension;
class UrlDecodeExtension extends \Twig_Extension
{
public function getFilters()
{
return array(
new \Twig_SimpleFilter('url_decode', array($this, 'UrlDecodeFilter'))
);
}
public function UrlDecodeFilter($url)
{
return urldecode($url);
}
public function getName()
{
return 'url_decode_extension';
}
}
Register your new extension:
url_decode_extension:
class: AppBundle\Twig\Extension\UrlDecodeExtension
tags:
- { name: twig.extension }
Finally, use it in your Twig template:
var id = $(this).attr('data-id');
windows.location = {{ path("mylink", {id: "%s"}) | url_decode | format('"+id+"') | raw }};
This is how it is going to render in the browser:
var id = $(this).attr('data-id');
window.location("/your/rendered/url/"+id+"");
You should really consider using FOSJsRoutingBundle. It is one of the most commonly used bundles. Its only purpose is to expose the routes you want to client side. Once installed, your code would be :
var id = $(this).attr('data-id');
windows.location = Routing.generate("mylink", {id: id});
Related
I have a python list called "devices" that looks something like this:
[{
'Version': 'V14E',
'DeviceID': 'e00fce68281671574f416a8c',
'TerminationDate': '2050-12-31',
'Latitude': 31.322139613573903,
'ActivationDate': '2021-01-04',
'Longitude': -101.93960164357534,
'DeviceName': 'Hans_Gruber-1'
}, {
'Version': 'V14E',
'DeviceID': 'e00fce68e1265e12e12fa02a',
'TerminationDate': '2050-12-31',
'Latitude': 31.32151602493975,
'ActivationDate': '2021-01-04',
'Longitude': -101.93948944894449,
'DeviceName': 'Hans_Gruber-2'
}]
In my flask app, I pass this list to my html file by the name "devices_test" using json.dumps() to correctly format the data to be used in java script.
return render_template("json_form.html",
devices = devices, components = components, operator = operator, name = site_name,
devices_test = json.dumps(devices))
Here is me trying to test out an answer I have seen on another post here via the "data" variable:
function update_device_form(strDevice) {
var data = {
{
devices_test | safe
}
};
var device_index = document.getElementById("devices").selectedIndex;
if (device_index == 0) { //IOW if no device is selected
document.getElementById("device_id").value = "";
} else {
document.getElementById("device_id").value = '';
}
But I get errors such as "Declaration or statement expected" and "Property assignment expected" and "',' expected". What am I doing wrong here?
You can use string to remove the error var data = "{{devices_test|safe}}"
Now data is not javascript object, it is a string, you need to use JSON.parse and also replaceAll.
var data = "{{devices_test|safe}}"
var data = data.replaceAll("'",'"') // replace single quote to double
var data = JSON.parse(data)
one line
var data = JSON.parse("{{devices_test|safe}}".replaceAll("'",'"'))
So I am currently trying to take a variable from my Main.js and import into a file called Iframe.html, the subject is a string containing the subject of a ticket from zen-desk I have the api working and it is grabbing the ticket subject however when I then try to implement that into the recognition system for the "BC-", it doesn't recognise.
This is the Main.js file with the variable "Subject" defined
function showInfo(data) {
var requester_data = {
//'email': data.ticket.address
//'name': data.ticket.name
'description': data.ticket.description,
'subject': data.ticket.subject
};
var source = $("#requester-template").html();
var template = Handlebars.compile(source);
var html = template(requester_data);
$("#content").html(html);
}
And this is the Iframe.html file that I am trying to import the variable "Subject" across to:
<!--BC-Check six digit-->
<script type="text/javascript">
function bc_check() {
var str = {{subject}};
var res = str.substring(str.indexOf("BC-"), str.indexOf("BC-") + 9);
document.getElementById("recognize").innerHTML = res;
}
</script>
Try to extract the variable requester_data out of the function but give it values inside it like you're doing it already.
I think your problem is that the variable requester_data belongs to the function and doesnt to the scope.
I try to add $(this).prev("input").val() in my id argument for an API route, but I don't know how to stop the C# part , I thought about <text></text> or #: but doesn't work like this.
Anyone has a trick ? (thought about writting the URL instead of using the RouteURL function but I don't think it's a good way to program)
$.ajax({
url: '#Url.RouteUrl("IsTranslated", new { id = <text>$(this).prev("input").val()</text> }, new {market=#ViewBag.market })
// [...]
})
You can't inject a JavaScript value like that (remember, the Razor code is evaluated server-side). What you can do is use your helper to build a "template" string, and replace the id value:
var template = '#Url.RouteUrl("IsTranslated", new { id = 0 }, new { market=#ViewBag.market })';
var id = $(this).prev("input").val();
var url = template.replace('id=0', 'id='+id);
$.ajax({
url: url
// [...]
})
This assumes, of course, that a querystring value is generated by the helper. If not, this might work:
var template = '#Url.RouteUrl("IsTranslated", new {}, new { market=#ViewBag.market })';
var id = $(this).prev("input").val();
var url = template.replace('IsTranslated', 'IsTranslated?id='+id);
$.ajax({
url: url
// [...]
})
Javascript
I have a method as follows,
function OpenRecord(id ,module ,screen) {
var url = '#Url.Action("OpenRecord", "Management", new { id = "_id", module = "_module",screen = "_screen" })';
url = url.replace("_id", encodeURIComponent(id));
url = url.replace("_module", encodeURIComponent(module));
url = url.replace("_screen", encodeURIComponent(screen));
window.location.href = url;
}
Controller
public ActionResult OpenRecord(string id, string module, string screen)
{
Int64 someID = Convert.ToInt64(id);
/*some act**/
return RedirectToAction(screen, module, new { id = someId});
}
When I run this i get id and module but screen param is passed null. When i inspect client side on chrome dev tools, i see all the parameters on javascript method are filled and the final url in url variable as follows;
/Management/OpenRecord/112?module=Customer&screen=MUSTRTANML
I guess that amp&; entity spoils my controller to get the last param but i am not sure and i don't know how to solve this.
Thanks in advance.
Simply wrap your Url.Action in Html.Raw(). Or you can go with replacement approach further - url = url.replace("&", "&"). Whatever you like, personally I would proceed with Html.Raw
you need to construct your url string with values
var url = '#Url.Action("OpenRecord", "Management", new { id = "_id", module = "_module",screen = "_screen" })';
this is wrong, it should be
var url = '/Management/OpenRecord?id=' + _id + '&module='+ _module + '&screen='+ _screen;
the above will pass the values of the variables rather than names , you cannot execute Url.Action as part of JavaScript this is Razor code
Here is the code that I am using to set the api url:
var clientUrl = '#Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Client"})';
In my route.config the route looks like this:
routes.MapHttpRoute(
name: "ApiControllerAction",
routeTemplate: "api/{controller}/{action}/{id}"
);
And the action on my controller that I am trying to hit is this:
[ActionName("clients")]
public IQueryable<Client> GetClients(int id)
{
return Uow.Clients.GetClients(id);
}
I have a function in javascript that is trying to hit this api, but I am getting a 404:
var getClients = function (id) {
return $.ajax(clientUrl + "/clients/" + id)
};
When I call getClients(1) the url is trying to hit is this:
localhost:12345/clients/1
Rather than my expected url of this:
localhost:12345/api/client/clients/1
Any idea where this is going wrong? I had this working in another project and can't remember if there is something else I am supposed to do. If I inspect the javascript the clientUrl = ''.
I came across this answer How to create ASP.NET Web API Url? which helped.
Example code for my answer here on GitHub
You can alter your #Url.RouteUrl code to include both the action name and the "ID" which currently appears not to be optional for your action route... this is probably why it is failing to find a match and returning an empty string. So try:
var clientUrl = '#Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Client", action = "clients" id=#... })';
NB. id=#... })'; at the end ... being what ever the id is going to be var or property on a model etc...
Or
You could of course just make ID optional which will also work:
config.Routes.MapHttpRoute(
name: "ApiControllerAction",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
Or
You may find it cleaner to avoid using an action... clients could live in its own controller ClientsController and you can use the routes and defaults to route to it:
routes.MapHttpRoute(
name: "ApiControllerAction",
routeTemplate: "api/client/clients/{id}",
defaults: new { controller="Clients" }
);
Then this should give you the required response:
var clientUrl = '#Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Clients" })';
//api/client/clients/
and...
var clientUrl = '#Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Clients", id=#... })';
//api/client/clients/x
Try to set the clientUrl like this:
var clientUrl = '#Url.RouteUrl("ApiControllerAction", new { httproute="", controller = "Client", action = "clients"})';
And then in change getClients to this:
var getClients = function (id) {
return $.ajax(clientUrl + "/" + id)
};