I'm in odoo create eg.
import xmlrpclib
username = 'admin'
pwd = 'admin'
dbname = 'odoo9'
sock_common = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/common')
uid = sock_common.login(dbname, username, pwd)
sock = xmlrpclib.ServerProxy('http://localhost:8069/xmlrpc/object')
contact_ids = sock.execute(dbname, uid, pwd, 'res.partner', 'search', [])
for contact_id in contact_ids:
contact = sock.execute(dbname, uid, pwd, 'res.partner', 'read', contact_id, [])
print('Name is: ' + contact['name'])
after call xml_rpc.py file in terminal get:
Name is: Admin
Name is: Marc
Name is: Ronald
Now I want all names (Admin, Marc, Ronald) load in my html div with ajax.
$.ajax({
???
???
});
How with ajax load data?
$.ajax({
url:"http://localhost:8069/connect_with_odoo",
type:"POST",
data:{},
})
put your data into the data:{<here>}
Related
I've been trying to get my button to send a POST request to the submitted URL, which does a write back to the database. The application looks like the POST request gets sent, but after hitting the button my URL never changes and the print at the submitted URL appears to be an empty set.
This is my jquery/ajax call for the button:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<button class="btn btn-primary my_select" type="submit">Request Access</button>
<script>
$(document).ready(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var phi = $('#phi').val();
var accesslevelid = $('#accesslevelid').val();
$.ajax({
url: "{% url 'submitted' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
phi: phi,
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
// do something with result
},
});
});
});
</script>
I'm expecting my POST of the Application List, PHI flag, and Access Level gets sent as a POST to my submitted URL. My view for submitted is the following:
def submitted(request):
owner = User.objects.get (formattedusername=request.user.formattedusername)
checkedlist = request.POST.getlist('report_id')
coid = User.objects.filter(coid = request.user.coid).filter(formattedusername=request.user.formattedusername)
facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True)
divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True)
print (f"checkedlist prior to post:{checkedlist}")
selectedaccesslevel = request.POST.get('accesslevelid')
selectedphi = request.POST.get('phi')
if request.method == 'POST':
for i in checkedlist:
requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title
,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi , access_beg_date = '2017-01-01 00:00:00', access_end_date = '2017-01-31 00:00:00')
requestsave.save()
print (f"postlist:{checkedlist}")
print (f"accesslevel:{selectedaccesslevel}")
print (f"phi:{selectedphi}")
return JsonResponse({'is_success':True})
My post looks like it occurs when I press my button:
[]
[12/Dec/2017 08:54:45] "POST /account/submitted/ HTTP/1.1" 200 1149
However, the URL doesn't switch to submitted. My list for checkedlist appears to be an empty set. When visiting submitted and having my print statements occur, i get nothing like the POST never occurred.
My form action is the following:
<form action = "{% url 'submitted' %}" form method = "POST">
{% csrf_token %}
{{ form.as_p}}
ajax is build to do background client server operation or load part of the page dynamic to avaid heavy requests
Example
most of social medias feeds use ajax. when you scroll the view a ajax request is send to server to retrieve the next feed .
in your case the data is posted to server successfully. but change the URL is not available by server at this point but you can do this with a trick ...
in your view.py file
from django.http import JsonResponse
if request.method == 'POST':
for i in checkedlist:
requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title
,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi , access_beg_date = '2017-01-01 00:00:00', access_end_date = '2017-01-31 00:00:00')
requestsave.save()
print (checkedlist)
print(selectedaccesslevel)
print(selectedphi)
return JsonResponse({'is_sucess':True})
this JsonResponse object will send back the data ajax.
success: function (result) {
if(result.is_sucess){
document.location = 'you url to direct page at' //
}
},
this job can be done using direct post to url and then redirecting to other url i. will leave this for now
Django 1.7.2/ python 3.4
this code is about 'like'.
if user click the 'like' button, ajax calls 'pushLike'.
if the user has liked the article before(saved inside Mysql), delete the row on table(DB).
or if the user is not liking the article, create a row and insert it on the table(DB).
after that, count how many like has beed clicked on that article.
I would like to pass the likeCnt(count) to ajax, and write it on the button.
The likeCnt has the right value(I checked it on the server mysql table).
The button color does change(white to blue, and vise versa), but the text does not change.
It seems like json does not pass to ajax. I tried passing data by 'text' type and it did worked, but i want it by json.
I've tried simplejson, json, mimetype, content_type on HttpResponse.
please help me.
view
#login_required
def pushLike(request):
pk = request.GET['writing_id']
try:
la = LikeArticles.objects.get(user = User.objects.get(username=request.user.username), article_id=pk)
if(la.is_like()):
la.delete()
likeCnt = LikeArticles.objects.filter(article_id=pk).count()
FreeBoards.objects.filter(id=pk).update(like = likeCnt)
else: #Never happens
la.like = True
la.save()
likeCnt = LikeArticles.objects.filter(article_id=pk).count()
FreeBoards.objects.filter(id=pk).update(like = likeCnt)
except ObjectDoesNotExist:
la = LikeArticles(user = User.objects.get(username=request.user.username),
article = FreeBoards.objects.get(id=pk),
like = True,
)
la.save()
likeCnt = LikeArticles.objects.filter(article_id=pk).count()
FreeBoards.objects.filter(id=pk).update(like = likeCnt)
data = {'likeCnt': likeCnt}
# return render(request, url, context)
return HttpResponse(simplejson.dumps(data), mimetype='application/javascript')
javascript
<script type="text/javascript">
$(document).ready(function(){
$('#btn-like').click(function(){
var e = $('#btn-like').css('background-color');
$.ajax({
url : '/sle/freeboards/pushLike/',
data : {'writing_id':{{writing_id}},
},
dataType : "json",
success:function(data){
alert(data.likeCnt);
if(e == 'rgb(59, 89, 152)') {
$('#btn-like').css('background-color', '#ffffff').css('color', '#000000');
$('#btn-like').text(data.likeCnt);
} else {
$('#btn-like').css('background-color', '#3b5998').css('color', '#ffffff');
$('#btn-like').text(data.likeCnt);
}
},
failure: function(data){
alert('fail!!')
}
});
});
});
</script>
you'll want to be sure to set the proper mimetype in your HttpResponse
#login_required
def pushLike(request):
...
# return json -- !!not javascript!!
return HttpResponse(simplejson.dumps(...), mimetype="application/json")
--or--
#login_required
def pushLike(request):
...
# return json -- !!not javascript!!
return JsonResponse({"your": "context dictionary"})
If that doesn't work, have you tried parsing the json with your Jquery code?
ie:
$.ajax({
...
success: function(data){
var response = $.parseJSON(data);
...
}
});
javascript might actually receiving bytes back from whatever you are serving your django app with... so instead of getting JSON back, you're actually getting string that looks like JSON. http://api.jquery.com/jquery.parsejson/
I need to make ajax submit to submit some data include a base64 string of the image, which is render from canvas.
When submit I look in the network panel of Chrome inspector and everything look fine, in "form data" it list all the data that I want to submit.
But in Grails I cannot get the data, there is nothing in the params, just the controller name and action name. Thus everything I get with simple params.dataName is null.
I guess there is something with the size of the post request, but I'm not so sure as I have done this before without ajax.
This is my code for upload with jquery ajax:
var imgBase64String = canvas.toDataURL("image/png");
imgBase64String = imgBase64String .replace('data:image/png;base64,', '');
var submitData = $(form).serializeArray();
submitData.push({name: "webImage", value: imgBase64String })
$.ajax({
type: 'POST',
url: '${createLink(action: 'myAction')}',
data: submitData,
dataType: "html",
success: function(data){//Success code},
});
UPDATE
My code on the server side, it fails at the simple step to retrieve params data:
def myAction= {
def paramData = params
log.info "paramData: " + paramData
def url = params.url
def email = params.email
def webImage = params.webImage
log.info "param: url = " + url
log.info "param: email = " + email
log.info "param: webImage = " + webImage
//Other implement code
}
And the output:
2012-10-08 16:31:28,988 [http-bio-8080-exec-5] INFO myController - paramData: [action:myAction, controller:myController]
2012-10-08 16:31:28,989 [http-bio-8080-exec-5] INFO myController - param: url = null
2012-10-08 16:31:28,989 [http-bio-8080-exec-5] INFO myController - param: email = null
2012-10-08 16:31:28,989 [http-bio-8080-exec-5] INFO myController - param: webImage = null
The size of the base64 image I'm trying to submit is 1998720, don't know if this matter.
Many thanks.
I believe you can simply pass canvas.toDataURL("image/png") into the data field in the $.ajax() method. Also use $.post() instead of $.ajax(). So your code should look like this in the js file:
$.post('/image/getCanvasImage', //this is your url
{
img : canvas.toDataURL('image/jpeg'),
email : email
}, function(data){
//whatever you wanna do with the returned data
}
);
Then in your action, import import sun.misc.BASE64Decoder package and you can write this code to save the canvas image:
def file = params.img.toString().substring((params.img.toString().indexOf(",")+1),params.img.toString().size())
byte[] decodedBytes = new BASE64Decoder().decodeBuffer(file)
def image = new File("mySavedImage.jpg")
image.setBytes(decodedBytes)
Should work!
Currently I am trying to implement a login validation system. I am using ajax so that users can get a response without being redirected to another page. My ajax function sends email and password that user has inputted, and get message in callback function, which can be in three types: email, password, or the actual HttpResponse object. But I have no idea how to render the given http response object using ajax and jquery. Is location.href an option? I am pasting the code below.
In javascript:
function loginSubmit(email, password) {
var d= "email=" + email + "&password=" + password;
$.ajax({
url: "/login",
type: "POST",
dataType: "text",
data: d,
success: function(m) {
if (m == "email") {
$("#emailMessage").html("There is no account associated with this email address.");
$("#emailError").show();
$("#emailError").fadeOut(5000, function() {});
} else if (m == "password") {
$("#emailMessage").html("There is no account associated with this email address.");
$("#emailError").show();
$("#emailError").fadeOut(5000, function() {});
} else {
}
}
});
}
in view function:
def login(request):
json = request.POST
e = json['email']
p = json['password']
u = User.objects.filter(email=e)
if (len(u)):
up = User.objects.filter(email=e, password=p)
if (len(up)):
return render_to_response('profile.html', context_instance=RequestContext(request))
else:
data = "password"
c = RequestContext(request, {'result':data})
t = Template("{{result}}")
datatype=u"application/javascript"
return HttpResponse(t.render(c), datatype)
else:
data = "email"
c = RequestContext(request, {'result':data})
t = Template("{{result}}")
datatype=u"application/javascript"
return HttpResponse(t.render(c), datatype)
p.s. Currently I am using a dummy template and HttpResponse to send data to the ajax success callback function. Is there a more efficient way to accomplish this (send back json data)? I will wait for your replies guys!
from django.contrib.auth import authenticate, login as auth_login
def login(request):
# Use authentication framework to check user's credentials
# http://djangosnippets.org/snippets/1001/ for auth backend
user = authenticate(
email = request.POST['email'],
password = request.POST['password'], )
if user is not None:
# Use Auth framework to login user
auth_login(request, user)
return render_to_response('profile.html',
context_instance=RequestContext(request))
else:
# Return Access Denied
# Never return bad email/bad password. This is information leakage
# and helps hackers determine who uses your platform and their emails.
return HttpResponse("Failed: Bad username or password", status=403)
function loginSubmit(email, password) {
$.ajax({
url: "/login",
type: "POST",
data: {email:email, password:password},
success: function(data) {
var returned_html = $(data);
$("#target_profile_area").clear().append(returned_html);
},
error: function(jqXHR) {
if (jqXHR.statusCode == 403) {
$("#loginMessage").text("Your login details are incorrect");
} else {
$("#loginMessage").text("Error Contacting Server");
}
$("#loginError").show();
$("#loginError").fadeOut(5000, function() {});
}
});
}
I am using the following view for my Ajax post function and the call is repeatedly failing. I can seem to get what is wrong here. Can anybody point it out
def interview(request):
if request.is_ajax():
if request.method == 'POST':
name = request.POST.get('name', False)
email = request.POST.get('email', False)
skype_id = request.POST.get('skype_id', False)
phone = request.POST.get('phone', False)
time_slot_1 = request.POST.get('time_slot_1', False)
time_slot_2 = request.POST.get('time_slot_2', False)
time_slot_3 = request.POST.get('time_slot_3', False)
recipients = ['abc#gamil.com']
subject = 'Interview Appointment'
message = "The following person has registered for interview \n Name: %s \n Email: %s \n Skype Id: %s \n Phone: %s \n Slot-1: %s \n Slot-2: %s \n Slot-3: %s" % ( name, email, skype_id, phone, time_slot_1, time_slot_2, time_slot_3)
from django.core.mail import send_mail
send_mail(subject, message, sender, recipients)
return_message = "Sent mail"
return HttpResponse(return_message,mimetype='application/javascript')
My javascript is also pretty straightforward, but I don't know why am I getting error message
var email_val = $("#emailp").val();
var skype = $("#skypeId").val();
var phone = $("#phone_no1").val();
var t1 = $("#time_slot1").val();
var t2 = $("#time_slot2").val();
var t3 = $("#time_slot3").val();
$.ajax({
type: "POST",
url: "/interviews/interview_form/",
data: {
'name': name_val,
'email': email_val,
'skype_id': skype,
'phone': phone,
'time_slot_1': t1,
'time_slot_2': t2,
'time_slot_3': t3,
},
success: function(){
alert("call successful");
$('#complete').html("Form has been Submitted");
},
error: function(){
alert("call failed");
$('#error').html("Form could not be Submitted! Please try again");
},
});
Any insights are welcome.
You need to submit the CSRF token as well, to prevent XSS attacks. The most straightforward way in your code would be to add csrfmiddlewaretoken: '{{ csrf_token }}' to your data dictionary. Also, make sure your view is returning a context_instance so that the CSRF token is available.