How to execute a XMLHttpRequest using onchange event of the select - javascript

I'm developing a web page and this web page I can't use php or another dynamic programming language and in this web page I want to get the result of a response from a REST API. I manage do this when the page is opened through this code:
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "https://..../select", true); // false for synchronous request
xmlHttp.send();
xmlHttp.onreadystatechange = processInitialRequest;
function processInitialRequest(e) {
if ((xmlHttp.readyState == 4) && (xmlHttp.status == 200)){
var jsonObj = JSON.parse(xmlHttp.responseText);
var i = 0;
var select = document.getElementById("select_manufacturers");
var content = select.innerHTML;
for (i = 0; i< jsonObj.manufacturers.length; i++){
//var opt = document.createElement("option");
var arObj = jsonObj.manufacturers[i];
var enable = arObj['enabled'];
if(enable)
select.options[select.options.length] = new Option(arObj['manufacturer'],arObj['id']);
}
}
}
I have some select components in my webpage:
<select id="select_manufacturers" onchange="processManufacturersChange()">
</select>
<select id="select_devicetypes">
</select>
And when I change the select_manufacturers I want to load the select_devicetypes but when I do this:
function processManufacturersChange(){
var select = document.getElementById("select_manufacturers");
var valueManufacturer = select.options[select.selectedIndex].value;
var textManufacturer = select.options[select.selectedIndex].text;
xmlHttpDeviceTypes.open("https://...../select?manufacturerId=" + valueManufacturer,true);
//process stop here
xmlHttpDeviceTypes.send();
xmlHttpDeviceTypes.onreadystatechange = processDeviceTypesRequest;
}
the process has stopped at the open line. I already enabled CORS at my API but it does not work.
Console said:
(index):149 Uncaught DOMException: Failed to execute 'open' on
'XMLHttpRequest':
'https://.....amazonaws.com/v1/.../select?manufacturerId=10' is not a
valid HTTP method.
at processManufacturersChange (http://localhost/jquery/jquery-ui-1.12.1/:149:21)
at HTMLSelectElement.onchange (http://localhost/jquery/jquery-ui-1.12.1/:58:75)
Anyone can help me?
Thanks for understanding.

is not a valid HTTP method.
The first argument to open has to be the HTTP method, like GET, PUT or POST.
You are passing a URL as the first argument. The URL should be the second argument.

Related

Why aren't my values coming from webservice inserting into select tag via AJAX?

so I have am making a GET request to my webservice class to get the emails of all users to store inside of <option> tags within <select> tags. When I print to the console, everything looks correct, but my <select> tags aren't even showing up on the page when I run it in the browser. I have ensured that the id that I'm grabbing is correct, the values are being received from the webservice, information is being parsed correctly, etc... Also, this function is using "onload" from the body tag. Here is my code:
function loader() {
let xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200){
let val = JSON.parse(this.responseText);
let len = val.length;
document.getElementById("ulistval").innerHTML = "select name='emailname' id='emailget'>";
for(let i = 0; i < len; i++){
document.getElementById("ulistval").innerHTML = `<option value="${val[i].email}">${val[i].email}</option>`;
console.log(`<option value="${val[i].email}">${val[i].email}</option>`);
}
document.getElementById("ulistval").innerHTML = "</select>";
}
}

django not identifing ajax, and not able to post

Found on questions on is_ajax- Django request.is_ajax returning false - but that does not solve anything for me. I'm working around this by using 'ajax' in the GET...
I'm also trying to post through AJAX, but I can't find the results.
My AJAX handler is this:
function getContent(pageGet,method,post,target) {
if (typeof(post) ==='undefined') post = "";
if (typeof(method) ==='undefined') method = "GET";
if (typeof(target) ==='undefined') target = "body";
pageGet = '/?ajax=home/'+pageGet.replace('?','&');
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
var body = document.getElementById(target);
if (this.readyState == 4) {
if (this.status == 200) {
body.innerHTML = this.responseText;
var scripts = body.getElementsByTagName("script");
var script_amount = scripts.length;
for( var i = 0; i < script_amount; ++i)
eval(scripts[i].innerHTML);
} else if (this.status == 0) {
getContent('main.html');
} else {
body.innerHTML = "Failed with "+this.status;
}
}
};
xhttp.open(method, pageGet, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(post);
return false;
}
As, I said this never registers in is_ajax, but AJAX is working fine. This is the value of pageGet:
/?ajax=home/forms/genericForm.html&form=UserForm
and this the value of post:
username=sdf&password=dfs&=Submit&
Obviously method="POST".
This gets to my view.py, and the request.GET is populated properly with 'ajax' (my workaround for the other problem), and 'form'. But request.POST is empty, as well as request.body which is alluded to here - Ajax POST not sending data when calling 'request.POST' in Django view and some other answer.
There are also mentions of a "CSRF" token, but I don't know what I'm doing wrong. The view code just prints request.GET,body, and POST, and is_ajax.
Please, only pure JS solutions.
Progress
I managed to get post to work - by default CSRF is enabled, and you must set the AJAX header with it. If anyone figures the is_ajax part I'd be obliged.

How to insert form into mysql without leaving the page (javascript+html)

I'm trying to insert a new user into mysql. I have tried to use jQuery, but it doesn't seem to be working. I tried to use pure javascript, but it's the same. It has no response after I click on the button. What's wrong?
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var shop = document.getElementById("shop");
var http = new XMLHttpRequest();
http.open("POST", "http://xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var params = "ac=" + acR + "&pw1="+pw1 "&shop="+ shop;
http.send(params);
http.onload = function() {
alert(http.responseText);
};
}
There's a quite a few problems in your JS code, I've tidied it up here and run it locally to a page called xyz.php, so that'll get the AJAX call to work but you'll need to post your PHP code to get any help with your DB queries
var regBtn = document.getElementById("regBtn");
regBtn.addEventListener("click", submitForm, false);
function submitForm() {
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
var http = new XMLHttpRequest();
// removed the http:// protocol, assuming you're going for a local AJAX call
http.open("POST", "xyz.php", true);
http.setRequestHeader("Content-type","application/x-www-form-urlencoded");
// get values of the form fields, don't submit the full element
// also added the plus (+) character before the final pw1
var params = "ac=" + acR.value + "&pw1=" + pw1.value;
http.send(params);
http.onload = function() {
alert(http.responseText);
}
}
I've attached a screen shot showing Chrome Dev Tools happily recording successful AJAX requests
Try to use a JQuery post.
var acR = document.getElementById("ac2");
var pw1 = document.getElementById("pw1");
$.post( "xyz.php", { ac: acR, pw1: pw1 })
.done(function( data ) {
alert( "Data inserted: " + data );
});
Backend handles this post and then implement the insert action for example in NodeJs(express)
app.post("/xyz", function(req, res, next) {
var obj = {};
obj[acR] = body.ac;
obj[pw1] = body.pw1;
mysql.insert(obj);
});

Load a JavaScript event the last in CRM form

I have one image saved in Notes with every form in my CRM Online 2013 custom entity. I am using the following code to query the image and show it in an Image tag in a Web Resource on the form. For debugging purposes I was calling the following code through a button, but I want this process of querying the Notes and displaying the image in the web resource to be automatic when the form load. Here is my code:
<html><head><meta charset="utf-8"></head>
<body>
<img id="image" src="nothing.jpg" style="width: 25%; height: auto;" />
<script type="text/javascript">
$(windows).load(function()
{
var recordId = window.parent.Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
var ODATA_ENDPOINT = "XRMServices/2011/OrganizationData.svc";
var objAnnotation = new Object();
ODataPath= serverUrl+ODATA_ENDPOINT;
var temp= "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
var result =serverUrl + ODATA_ENDPOINT + temp;
var retrieveRecordsReq = new XMLHttpRequest();
retrieveRecordsReq.open('GET', ODataPath + temp, false);
retrieveRecordsReq.setRequestHeader("Accept", "application/json");
retrieveRecordsReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveRecordsReq.onreadystatechange = function ()
{
if (this.readyState == 4 /* complete */)
{
if (this.status == 200)
{
this.onreadystatechange = null; //avoids memory leaks
var data = JSON.parse(this.responseText, SDK.REST._dateReviver);
if (data && data.d && data.d.results)
{
SuccessFunc(JSON.parse(this.responseText, SDK.REST._dateReviver).d.results);
}
}
else
{
alert(SDK.REST._errorHandler(this));
}
}
};
var x = new XMLHttpRequest();
x.open("GET", result, true);
x.onreadystatechange = function ()
{
if (x.readyState == 4 && x.status == 200)
{
var doc = x.responseXML;
var title = doc.getElementsByTagName("feed")[0].getElementsByTagName("entry")[0].getElementsByTagName("content")[0].getElementsByTagName("m:properties")[0].getElementsByTagName("d:DocumentBody")[0].textContent;
document.getElementById('image').src ="data:image/png;base64,"+title;
}
};
x.send(null);
});
</script>
</body></html>
I have removed the button tag..now I want this the query to happen on page Load, but nothing happens when I refresh the form. In my opinion the function loads before the annotation loads. Is there a way to make it wait and load the last?
If you want to wait for the parent window to load I think $(windows).load(myFunction); should do the trick.
Maybe $ is undefined because you did not add jQuery to your webressource.
There are also a few little mistakes and unattractive things:
First:
You will get a wrong server url.
If you want to access the Xrm-object in a webresource you always have to use window.parent.Xrm or you put it in a variable var Xrm = window.parent.Xrm;
For example:
var Xrm = window.parent.Xrm;
var recordId = Xrm.Page.data.entity.getId();
var serverUrl = Xrm.Page.context.getServerUrl().toString();
Second:
The ODataPath variable is not declared. Use var ODataPath= serverUrl+ODATA_ENDPOINT; instead. By the way the value of the ODataPath has nothing to do with OData. It is more the REST-Endpoint of Dynamics CRM.
My script would look like this:
var Xrm, recordId, serverUrl, restEndpointUrl, odataQuery, fullRequestUrl, xmlRequest;
Xrm = window.parent.Xrm;
recordId = Xrm.Page.data.entity.getId();
serverUrl = Xrm.Page.context.getServerUrl().toString();
restEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc";
^ I think a '/' was missing there
odataQuery = "/AnnotationSet?$select=DocumentBody,FileName,MimeType,ObjectId&$filter=ObjectId/Id eq guid'" + recordId + "'";
fullRequestUrl = restEndpointUrl + odataQuery;
I also dont understand why you use the second HttpRequest.
All of this code is not tested.

Javascript only works when javascript console is open on chrome

I have a script (javascript) that works in firefox but not in chrome or IE. I opened chromes debug console to find the problem. No errors are reported and the code works perfectly. Running it again with the console closed does not work again.
I verified that the version of the script is correct (not old and cached). The console does not report any warnings or errors.
I tried putting in simple logging that writes to a div at the bottom of the page - no information.
(in the debug console it works - including logging info in the div).
The function is the callback after an XMLHttpRequest is made to the server.
I verified that the php script is called by including error_log calls. The error_log shows the return value correctly. A page refresh also show the row has been deleted.
It appears as if the function removeRow() is never called unless the console is open. (method or reserved words conflict??) Tried changing the function name to delRow (including callback) - still not working.
All other Ajax calls seem to work fine.
A Code snippet follows:
var pos = 0;
var xhr;
function eraseRow() {
var myImage = this;
var fullid = myImage.id;
// split row no and record id eg 5_1223 => row=5 and recordid=1223
var idComponents = fullid.split("_");
if (idComponents.length > 1) { // check if image has complete row info
rowid = idComponents[1]; // extract row number from id
pos = parseInt(idComponents[0]);
xhr = new XMLHttpRequest(); // only support IE8 or +
xhr.onreadystatechange = removeRow;
xhr.open("GET","valid_del.php$delrow="+rowid;
xhr.send(null);
}
}
function removeRow() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var err = document.getElementById("errormsg");
var str = xhr.responseText;
err.innerHTML = "Server returned "+str;
if (str === "go-ahead") {
var table = document.getElementById("tableid");
table.deleteRow(pos);
}
}
}
}
PHP (valid_del.php):
<?php
include(funclib.php);
if (isset($_GET['delrow']) && strlen($_GET['delrow'] > 0) {
$recid = $_GET['delrow'];
$db = createDbConn(); // function that connects to mysql server db
$result = $db->query("delete from doclibrary where doc_id='$recid'");
if ($result===true) {
echo 'go-ahead';
error_log('Script successful - returns go-ahead',0);
} else {
echo 'stop';
error_log('Script not successful - returns stop',0);
}
$db->close();
} else {
echo 'stop';
error_log('Script not given record id - returns stop',0);
}
?>
I think the DOM is not ready, try to add your code calls into window.onload, or in $(document).ready if you are using JQuery.

Categories