What is wrong with my javascript function? (XMLHttpRequest) - javascript

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.

Related

Javascript GET request after POST request

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

Function output empty by succesfull AJAX response

There's an issue with my function in the AJAX.
I create an AJAX call to a PHP file that returns JSON.
For loop this JSON I created a fucntion that I run if the AJAX is successfull.
But in practice the data is empty.
<script>
document.getElementById("getproducts").addEventListener("submit", sendAjax);
function sendAjax(event) {
var q = document.getElementById('search').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
display(this.responseText);
}
}
xhttp.open("POST", "results.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('search='+q);
event.preventDefault();
}
function display( jsdata ){
for ( var key in jsdata ){
var htmltabel = '';
var datanode = document.createElement("div");
htmltabel += '<div class="id">' + jsdata[key]['id'] + '</div>';
content = htmltabel;
datanode.innerHTML = content;
document.getElementById("resultt").appendChild(datanode);
}
}
</script>
If I code the JSON hardcode in the function like this than everything is okay.
var hardcoded = {"1736":{"id":"1736","post_title":"Test explode","_sku":"12345","_stock":null,"_price":"9.50"}}
//PART OF THE CODE
if (this.readyState == 4 && this.status == 200) {
display(hardcoded);
}
How can I fix this that the function use the responded JSON?
here is a corrected script, You should just convert the responseData from string to Json Object!
document.getElementById("getproducts").addEventListener("submit", sendAjax);
function sendAjax(event) {
var q = document.getElementById('search').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
display( JSON.parse(this.responseText) ); // You should convert the response from string to a valid JSON
}
}
xhttp.open("POST", "results.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('search='+q);
event.preventDefault();
}
function display( jsdata ){
for ( var key in jsdata ){
var htmltabel = '';
var datanode = document.createElement("div");
htmltabel += '<div class="id">' + jsdata[key]['id'] + '</div>';
content = htmltabel;
datanode.innerHTML = content;
document.getElementById("resultt").appendChild(datanode);
}
}

Send data from Django to java script(in Chrome extension)

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

Get the txt file into the push() method?

Please help me!
I have Script:
var titles =[];
titles.push('I want file txt in here');
I can not get the txt file into the titles.push, so I need some help!
function readTextFile(){
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "text.txt", false);
rawFile.onreadystatechange = function (){
if(rawFile.readyState === 4){
if(rawFile.status === 200 || rawFile.status == 0){
var allText = rawFile.responseText;
console.log(allText);
}
}
}
rawFile.send(null);
}
I do not have a text file ready to show so I used what you should be reading about XMLHttpRequest.responseText you do not want to use onreadystatechange but maybe xhr.onload I left some console.log()s in the code so you can play around with it.
var titles =[];
titles.push('I want file txt in here');
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText', true);
xhr.responseType = 'text';
xhr.onload = function () {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
//console.log(xhr.response);
//console.log(xhr.responseText);
// not needed but do not want to push the entire page
// to titles so lets find just one title
var parser = new DOMParser();
var doc = parser.parseFromString(xhr.responseText, "text/html");
var title = doc.querySelector('h1');
// console.log(title);
titles.push(title);
logTitles();
}
}
};
xhr.send(null);
function logTitles() {
console.log(titles);
};

Change the reply email address to the queue's email address in dynamic crm 2011

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();

Categories