I have developed a chrome extension and I am inserting json data in mysql through django service. I want to send data from django to java script which is in chrome extension.
popup.js:
document.addEventListener('DOMContentLoaded', documentEvents, false);
function myAction(fname,femail,fpassword) {
var str = "name="+ fname.value + "&email=" + femail.value + "&password=" + fpassword.value;
var xmlhttp = new XMLHttpRequest();
alert(str);
var theUrl = "http://127.0.0.1:8000/polls/?";
xmlhttp.open("POST", theUrl, true);
xmlhttp.onreadystatechange = function() {
//alert(xmlhttp.readyState + " " + xmlhttp.status);
if (xmlhttp.readyState == 4){
alert("entered");
}
else{
alert("not entered");
}
};
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send(str);
}
function loadDoc() {
var xhttp = new XMLHttpRequest();
var theUrl = "http://127.0.0.1:8000/polls/?";
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("output").innerHTML = this.responseText;
}
};
xhttp.open("GET",theUrl,true);
xhttp.send();
}
function documentEvents() {
var submitButton = document.getElementById('submit')
submitButton.addEventListener('click',
function(event) {
var formId = document.getElementById('test');
var name = document.getElementById('name');
var email = document.getElementById('email');
var password = document.getElementById('password');
myAction(name,email,password);
});
}
views.py :
from django.http import HttpResponse
from django.http import HttpResponseRedirect, HttpResponse
from .models import UserProfile
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def index(request):
req = request.method
t = request.GET
print(req)
name = request.POST.get('name')
email = request.POST.get('email')
password = request.POST.get('password')
savedata = UserProfile(name=name,email=email,password=password)
savedata.save()
print('Hello %s %s %s' % (name, email, password))
return HttpResponse('successfully inserted')
My problem is how to send data from views and how to get that data in java script.Is there a way to define java script method name in django views. Please provide me the clear code of views and java script
Related
How do I make a post request from java to flask?
Why can I get the data sent to the server?
<button name="send" id = "sendbutton">Send</button>
document.getElementById("sendbutton").addEventListener('click', () => {
var image = canvas.toDataURL();
var r = new XMLHttpRequest();
r.open("POST", "http://127.0.0.1:5000/truthMask", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
//alert("Success: " + r.responseText);
console.log("sent");
};
r.send(input="test");
});
#app.route('/truthMask', methods=['POST'])
def set_truthMask():
print("Got the data")
foo = request.args.get("input")
print("Print the data: {}".format(foo))
return "sent"
JS Code
document.getElementById("sendbutton").addEventListener('click', () => {
var image = canvas.toDataURL();
var r = new XMLHttpRequest();
r.open("POST", "http://127.0.0.1:5000/truthMask", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
//alert("Success: " + r.responseText);
console.log("sent");
};
// Send data in below way from JS
r.send(JSON.stringify({"input": "test"}));
});
Python Flask API
import json
#app.route('/truthMask', methods=['POST'])
def set_truthMask():
print("Got the data")
foo = json.loads(request.data.decode())["input"]
print("Print the data: {}".format(foo))
return "sent"
Don't forget to import json
I have a page that uses a function for getting some data, with a GET xhttp request, from a database (get_worktime_list()).
On the same page, I can add some data to the database with a form using a POST xhttp request and after a success (saved in the response) I will get the content included the new line from the database with the same function get_worktime_list().
The problem is that when getworktime is called after the POST request, get_worktime_list() makes another POST request instead of a GET. why???
function http_request(post_data, end_point, type)
{
console.log("HTTP");
var res = 0;
//var data = "data=0&username="+stored_token.username+"&token="+stored_token.token;
var data = "data=0&"+post_data;
console.log(data);
// Check if is valid token/username from database
const url = "http://192.168.1.188:5000/services/"+end_point;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res = JSON.parse(xhttp.responseText);
}
};
if (type == "GET")
{
console.log(url+"?"+post_data);
xhttp.open("GET", url+"?"+post_data, false);
}
else
{
console.log("Data: "+data);
xhttp.open("POST", url, false);
}
xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(data);
xhttp.abort();
return res;
}
This add data to DB
function addworktime(username,token)
{
console.log("Aggiungo ore");
var date = document.getElementById("data").value;
var type = document.getElementById("turno").value;
var pay = document.getElementById("paga").value;
var emp = document.getElementById("dipendente").value;
var ore = document.getElementById("num_ore").value;
var data = "username="+username+"&token="+token+"&day="+date+"&turn_type="+type+"&pay="+pay+"&emp="+emp+"&ore="+ore;
var res = http_request(data,"admin/dipendenti/addtime.php","");
//console.log(res);
if (res.insert_ok == 1)
{
display_time_table(0,0,null);
} else {
console.log(res);
}
}
This function makes a GET request when a page load and a POST request when called by addworktime()
function display_time_table(from,to,cf)
{
let time_list_table = document.getElementById("list-container");
var time_list = get_worktime_list(saved_data.username,saved_data.token,from,to,cf);
let time_table = generate_time_list_table(time_list);
time_list_table.innerHTML = time_table;
}
function get_worktime_list(username,token,date_from,date_to,cf)
{
var data = "username="+username+"&token="+token;
if (cf != "" || cf != null)
{
data = data+ "&dipendente="+cf;
}
if (date_from != 0)
{
data = data +"&date_from="+date_from;
}
if (date_to != 0)
{
data = data + "&date_end="+date_to;
}
var time_list = http_request(data,"admin/dipendenti/getworktime.php", "GET");
return time_list;
}
The server can only accept GET requests for that API and obviously, I get a parse error parsing the JSON response.
Thanks for help
So, this is my function to send email, but its not posting correctly...It runs, loads the file .php, returns the data and display it on the status's div, but the POSTs are empty. What is wrong? I'm pasting this at the bottom of the page, after the jquery call.
What am I doing wrong?
function sendemail(){
var name = document.getElementById('name').value;
var email = document.getElementById('email').value;
var subject = document.getElementById('subject').value;
var msg = document.getElementById('message').value;
var status = document.getElementById('status').value;
var hr = new XMLHttpRequest();
var url = "send-email.php";
var vars ="name="+name+"&email="+email+"&subject="+subject+"&msg="+msg+"&status="+status;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
setTimeout(function () {
hr.send(vars);
}, 500);
document.getElementById('status').innerHTML = "Sending...";
}
Thanks.
Posting this because I found a lot of jquery answers, but no raw javascript answers.
So I have a function to post a comment to a comment section, and I want the comment section to refresh after posting a comment, But for some reason my code isn't working.
The code for loading the comment section:
function loadCommentSection() {
console.log("loading section")
imgid = imgid.replace("img/pic (", "");
imgid = imgid.replace(").jpg", "");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("commentsection").innerHTML = this.responseText;
}
};
xhttp.open("GET", "commentsection.php?imgid=" + imgid, true);
xhttp.send();
}
and the code for submitting the comment:
function submitComment() {
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var comment = document.getElementById("comment").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("msg").innerHTML = this.responseText;
}
};
xhttp.open("GET", "comment.php?imgid=" + imgid + "&title=" + title + "&comment=" + comment + "&name=" + name, true);
xhttp.send();
loadCommentSection();
}
The problem is that the loadCommentSection function in the submitComment function isn't executing.
You should allow the comment to be sent to the server and be registered before calling loadCommentSection. So, it is probably best to call it when the response becomes available:
function submitComment() {
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var comment = document.getElementById("comment").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("msg").innerHTML = this.responseText;
loadCommentSection(); // <<---- moved here.
}
};
xhttp.open("GET", "comment.php?imgid=" + imgid + "&title=" + title + "&comment=" + comment + "&name=" + name, true);
xhttp.send();
}
What i want to do is when we click on Reply button , the From address field will be populate with the email-id (default team's default queue's email-id). Current scenario is populated with logged in user.
I used the following js code onLoad, but I am getting an error that says "Object doesn't support property or method getAttributeValue
function CheckEnquiryReplyAddress() {
// Only complete this validate on Create Form
var formType = Xrm.Page.ui.getFormType();
var emailStatus = Xrm.Page.getAttributeValue("statecode").getValue();
var emailDirection = Xrm.Page.getAttributeValue("directioncode").getValue();
if (formType == 1 || (formType == 2 && emailStatus == "Open")) {
if (emailDirection == "1"){
var previousEmailId=getExtraqsParam("_InReplyToId", window.parent.location.search);
//getting context from the parent window
var context = Xrm.Page.context;
try {
var serverUrl = context.getServerUrl();
//The XRM OData end-point
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var query="/EmailSet?$select=ActivityId,ActivityTypeCode,DirectionCode,";
query=query+"ToRecipients,Email_QueueItem/QueueId&$expand=Email_QueueItem&$filter=ActivityId eq guid'" + previousEmailId +"'";
query =serverUrl+ODATA_ENDPOINT+ query;
var request= new XMLHttpRequest();
request.open("GET", query, false);
request.setRequestHeader("Accept", "application/json");
request.setRequestHeader("Content-Type", "application/json; charset=utf-8");
request.onreadystatechange=function(){ CompleteEnquiryReplyCheck(request,serverUrl);}
request.send(null);
}
catch(e) {
alert(e.Description);
}
}
}
}
function CompleteEnquiryReplyCheck(request,url)
{
if (request.readyState==4) {
if(request.status==200) {
var queue=JSON.parse(request.responseText).d.results[0];
if (queue != null) {
var queueId = queue.Email_QueueItem.results[0].QueueId.Id;
var lookup = new Array();
var lookupItem = new Object();
lookupItem.id = queueId;
lookupItem.name = queue.Email_QueueItem.results[0].QueueId.Name;
lookupItem.typename = "queue";
lookup[0] = lookupItem;
Xrm.Page.getAttribute("from").setValue(lookup);
}
}
}
}
The get attribute value method is incorrect, to get value of an attribute use the following:
var attributeValue = Xrm.Page.getAttribute("attributeName").getValue();
So, in your case it would be:
var emailStatus = Xrm.Page.getAttribute("statecode").getValue();
var emailDirection = Xrm.Page.getAttribute("directioncode").getValue();