Reputation: 340
i am rewriting my url and category name passing in to url. Now i am creating Url Friendly String using JS function is:
function getUrlFriendlyString(str)
{
// convert spaces to '-'
//alert(str);
str = str.replace(/ /g, "-");
// Make lowercase
str = str.toLowerCase();
// Remove characters that are not alphanumeric or a '-'
str = str.replace(/[^a-z0-9-]/g, "");
// Combine multiple dashes (i.e., '---') into one dash '-'.
str = str.replace(/[-]+/g, "-");
return str;
}
now on HTML page this JS function is giving a string value in JS like
<? $cat_name= 'Personalized Chocolates / Gift'; ?>
<script>var url=getUrlFriendlyString("<?=$cat_name;?>");</script>
i want to pass var url value in html tag href like that
<a href="<?PHP echo SITE_URL;?>/category/<script>document.write(url);</script>/<?=$data_2['cat_id'];?>"
but
<script>document.write(url);</script>
not giving their value and coming url is like that
http://localhost/ecom/category/<script>document.writeln(url);</script>/105
required url is
http://localhost/ecom/category/personalized-chocolates-gift/105
any idea how i can show proper url using js string?
i can save var url value in PHP variable
Upvotes: 2
Views: 1724
Reputation: 340
this may help you JS in HTML Code redirectTo()
is JS Function
<a onclick="redirectTo();">click here</a>
Upvotes: 0
Reputation: 58
This is working for me
you can take var url value in php variable and use in your href tag
<? $cat_name= 'Personalized Chocolates / Gift'; ?>
<script>var url=getUrlFriendlyString("<?=$cat_name;?>");</script>
and
<?php
$m="<script>document.write(url);</script>";
echo $m; // output is : personalized-chocolates-gift
?>
this will not give you same o/p inside href, will give you o/p your js code because inside $m js code is saved and href not converting js into string o/p
i hope this will work for you :)
Upvotes: 1
Reputation: 944442
You can't include an element (such as <script>...</script>
) in the middle of an attribute value.
If you are going to take this approach, then you need to write out the entire anchor element using JavaScript.
An alternative approach would be to set a default value in the HTML, then access the element with DOM in a script that appears after the element is complete.
A better approach would be to rewrite the getUrlFriendlyString
function in PHP and run it on your server.
Upvotes: 3