Code prints out tasks information. I want to pass tasks array to JS. How could I do that? Some of my twig code:
<div>
{% for task in tasks %}
<tr>
<td id>{{ task.Id }}</td>
<td>{{ task.Status }}</td>
<td>{{ task.Name }}</td>
<td>{{ task.Description }}</td>
<td>{{ task.Category }}</td>
<td>{{ task.Author }}</td>
<td>{{ task.CreationDate|date("m/d/Y") }}</td>
<td><a id="myLink" href="/edit/{{ task.ID }}" > Edit </a></td>
<td><a id="myLink" href="/delete/{{ task.ID }}" >Delete</a></td>
<?php echo 2+2; ?> </tr>
{% endfor %}
</table>
</div>
I want to pass array to this js class:
$(function(){
$('#calendar').fullCalendar({
});
});
You can serialize the array in json format: {{ tasks | json_encode() }}.
If your javascript is inside a <script> element of the twig template, you can just do: var data = {{ tasks | json_encode() }}.
Otherwise, you can put the serialized array somewhere in the twig template as an element's attribute:
<div id="data-element" data-tasks="{{ tasks | json_encode() }}">.
Then just get the data with
var jsonString = $('#data-element').data('tasks');
var data = JSON.parse(jsonString);
First of all , you need to know that there are a big deference between PHP arrays and Javascript arrays.
you need to convert your array to a common understood format that both PHP and Javascript can understand , which is JSON .
so I will assume that you are sending your tasks from your controller to twig as a json format, then you can set your javascript variable as follows :
<script>
var tasks = '{{ tasks }}';
var tasksObj = JSON.parse(tasks); // to convert json into a javascript object
</script>
Related
I am using a Jinja loop to display a table of results in an html page. When someone clicks the button in a table row, the code should send the first column value in that row to the server. The server should then use the value to populate values in another page. All works fine except the render_template function in app.py isn't executing.
What am I doing wrong?
My last print(request_details) shows the data needed correctly. However the render_template that follows just doesn't want to execute.
HTML and JS:
{% extends "layout.html" %}
{% block body %}
<table>
<tr>
<th>Request ID</th>
<th>Origin</th>
<th>Destination</th>
<th>Distance</th>
<th>Cargo</th>
<th></th>
</tr>
{% for r in supplier_results %}
<tr>
<td>{{ r[0] }}</td>
<td>{{ r[2] }}</td>
<td>{{ r[3] }}</td>
<td>{{ r[4] }}</td>
<td>{{ r[5] }}</td>
<td><button onclick="passRequest({{ r[0]|safe }})">Offer</button></td>
</tr>
{% endfor %}
</table>
<script>
function passRequest(arg) {
let details = arg
console.log(details)
const request = new XMLHttpRequest()
request.open('POST', '/viewrequest/' + details)
request.send();
};
</script>
{% endblock %}
Python:
#app.route("/viewrequest/<int:details>", methods=["GET", "POST"])
def viewrequest(details):
# Retrieve request information with the request_id (details)
retrieve_request = f"SELECT * FROM requests WHERE request_id='{details}';"
cur.execute(retrieve_request)
request_details = cur.fetchall()
# Call the newoffer page and pass the request details
if request_details == []:
print("No data found")
return
else:
print(request_details)
return render_template("supplier/newoffer.html", request = request_details)
Passing variables into onclick method.How do I do it in HTML and javascript
I am passing the variable usersid from the onclick calling funtion to called function.
<tbody>
{% for each_user in detail %}
<tr>
<td>{{ each_user.userss_name }}</td>
<td>{{ each_user.userss_email }}</td>
<td><input class="btn btn-info" type="button" value="Edit" id="edit"
onclick="editUser('\''+ '{{ each_user.userss_id }}' +'\'')"></td>
</tr>
{% endfor %}
</tbody>
My script code is
<script>
function edituser(user_id) {
console.log(user_id);
document.location.href = "/'{{ user_id }}'/user/edit/"
}
</script>
What is the expected result is when I click the edit button it should take me to the url /user_id/user/edit. So user id is the integer here.So I shoule see /1/user/edit.
But what I am getting here is http:/""/interviewer/edit and page not found error also.
So I dont know how to pass the variable to the url.
edit your document.location.href like below should works. The issue is user_id is a javascript variable, not a template variable, so you don't wrap it with {{ }}.
<script>
function edituser(user_id) {
console.log(user_id);
document.location.href = "/" + user_id + "/user/edit/"
}
</script>
<script>
function edituser(user_id) {
console.log(user_id);
document.location.href = "/" + user_id + "/user/edit/"
}
</script>
user_id doesn't need to be in {{}}
I will try to be as clear as possible. I have a table with ng-repeat in blade file.
I want to send parameters to a Laravel function, inside the repeat loop.
Here is the example:
The angular
app = angular.module("myApp",[], function($interpolateProvider) {
$interpolateProvider.startSymbol('<%');
$interpolateProvider.endSymbol('%>');
});
The blade file : $idVal needs to be the id from the loop.
<tr ng-repeat="rec in recomends" ng-init="recomends = {{ $recomends }}">
<td ><% $index + 1 %></td>
<td><% rec.name %></td>
<td>{{ HelperAdmin::getTotalParam('quality',$idVal) }}</td>
</tr>
The laravel Function:
public static function getTotalParam($field,$reco_id){
$total = DB::select("SELECT AVG($field) AS mysum FROM recommendation_measure WHERE reco_id = $reco_id ");
return number_format($total[0] ->mysum,2);
}
I need to push $idVal as the id of the loop data. But I can't find a way to send it. Any idea?
Hope this question is clear.
I want to get the values of the two object in thesame ng-repeat
$http.get('/api/PreviewPayroll').success(function (data){
//alert(data[0].empID);
$scope.allowance = data;
});
$http.get('/api/Deduction').success(function (data){
//alert(data[0].empID);
$scope.Deduction = data;
});
<tr ng-repeat="item in allowance && ng-repeat="value in Deduction">
<td>{{ item.empID }}</td>
<td>{{ value.empID }}</td>
</tr>
how can I get the two scope object on thesame ng-repeat
So you will want to combine the data.
You can use $q.all(promises):
var promise1 = $http.get('/api/PreviewPayroll');
var promise2 = $http.get('/api/Deduction');
$q.all([promise1, promise2]).then(function (results) {
var allowances = results[0];
var deductions = results[1];
var combinedList = /* some combination logic */;
});
By using $q.all() you are ensuring you have both lists of data before trying to combine anything. You can easily play around with this to get the desired effect. For example, if you don't care if the other list isn't available.
Then you can use the ng-repeat in order to iterate over that new combined list:
<tr ng-repeat="item in combinedList">
<td>{{ item.allowance.empID }}</td>
<td>{{ item.deduction.empID }}</td>
</tr>
The sub properties allowance and deduction are based on your combined list.
However
It is in my honest opinion that, the server side gives you the data in the format you need to display it in. (i.e. the business logic remains server side in a controlled environment). I believe the view should only deal with view logic, like button actions etc..
But this is my opinion, and is what I find easiest.
Another note
I prefer to also keep the view logic in the JavaScript, hence why I combine the data there. Rather than trying to do some overly complicated angular expression in the HTML.
You could either have a nested ng-repeat and also combine the two objects into one.
<table>
<tbody ng-repeat="row in mainCombinedObject">
<tr>
<th>{{row.empID}}</th>
</tr>
<tr ng-repeat="sub in row.subObject">
<td>{{sub.empID}}</td>
</tr>
</tbody>
</table>
Combine $scope.allowance and $scope.Deduction to one list of objects "combined" then do your ng-repeat:
<tr ng-repeat="c in combined">
<td>{{ c.someField }}</td>
<td>{{ c.someOtherField }}</td>
</tr>
You can't do that in such way! If your allowance and Deduction have the same size you have to mix them in the collection like this:
var array = [
{ allowance: value1, Deduction: value2},
{ allowance: value3, Deduction: value4},
...
];
and them use it in the view:
<tr ng-repeat="item in array">
<td>{{ item.allowance.empID }}</td>
<td>{{ item.Deduction.empID }}</td>
</tr>
I am using Django 1.7 and nginx.
My sample view file is,
def testing(request):
return render_to_response('pages/testing.html', )
def testing1(request):
return render_to_response('pages/comingsoon.html',)
def testing2(request):
x= User.objects.all()
return render_to_response('pages/index1.html',{'users': x,})
def testing3(request):
context = User.objects.all()
return render_to_response('pages/testing.html',)
pages/testing.html - contains only text.(pure text)
pages/testing1.html - contains css and js
pages/testing2.html -
<body>
<h1>Users</h1>
{% for e in users %}
<table>
<tr>
<td class="active">{{ e.username }}</td>
<td>{{ e.email }}</td>
</tr>
</table>
{% endfor %}
</body>
pages/testing3.html - contains same as testing1.html
But while running this .
testing, testing1 take less than 3seconds in server.
But testing3 takes 40seconds and testing2 takes more that 1 Min.
How could I reduce that?
Thanks In Advance.
You may use values_list or values
and specify the values you need in templates inside values_list or values, instead of User.objects.all(). This is going to make a huge diffrence.