AJAX Calling A Variable [duplicate] - javascript

I have a controller that passes an array to a twig template, which I want to use in a script written on that page. How would I go about doing that?
I've tried this in my .twig template:
<script>
$(document).ready(function(){
var test = {{ testArray }};
});
</script>
but that only works if it's a string.

You might have to json_encode the array, try this:
<script>
$(document).ready(function(){
var test = {{ testArray|json_encode(constant('JSON_HEX_TAG'))|raw }};
});
</script>

First, send the data json encoded from controller and
then in javascript,
var context= JSON.parse('{{ YourArrayFromController|raw}}');

I do it this way:
Return of the controller test.data then
$test = array('data' => array('one','two'))
Twig:
<div id="test" data-is-test="{{ test.data|json_encode }}"></div>
Js:
$(document).ready(function() {
var test = $('#test').data("isTest");
console.log(test);
});
Output:
["one", "two"]
documentation here

json_encode works well, in combination with the raw filter.
<script>
$(document).ready(function(){
let test = {{ testArray | json_encode(constant('JSON_HEX_TAG')) | raw }};
});
</script>
Don't forget the JSON_HEX_TAG flag.
Otherwise, you can get broken HTML. A string containing <!--<script> is a good way to test that.

In My Controller I Install SerializerBundle
$serializer = $this->get('serializer');
$countries = $this->getDoctrine()->getRepository("QSCORBundle:CountryMaps")->findAll();
$jsonCountries = $serializer->serialize($countries, 'json');
return $this->render('QSCORBundle:Default:index.html.twig',array("countries"=> $jsonCountries));
And In My File Twig
<script type="text/javascript" >
var obj = {{ countries|json_encode|raw }};
var myObject = eval('(' + obj + ')');
console.log(myObject[0]['capital_latitude'] + " " + myObject[0]['capital_longitude']);//for the First Element
</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>

how to use javascript variable into array in laravel blade file

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>

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>

Parsing json from external url Html and JS only

<html>
<body>
<div id="output">hi</div>
</body>
<script>
var link="http://mywp.com/cilacap/api/get_posts/";
var jcontent= JSON.parse(link);
var output=document.getElementById('output');
output.innerHTML=jcontent.id' ';
</script>
</html>
It only shows "hi".
Can someone tell me how to show JSON items such as "id" and "postDate"
with looping but without PHP scripting?
Thanks
Few syntactical errors, below is the right one.
<html>
<body>
<div id="output">hi</div>
</body>
<script>
var link='{"url":"http://mywp.com/cilacap/api/get_posts/", "id":"url_id_01"}';
var jcontent= JSON.parse(link);
var output=document.getElementById('output');
output.innerHTML=jcontent.id + ' ';
</script>
</html>
JSON Data(var link), was not parsable.
JSON Data(var link), didnt contained any attribute called id.
String concatenation in last line(output.innerHTML), was wrong.
Try removing the quotes from:
output.innerHTML=jcontent.id' ';
and change it to:
output.innerHTML += jcontent.id;
Providing that the link is valid it should work now.
You can also write:
console.log(jcontent);
and check if the console displays the value, or any errors that have occurred.
That url is a string, not json.
Use Ajax to get the data ( using jquery)
var link;
$.ajax({
url: "test.html",
}).done(function(data) {
link = data;
});
Then, extract the data;
output.innerHTML=jcontent.id;
Is for the value. You get the key like this:
ES7
Object.entries(jcontent)
.forEach(keyValuePair =>
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
output.appendChild(t);   
});
ES6
Object.keys(jcontent)
.map(key => [key, jcontent[key]])
.forEach(keyValuePair =>
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
output.appendChild(t);   
});
ES5 (Most likely your case)
Use function instead of arrow functions for es5:
Object.keys(jcontent)
.map(function(key){ [key, jcontent[key]] })
.forEach(function(keyValuePair)
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
output.appendChild(t);   
});
Access the value:
keyValuePair[0] // key
keyValuePair[1] // value
Ps
If you want to use the es7 or es6 method, have a look at babeljs

How to pass an object to query string in javascript using getElementById

I have the below file that passes variables in query string.
What I am able to do
Get document.getElementById("getthis").innerHTML and save it in
var getthis.
Get value selected $('#first').val(); and save it in var from
What I am not able to do
Get this values document.getElementById("list1").innerHTML, document.getElementById("list2").innerHTML, document.getElementById("list3").innerHTML and save the it in var data in this format var data = { seats_booked: [ 'B2', 'B5', 'A20' ] };.
I would like to know how to do this, since in query string I can then be able to get the variables using PHP.
I hope my question is clear and help will be appreciated. Thank you in advance.
Here is the code:
<?php
$str = $_SERVER['QUERY_STRING'];
parse_str($str);
echo $seats_booked[0];
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<body>
<ul>
<li id="getthis">list</li>
</ul>
<select id="first" name="first">
<option value="10">First</option>
<option value="11">Second</option>
<option value="12">Third</option>
<option value="13">Forth></option>
</select>
<ul>
<li id="list1">B2</li>
<li id="list2">B5</li>
<li id="list3">A20</li>
</ul>
<button id="next" name="next">Next Step</button>
<script type="text/javascript">
$(document).ready(function(){
$("#next").click(function() {
var data = { seats_booked: [ 'B2', 'B5', 'A20' ] };
var result = $.param(data);
var first = $('#first').val();
var getthis = document.getElementById("getthis").innerHTML;
window.location = '?first='+first+'&getthis='+getthis+'&result='+result;
});
});
</script>
</body>
</html>
jQuery.param converts a data structure to the format used for query strings. Whole query strings. Not bits of query string*.
Put all your data in a query string, then use param on it.
var result = { seats_booked: [ 'B2', 'B5', 'A20' ] };
var first = $('#first').val();
var getthis = document.getElementById("getthis").innerHTML;
var data = {
result: result,
first: first,
getthis: getthis
};
var query = jQuery.param(data);
window.location = "?" + query;
* more precisely, it converts to a set of key=value pairs suitable for a query string, so you can join them up yourself. Your problem is that you are taking the key=value pairs and then trying to use them as a single query string value. But you're also failing to encode the rest of the data properly, and using param for the whole thing is much cleaner and more maintainable.
You can do it this way
<ul class="seats_booked">
<li id="list1">B2</li>
<li id="list2">B5</li>
<li id="list3">A20</li>
</ul>
var seats_booked = [];
$("ul.seats_booked li").each(function() { seats_booked.push($(this).text()) });
var data = {};
data["seats_booked"]=seats_booked;
Did you mean something like this?
https://jsfiddle.net/5p6k11ny/
I have only changed window.location to console.log
var data = { seats_booked: [] };
data.seats_booked.push(document.getElementById("list1").innerHTML);
data.seats_booked.push(document.getElementById("list2").innerHTML);
data.seats_booked.push(document.getElementById("list3").innerHTML);
Ofc, you could do it in some loop like
"list" + i

Categories

Resources