how to use javascript variable into array in laravel blade file - javascript

How to use var aid value assign into $data array? I am getting error: "Use of undefined constant aid". I am working on Laravel 5.4. I want to show ($data['services'][aid]->servicesubdetails) value in tage. My code is below:
<script language="JavaScript">
function theFunction(e)
{
var aid= e.target.id;
$("p").html('{{ ($data['services'][aid]->servicesubdetails) }}');
}
</script>

Single quotes are interrupted by another single quote.
<script language="JavaScript">
function theFunction(e)
{
var aid= e.target.id;
$("p").html(“{{ ($data['services'][aid]->servicesubdetails) }}”);
}
</script>
Notice “ instead of ‘.

EDIT
You can use json to use you PHP array in javascript
Look at LaravelDisplayData and PHPJsonEncode
<script language="JavaScript">
var data = #json($data)
function theFunction(e)
{
var aid= e.target.id;
$("p").html(data.services[aid].servicesubdetails);
}
</script>

Related

How to pass a java ArrayList of Strings to JavaScript [duplicate]

I am using Thymeleaf as template engine. How I pass a variable from Spring model to JavaScript variable?
Spring-side:
#RequestMapping(value = "message", method = RequestMethod.GET)
public String messages(Model model) {
model.addAttribute("message", "hello");
return "index";
}
Client-side:
<script>
....
var m = ${message}; // not working
alert(m);
...
</script>
According to the official documentation:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[[${message}]]*/ 'default';
console.log(message);
/*]]>*/
</script>
Thymeleaf 3 now:
Display a constant:
<script th:inline="javascript">
var MY_URL = /*[[${T(com.xyz.constants.Fruits).cheery}]]*/ "";
</script>
Display a variable:
var message = [[${message}]];
Or in a comment to have a valid JavaScript code when you open your template file in a static manner (without executing it at a server).
Thymeleaf calls this: JavaScript natural templates
var message = /*[[${message}]]*/ "";
Thymeleaf will ignore everything we have written after the comment and before the semicolon.
More info: http://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#javascript-inlining
var message =/*[[${message}]]*/ 'defaultanyvalue';
According to the documentation there are several ways to do the inlining.
The right way you must choose based on the situation.
1) Simply put the variable from server to javascript :
<script th:inline="javascript">
/*<![CDATA[*/
var message = [[${message}]];
alert(message);
/*]]>*/
</script>
2) Combine javascript variables with server side variables, e.g. you need to create link for requesting inside the javascript:
<script th:inline="javascript">
/*<![CDATA[*/
function sampleGetByJquery(v) {
/*[+
var url = [[#{/my/get/url(var1=${#httpServletRequest.getParameter('var1')})}]]
+ "&var2="+v;
+]*/
$("#myPanel").load(url, function() {});
}
/*]]>*/
</script>
The one situation I can't resolve - then I need to pass javascript variable inside the Java method calling inside the template (it's impossible I guess).
MAKE sure you have thymleaf on page already
//Use this in java
#Controller
#RequestMapping("/showingTymleafTextInJavaScript")
public String thankYou(Model model){
model.addAttribute("showTextFromJavaController","dummy text");
return "showingTymleafTextInJavaScript";
}
//thymleaf page javascript page
<script>
var showtext = "[[${showTextFromJavaController}]]";
console.log(showtext);
</script>
I've seen this kind of thing work in the wild:
<input type="button" th:onclick="'javascript:getContactId(\'' + ${contact.id} + '\');'" />
If you use Thymeleaf 3:
<script th:inline="javascript">
var username = [[${session.user.name}]];
</script>
If you need to display your variable unescaped, use this format:
<script th:inline="javascript">
/*<![CDATA[*/
var message = /*[(${message})]*/ 'default';
/*]]>*/
</script>
Note the [( brackets which wrap the variable.
Another way to do it is to create a dynamic javascript returned by a java controller like it is written here in the thymeleaf forum: http://forum.thymeleaf.org/Can-I-use-th-inline-for-a-separate-javascript-file-td4025766.html
One way to handle this is to create a dynamic javascript file with the
URLs embedded in it. Here are the steps (if you are using Spring MVC)
#RequestMapping(path = {"/dynamic.js"}, method = RequestMethod.GET, produces = "application/javascript")
#ResponseStatus(value = HttpStatus.OK)
#ResponseBody
public String dynamicJS(HttpServletRequest request) {
return "Your javascript code....";
}
Assuming request attribute named "message":
request.setAttribute("message", "this is my message");
To read it in the html page using Thymeleaf template:
<script>
var message = "[[${message}]]";
alert(message);
</script>

Asp.net mvc passing a C# model to Javascript file

I want to pass the value i got it from model to the java-script function
<script type="text/javascript">
var checkin = #Model.Parameters.Checkin.ToString("dd-MM-yyyy");
var checkout = #Model.Parameters.Checkout.ToString("dd-MM-yyyy");
</script>
this function that i want to pass model chick-in and chick-out value to it:
$('document').ready(function () {
$("#Arrival").val(checkin);
$("#Departure").val(checkout);
});
i tried many solution but it didn't work yet .
any advice, thanks
if the #Model.Parameters.Checkin and #Model.Parameters.Checkout not null then Try:
<script type="text/javascript">
$( document ).ready(function(){
var checkin = '#Model.Parameters.Checkin.ToString("dd-MM-yyyy")';
var checkout = '#Model.Parameters.Checkout.ToString("dd-MM-yyyy")';
$("#Arrival").val(checkin);
$("#Departure").val(checkout);
});
Just you miss '. and also change $('document').ready(function () { }) to $(document).ready(function () { }).
you must write all script into a .cshtml file. #Model.Parameters.Checkin.ToString("dd-MM-yyyy") never work into a .js file.
Because, In .cshtml, when the the page is render then it white to HTTP response stream as a string.
In MVC, you can use following code:
<script type="text/javascript">
var number = parseInt(#ViewBag.Number); //Accessing the number from the ViewBag
alert("Number is: " + number);
var model = #Html.Raw(#ViewBag.FooObj); //Accessing the Json Object from ViewBag
alert("Text is: " + model.Text);
</script>

How to access smarty variable and assign to jquery variable?

I just need your help about my code. My problem is how can I access smarty variable within jquery or javascript file? Becuase my smarty variable is a URL request from my controller. And I need to use that variable for creating validation. Here's my code.
{$get.search_by} {**works without error**}
{literal}
<script type="text/javascript">
$(document).ready(function(){
var dispatch = "{$get.search_by}"; //can't access
var new_class = "it3 ir3 il3 jt10 jr05 jl05 kt03 kr04 kl04";
var old_class = "it3 ib3 il3 jt05 jb05 jl10 kt04 kb04 kl03";
var toggleState = true;
//could not access
if(dispatch == companies.catalog){
alert("catalog");
}else{
alert("product search");
}
console.log(dispatch);
Try this code
var dispatch = '{/literal}{$get.search_by}{literal}'
To make things cleaner, you can move the {literal} tag down and also escape the $get.search_by variable (in case search_by may have a string with a quote i.e. "let's try"):
<script type="text/javascript">
var dispatch = '{$get.search_by|escape:'javascript'}';
{literal}

How do I reference a Razor variable later in my page in JavaScript or HTML

I have the following Razor code:
#{
if (IsPost)
{
string pn=Request.Form["pn"];
if (!string.IsNullOrEmpty(pn)){
/* my code to call the stored procedure with pn as a parameter*/
}
}
}
And in the page, using JavaScript / HTML I need to tell the user about pn. Be it that it's empty, or report back that the value was inserted in the database.
How do I do that?
You need to insert the result into the rendering. There are a couple of ways of doing that. You could store it in a variable:
<script type="text/javascript">
var pn = '#(pn)';
alert('pn is ' + pn);
</script>
Or you could call a function, sort of like JSONP:
<script type="text/javascript">
parsePn('#(pn)');
<!-- ... extra logic ... -->
function parsePn(pn) {
alert('pn is ' + pn);
}
</script>

Replacing function contents dynamically in JavaScript

How do you completely replace a function in JavaScript?
I got this code, but it doesn't work. The DOM gets updated, though. What's up with that?
<html>
<head>
<script id="myScript" type="text/javascript">
function someFunction() {
alert("Same old.");
}
</script>
</head>
<body>
<input type="button" onclick="someFunction();" value="A button." />
<script>
function replace() {
var oldFunctionString = someFunction.toString();
var oldContents = oldFunctionString.substring(oldFunctionString.indexOf("{") + 1, oldFunctionString.lastIndexOf("}") );
var newCode = "alert(New code!);";
var newFunctionString = "function someFunction(){"+newCode+"}";
var scriptTag = document.getElementById('myScript');
scriptTag.innerHTML = scriptTag.innerHTML.replace(oldFunctionString,newFunctionString);
}
replace();
</script>
</body>
</html>
JSfiddle here
Setting .innerHTML doesn't re-execute a script. If you really wanted to do that, you'd have to create a new script element and append it to the DOM, which then overwrites what the previous script has done (not possible in all cases, of course).
If you want to replace that function, just use
somefunction = function() {
alert(New code!); // syntax error, btw
};
Of course, to replace only parts of the code (not knowing all of it) you could try regex and co. Still just reassign the new function to the variable:
somefunction = eval("("
+ somefunction.toString().replace(/(alert\().*?(\);)/, "$1New code!$2")
+ ")");
It seems you are trying to work with strings, not the function itself. Just do this instead:
someFunction = function () { /* your function code here */ }

Categories

Resources