JavaScript Handlebars give no error but does not work - javascript

I am trying to replace text in my page using handlebars. But its not working and i am not getting any errors either.
The following code kicks in when the user presses the submit button
<button type="submit" id="add_lunch" class="button button-contactForm boxed-btn" onclick="addToCart()">Submit</button>
this then
function addtoCart() {
var request = new XMLHttpRequest();
var base_id = $("input[name='base_id']:checked").val();
var protein_id = $("input[name='protein_id']:checked").val();
var dessert_id = $("input[name='dessert_id']:checked").val();
var side_id = $("input[name='dessert_id']:checked").val();
request.open('POST', '/cart');
request.onload = () => {
// Extract JSON data from request
var template = Handlebars.compile(document.querySelector('#js_result').innerHTML);
var data_response = JSON.parse(request.responseText);
var content = template({'base_name': data_response.base.name});
console.log("****" + data_response.base.name)
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#add_lunch').onclick = () => {
document.querySelector('#media_js_body').innerHTML += content;
};
});
}
var data = new FormData();
data.append('base_id', base_id);
data.append('protein_id', protein_id);
data.append('side_id', side_id);
data.append('dessert_id', dessert_id);
// Send request
request.send(data);
return false;
}
plus the template
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<script id="js_result" type="text/x-handlebars-template">
{{ base_name }}
</script>
<script src="{{ url_for('static', filename='js/util.js') }}"></script>
What i have figured out so far is that it has something to do with DOM state? and onclick even.
Any suggestions and corrections?

i do not know if it was the coffee i drank, but after a few sips and few changes it seems to work partially now. i am getting the text being placed in the right place.
Now i only have to make sure that the values from data_response gets transferred in content as well
This is what i changed.
function addToCart() {
var request = new XMLHttpRequest();
var limit=2;
var base_id = $("input[name='base_id']:checked").val();
var protein_id = $("input[name='protein_id']:checked").val();
var dessert_id = $("input[name='dessert_id']:checked").val();
var side_id = [];
$.each($("input[name='side_id']:checked"), function(){
side_id.push($(this).val());
});
if(side_id.length==limit) {
request.open('POST', '/cart');
request.onload = () => {
// Extract JSON data from request
var data_response = JSON.parse(request.responseText);
var templateInfo=document.querySelector('#js_result').innerHTML
console.log("TempInfo:" + templateInfo)
var template = Handlebars.compile(templateInfo);
var content = template({'base_name': data_response.base.name});
console.log("DataResponse:" + data_response.base.name);
console.log("Content:" + data_response.base.name);
document.querySelector('#media_js_body').innerHTML += content;
}
var data = new FormData();
data.append('base_id', base_id);
data.append('protein_id', protein_id);
data.append('side_id', side_id);
data.append('dessert_id', dessert_id);
// Send request
request.send(data);
} else {
alert("Kindly select "+limit+" sides")
}
return false;
}

Related

JavaScript is retrieving data from mysql database that is suppose to be deleted with AJAX delete method already

In the script , a button have an onclick function that call deleteByName function
<button onclick='deleteByName("name","view","view_value")' type='button'>
In this function , it use AJAX to execute delete method and calls search function to update page
function deleteByName (target,view,view_value){
var url = "http://localhost/assignment_web/index.php/facility/name/"+target;
request.open("DELETE", url, true);
request.send(null);
search("all");
}
In search function , it use AJAX get method to retrieve data and use updatePage attribute to update the innerHTML
function search(type) {
var target = "" ;
if(type=="district"|type=="name"){
var target = document.getElementById('option_txt').value;
}
var url = "http://localhost/assignment_web/index.php/facility/"+type+"/"+target;
request.open("GET", url, true);
request.onreadystatechange = updatePage;
request.send(null);
}
function updatePage() {
if (request.readyState==4) {
if (request.status==200) {
var serverData = request.responseText;
console.log("serverData: "+serverData);
var dataArr = JSON.parse(serverData);
var objLen = Object.keys(dataArr).length;
var view = document.querySelector('input[name="option"]:checked').value;
var view_value;
var html ="<ul>";
for(let i=0;i<objLen;i++){
var name =dataArr[i].Name_en ;
if(view=="district"){view_value = dataArr[i].District_en;}else if(view=="name"){view_value = dataArr[i].Name_en;
}else{view_value = "all" ; }
html = html+"<li>District : "+dataArr[i].District_cn+"&nbsp"+dataArr[i].District_en
+"</li>...<li><button onclick='deleteByName(\""+name+"\",\""+view+"\",\""+view_value+"\")' type='button'>delete</button>
<div name=\""+name+"_textBox\" id=\""+name+"_textBox\"></div></li><hr>" ;
}
html = html+"</ul>";
document.getElementById("displayArea").innerHTML = html;
}
}
}
The question is , in get method , it retrieved the data (shown in console.log(DataArr) ) i was deleted from the delete method before . How do i make sure the update function won't retrieve any data that is deleted before instead retrieving the data after the delete method is complete ...

How to assign input id to variable for concat with url api call

I'm loading data from api into html table and would like to use user input field to change api call.
<input id="stockInput" value="AAPL"></input>
<br/>
<button id="submit">Submit</button>
const stocksBody = document.querySelector("#stocks-table > tbody
#data");
var input = $("#stockInput").val();
var url = "https://api.iextrading.com/1.0//stock";
var quote = "/quote";
function setup() {
var button = select("#submit");
button.mousePressed(loadData);
}
function loadData(){
const request = new XMLHttpRequest();
request.open("get", url + input.val() + quote);
request.onload = () => {
try {
var response = JSON.parse(request.responseText);
console.log(response);
populateData(response);x
} catch (e) {
console.warn("Could not load data!");
}
};
request.send();
I expect stock symbol entered by user to return stock data.
You are calling .val() twice.
Change this line:
request.open("get", url + input.val() + quote);
// ^^^^^^ - remove

JSON AJAX Http request

I am working with a JSON file that I have, and I am linking it in my JavaScript.
I am trying to get it requested through AJAX to show up on my console.log, but I am just getting null for my readystatechange function. What am I doing wrong?
Also to better clarify I am doing this for my course and ideally what my goal is; I have a json file that I created (myjson.com), I have that URL its in my JavaScript, and I am trying to get that json url to update to my JavaScript so when I do a console.log it shows up the values of the objects from the json. Here's my code:
<div id="btn1"> Update </div>
<div id="output"></div>
<script>
var output = document.getElementById("output");
document.getElementById("btn1").onclick = function () {
var a = newXMLHttpRequest();
a.onreadystatechange = function () {
}
a.open("GET", "https://api.myjson.com/bins/z79bt", true);
a.send();
};
</script>
UPDATE
Code from the comment:
var output = document.getElementById("output");
document.getElementById("btn1").onclick = function () {
var a = new XMLHttpRequest();
a.onreadystatechange = function () {
if(this.readyState == 4) {
var myObj = this.responseText;
}
console.log(a);
}
a.open("GET", "api.myjson.com/bins/z79bt";, true);
a.send();
};
Two issues:
you're missing a space in newXMLHttpRequest
you're not doing anything inside the state change callback
(third: you're also not populating the output div)
See the live example here:
var output = document.getElementById("output");
document.getElementById("btn1").onclick = function () {
var a = new XMLHttpRequest();
a.onreadystatechange = function () {
if(a.readyState === XMLHttpRequest.DONE && a.status === 200) {
console.log(a.responseText);
output.textContent = a.responseText;
}
}
a.open("GET", "https://api.myjson.com/bins/z79bt", true);
a.send();
};
<div id="btn1"> Update </div>
<div id="output"></div>
UPDATE
Fixed code from the comment:
var output = document.getElementById("output");
document.getElementById("btn1").onclick = function () {
var a = new XMLHttpRequest();
a.onreadystatechange = function () {
if(this.readyState == 4) {
var myObj = this.responseText;
console.log(myObj);
}
}
a.open("GET", "https://api.myjson.com/bins/z79bt", true);
a.send();
};
<div id="btn1"> Update </div>
<div id="output"></div>

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.

Categories