I'm trying to pass a data to django view via ajax like I used to do with php but I get on print empty value but my console log show that there is a data value on javascript but on view return None
Quit the server with CONTROL-C.
None
my html file code
{% for image in images %}
<table style="width:100%;" id="tab-{{image.image_cid}}">
<tr>
<td style="width:70%;vertical-align:middle">
<img src="/medias/{{ image.image_value }}" alt="" width="100" >
</td>
<td style="width:30%;vertical-align:middle">
DELETE
</td>
</tr>
</table>
{% endfor %}
<script>
$(document).ready(function(){
$(".cl-img-del").click(function(e){
var imgID = e.target.id
console.log(imgID);
$.ajax({
headers: {'X-CSRFToken': '{{ csrf_token }}'},
url: "{% url 'delete-image-ajax' %}",
type: "POST",
data: { imageid: imgID },
contentType: false,
cache: false,
processData:false,
success: function(data){
if(data == 'done')
{
$('#tab-'+imgID).remove();
}
},
error: function(){}
});
});
});
</script>
and my view file code is
def deleteImageAjxFn(request):
if request.method == "POST":
imgid = request.POST.get('imageid')
print(imgid)
try:
image = Images.objects.filter(image_shw = int(0), image_cid=imgid).delete()
except Images.DoesNotExist:
image = None
if(image):
return HttpResponse('done')
else:
return HttpResponse('None')
use static url in ajax instead of dynamic django url tags
use this instead url: "/delete-image-ajax/"
Related
I have posts that, user can add comments to, but i unable to add those comments to that specific posts, here is the code that I'm following:-
the code is working fine with models and the only issue is when comment added, its added to only one post, rather than specific comment to specific post
HTML Code
<div class="quote-comment-box">
<form method="POST" class="com">
{% csrf_token %}
<input placeholder="Your thought" type="text" name="quote-comment" class="comment-input" id="{{ quote.id }}" title="{{ quote.user.id }}" data="{{ request.user }}">
<button type="submit" href="{% url 'micro__blog:quote_comment' %}" class="comment-button">POST</button>
</form>
<div class="content" id="content">
</div>
</div>
js code
$('.comment-button').click(function (params) {
csrftoken()
var index = $('.comment-button').index(this)
var comment = $( ".comment-input" ).eq(index).val()
var id = $( ".content" ).eq(index).attr('id')
params.preventDefault()
$.ajax({
url:$(this).attr("href"),
data:{
'blog_id' : $( '.comment-input' ).eq(index).attr('id'),
'blog_user' : $( '.comment-input' ).eq(index).attr('title'),
'comment' : $( ".comment-input" ).eq(index).val(),
},
type:'POST',
dataType: 'json',
success: function (res, status) {
if (res['status'] == 'ok') {
$('.comment-input').eq(index).val('');
var content = $('.content').eq(index)
console.log(index, content)
const div = document.createElement('div');
div.className = "comment-added"
div.innerHTML = `
<span class="user">` + $( ".comment-input" ).eq(index).attr('data') + `</span>
<span class="text">` + comment + `</span>`;
document.getElementById('content').appendChild(div);
console.log(res.status)
} else {
console.log(res.status)
}
},
error: function (res) {
console.log(res.status);
}
})
Here is view code
def quote_comment(request):
if request.method == 'POST':
blog_id = request.POST.get('blog_id')
blog_user = request.POST.get('blog_user')
comment = request.POST.get('comment')
current_user = User.objects.get(id = request.user.id)
if blog_id and blog_user and comment and current_user:
blog_id = Quote.objects.get(id = blog_id)
blog_user = User.objects.get(id=blog_user)
try:
QuoteComment.objects.get_or_create(user=current_user,blog_id=blog_id,blog_user_id=blog_user,comment=comment)
return JsonResponse({'status':'ok'})
except User.DoesNotExist:
return JsonResponse({'status':'error'})
return JsonResponse({'status':'error'})
and url
path('quote_comment/', views.quote_comment, name="quote_comment"),
A view that renders this template
def index(request):
quotes= Quote.objects.all()
return render(request=request, template_name="dashboard.html",context={'quotes':quotes})
to render on quotes im suing for loop like this
{% for quote in quotes %}
{% endfor %}
I am getting details from mongodb using express api and calling it using AJAX in front-end, i am able to get the details but not able to display it in a table.
I have tried appending it in a table. I have attached some code on what i have done.
The AJAX Part
$.ajax({
type: 'GET',
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://localhost:8000/employees",
success:function(data){
data.forEach(element => {
$("#Name").append("<td>"+element.Name+"</td>");
$("#EmployeeId").append("<td>"+element.EmpId+"</td>");
$("#Designation").append("<td>"+element.Designation+"</td>");
$("#Email").append("<td>"+element.Email+"</td>");
});
},
error:function( errorMessage)
{
console.log(errorMessage);
}
});
The HTML part
<table>
<th>Name</th><th>EmployeeId</th><th>Designation</th><th>Email</th>
<tr>
<td id="Name"></td>
<td id="EmployeeId"></td>
<td id="Designation"></td>
<td id="Email"></td>
</tr>
</table>
I am currently getting entire output in single
i want the data in separate .
Current Output
You're getting all the data put into the same td because you're only using one row.
The way your code is running is basically...
<td id="Name">
<td>{value1}</td><td>{value2}</td>
</td>
....
You need to create rows tr inside the callback, instead of just appending data to the columns td
What you can do to fix this, is building entire rows in the success callback..
$.ajax({
type: 'GET',
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "http://localhost:8000/employees",
success:function(data){
data.forEach(element => {
var row = document.createElement("tr");
var name = document.createElement('td');
var employeeID = document.createElement('td');
var designation = document.createElement('td');
var email = document.createElement('td');
name.innerHTML = element.Name;
employeeID.innerHTML = element.EmpID;
designation.innerHTML = element.Designation;
email.innerHTML = element.Email;
row.appendChild(name);
row.appendChild(employeeID);
row.appendChild(designation);
row.appendChild(email);
$('#table').append(row);
});
},
error:function( errorMessage)
{
console.log(errorMessage);
}
});
and in your HTML, just apply the ID to table or whatever you want.
Edit::
Also, syntactically, you should put the table headers inside a row as well, so,
<tr>
<th>Name</th>
<th>Employee ID</th>
...
</tr>
For my class I have to design an app that says at the top of the page whether an incoming request is GET or POST, then has to print a table that shows all parameter names and values that were sent in the URL query string, and the property names and values that were received in the request body.
So far I have been able to get my localhost:port to work, it correctly shows whether a request is GET or POST. But when I go to the subpage that is supposed to display the tables, I get a 404 instead.
Here is the render page that I think is causing the problem:
function runQ(req) {
console.log(req.qParams);
console.log(req.body);
var context = {};
context.queryParams = [];
context.bodyParams = [];
context.queryCount = 0;
context.bodyCount = 0;
for( var p in req.qParams) {
context.queryCount++;
context.queryParams.push({'name': p, 'value': req.qParams[p] });
}
for( var p in req.body) {
context.bodyCount++;
context.bodyParams.push({'name': p, 'value': req.body[p] });
}
context.methodType = req.method;
return context;
}
app.get('/request', function(req, res) {
res.render('request', runQ(req));
});
app.post('/request', function(req, res) {
res.render('request', runQ(req));
});
I have a request.handlebar saved in my ubuntu/getpost/views folder along with the 404 and 500 handlebars.
The command I use for testing is:
$ curl --data "a=1&b=2&c=3" localhost:port
I replaced the localhost:port with an actual IP and port address when I have node running.
My console returns this on the tab that is running node:
undefined
{ a: '1', b: '2', c: '3' }
And this on the tab where I typed the cURL command:
<!doctype html>
<html>
<head>
<title>Demo Page</title>
</head>
<body>
<h1>POST Request Received</h1>
<table>
<caption><p>Request Body Table</p></caption>
<thead>
<tr>
<th>Property Names</th>
<th>Values</th>
</tr>
</thead>
<tbody>
<tr>
<td>a</td>
<td>1</td>
</tr>
<tr>
<td>b</td>
<td>2</td>
</tr>
<tr>
<td>c</td>
<td>3</td>
</tr>
</tbody>
</table>
</body>
So everything seems to be working from the console but when I try to access localhost:port/request, I go to the 404 error instead of a page that displays the tables.
Can anyone tell me what I'm doing wrong? Thank you all for your time.
I have a view with a table of products that can be added to a shopping cart. Each row has a DropDownList with allowed quantities that can be ordered along with a button to add to cart. Everything is populating and displaying properly. I know how to pass the item ID in the ActionLink but how can I get the value of the DownDownList associated with the table row of the ActionLink that was clicked?
I am guessing possibly using JQuery that fires when the ActionLink is clicked?
I also thought of making every row a form but that seems overkill.
Is there an easy MVC way to do this?
In prepping more info for a proper question and went ahead and solved it. Thank you Stephen for the nudge and info.
I tried putting a Html.BeginForm around each <tr> tag in the details section. This did indeed work for me. I was able to easily get the unique form info to POST for each individual row. However, when I would enable JQuery DataTables the submit would break. DataTables must be capturing the submit or click somehow. Haven't figured that out but it made me try JQuery which seems a much better way to do it.
Here is how I construct the table data row:
#foreach (var item in Model)
{
<tr>
<td>
<img src="#item.GetFrontImage()" width="100" />
</td>
<td>
<strong>#Html.DisplayFor(modelItem => item.DisplayName)</strong>
</td>
<td>
#Html.DisplayFor(modelItem => item.CustomerSKU)
</td>
<td>
#Html.DropDownList("OrderQty", item.GetAllowedOrderQuantities(), htmlAttributes: new { #class = "form-control" })
</td>
<td>
<a class="btn btn-default pull-right" data-id="#item.ID">Add to Cart</a>
</td>
</tr>
}
This creates a select with id of OrderQty and I embedded the item ID in data-id attribute of the link. I then used this JQuery to capture the info and POST it to my controller. Just have a test div displaying the results in this example:
// Add to Cart click
$('table .btn').click(function () {
// Gather data for post
var dataAddToCard = {
ID: $(this).data('id'), // Get data-id attribute (Item ID)
Quantity: $(this).parent().parent().find('select').val() // Get selected value of dropdown in same row as button that was clicked
}
// POST data to controller
$.ajax({
url: '#Url.Action("AddToCart","Shopping")',
type: 'POST',
data: JSON.stringify(dataAddToCard),
contentType: 'application/json',
success: function (data) { $('#Result').html(data.ID + ' ' + data.Quantity); }
})
});
The JQuery function receives the reference to the link being clicked so I can extract the Item ID from the data-id attribute. I can then get a reference to the dropdown (select) that is in the same row by using .parent.parent (gets me to the <tr> tag) and then just finding the next 'select' tag. Probably pretty obvious to a lot of you.
This works great for my purposes. I can also update other elements with data returned from the POST.
Thank you
Karl
for the table in html:
<div class="table-responsive">
<table id="employeeTable"class="table table-bordered">
<thead>
<tr>
<th class="text-center">ُُُEmpId</th>
<th class="text-center">Name</th>
<th class="text-center">Absense State</th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td>#item.Id</td>
<td>#item.Name</td>
<td class="text-center">#Html.DropDownList("DDL_AbsentStatus", new SelectList(ViewBag.statusList, "Id", "Name"), new { #class = "form-control text-center" })</td>
</tr>
}
</tbody>
</table>
</div>
in javascript to get the selected value:
//Collect Date For Pass To Controller
$("#btn_save").click(function (e) {
e.preventDefault();
if ($.trim($("#datepicker1").val()) == "") {
alert("ادخل تاريخ يوم صحيح!")
return;
}
var employeesArr = [];
employeesArr.length = 0;
$.each($("#employeeTable tbody tr"), function () {
employeesArr.push({
EmpId: $(this).find('td:eq(0)').html(),
EntryDate: $.trim($("#datepicker1").val()),
StatusId: $(this).find('#DDL_AbsentStatus').val()
});
});
$.ajax({
url: '/Home/SaveAbsentState',
type: "POST",
dataType: "json",
data: JSON.stringify(employeesArr),
contentType: 'application/json; charset=utf-8',
success: function (result) {
alert(result);
emptyItems();
},
error: function (err) {
alert(err.statusText);
}
});
})
I have been trying to make this work for several days now. I cannot access a profile object from its associated user object. I have the latest versions of Ember and ember-data
Ember-data: 1.0.0-beta15
Ember: 1.10.0 production
I have a simple table view that lists my users and a couple properties. Here is the view:
<script type="text/x-handlebars" data-template-name="users/verification-candidates">
<div class="small-12 column">
<h1>Candidates for Verification</h>
<table>
<tr>
<th>System ID</th>
<th>Email</th>
<th>Created At</th>
<th>Legal First Name</th>
<th>Legal Last Name</th>
<th></th>
<th></th>
</tr>
{{#each user in model itemController="candidate" }}
<tr>
<td> {{ user.id }}</td>
<td> {{ user.email }}</td>
<td>{{ user.created_at }}</td>
<td>{{ user.legal_first_name }}</td>
<td>{{ user.legal_last_name }}</td>
<td><button id="verify" {{ action "markVerified" }}>Verify</button></td>
<td><button id="disable" {{ action "markDisabled" }}>Disable</button></td>
</tr>
{{/each}}
</table>
</div>
</script>
The models are like so:
App.Profile = DS.Model.extend({
user: DS.belongsTo('user'),
incognito_name : DS.attr('string'),
advisor_id : DS.attr('number'),
created_at : DS.attr('date'),
//etc..
App.User = DS.Model.extend({
profile: DS.belongsTo('profile',{ async: true }),
email: DS.attr('string'),
sign_in_count: DS.attr('number'),
last_sign_in_at: DS.attr('date'),
//etc...
I am using the rest adapter:
App.ApplicationAdapter = DS.RESTAdapter.extend({
host: 'http://localhost:1337',
defaultSerializer: 'json'
});
Pertinent routes:
App.Router.map(function(){
this.resource('users', { path: '/users'}, function(){
this.route('verification-candidates');
});
this.resource('profiles', { path: '/profiles' }, function(){
})
});
App.UsersRoute = Ember.Route.extend({
model: function(){
return this.store.find('user');
}
});
App.ProfilesRoute = Ember.Route.extend({
model: function(){
return this.store.find('profile');
}
})
App.UsersVerificationCandidatesRoute = Ember.Route.extend({
model : function(){
var items = this.store.find('user', { role: "advisor", disabled: false, is_verified: false });
return items;
},
})
My server is a sails.js back end, which accesses a database created by a Rails application.
I want to alter the profile in this object controller, but cannot access it in any meaningful form:
App.CandidateController = Ember.ObjectController.extend({
actions: {
markVerified: function(){
var user = this.get('model');
var profile = user.get('profile');
console.log(profile); //output 1
console.log(profile.incognito_name); //output 2
}
}
});
The output2 is undefined. Output 1 gives me some sort of object with properties __nextSuper, __ember_meta, a bunch of other things, isFulfilled, and content. But, no object properties from the model definition. This appears to be a promisearray,but, I thought this was the way to get a related object. Meanwhile, when I try to treat it as a PromiseArray, per the documentation, i get null, like this:
App.CandidateController = Ember.ObjectController.extend({
actions: {
markVerified: function(){
var user = this.get('model');
user.get('profile').then(function(content){
console.log("promise content is " + content);
//prints 'promise content is null'
})
//console.log(profile);
//console.log(profile.incognito_name);
}
}
I am fairly certain all my back end server/client things are in order, as I can access the user objects and work with them on the page. I am thinking it may be related to how the profile relates to the user via advisor_id, but, I am so confused right now. I am very much at my wit's end.