This is my jsp code. I want to bind the catid parameter to url when I call getproductsub() and send ajax request.
r.open("GET", "url?catid=" + catid,true);
above line seems an error of my code.How can I fix it.
<select class="form-control" id="pcategory" name="pcategory" onchange="getproductsub();">
<script>
function getproductsub() {
var catid = document.getElementById('pcategory').value;
var url = window.location.href;
var r = new XMLHttpRequest();
r.onreadystatechange = function() {
if (r.readyState === 4 && r.status === 200) {}
};
r.open("GET", "url?catid=" + catid, true);
r.send();
}
</script>
Note that window.location.href gives the complete location including the parameters in the url at the current time. So ? might be included in it.
You can either use
var url = window.document.location.pathname;
And concat the url to the String passed to open().
r.open("GET", url + "?catid=" + catid, true);
OR
Use getRequestURL() as you are coding in jsp.
r.open("GET", "<%= request.getRequestURL()%>?catid=" + catid, true);
Related
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);
});
I am trying to get a very simple Stock API to work on JSFiddle.net using Quandl API: https://www.quandl.com/blog/api-for-stock-data
If I use the current ".csv" format as below, I am returned a CSV file. If I change the format to ".json" in my API, how do I recover the data so that I can use it on a website for example?
I believe I need to use a getJSON command, but I am confused as to how it works. Can someone help me out?
HTML:
<input type="text" id="symbol">
<button id="getPrice">Get Price!</button>
<div id="result">Stock Market Ticker</div>
JavaScript:
function getPrice() {
var symbol = $("#symbol").val();
var baseurl = "https://www.quandl.com/api/v3/datasets/WIKI/";
var stock = symbol+".csv";
var endurl = "column_index=4&rows=1&api_key='8mii36sd1q46uLgSTkLm";
var url = baseurl+ stock + "?" + endurl;
$("#result ").html("<a href = '" + url + "' >Hyperlink</a>");
}
$("#getPrice ").click(getPrice);
My OUTPUT using stock ticker KORS (.CSV file) is: Data Close
1/5/2016 40.72
I've recently answered to "How do I use a Quandl API?" with the following snippet, which you should adapt for your JSON:
var baseurl = "https://www.quandl.com/api/v3/datasets/WIKI/";
var endurl = "column_index=4&rows=1&api_key='8mii36sd1q46uLgSTkLm";
var quandlcode = "KORS"; // if is it's your choice?
var url = baseurl + quandlcode + ".json?" + endurl; // dont forget the "?"
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onload = function() {
var data = JSON.parse(this.responseText).dataset.data;
// {}.dataset.data is the data matrix in Quandl
// for most datasets as far as I know ...
// then process your own way
}
xhr.send();
I have my JavaScript function which does XMLHttpRequest. Here is my code.
function addbilldetails() {
// Cancel the form submit
event.preventDefault();
// The URL to POST our data to
var postUrl = 'http://example.com/post.php';
// Set up an asynchronous AJAX POST request
var xhr = new XMLHttpRequest();
xhr.open('POST', postUrl, true);
// Prepare the data to be POSTed
var clientId = "clientid",
submittype = "a",
name = encodeURIComponent(document.getElementById('name').value),
billno = encodeURIComponent(document.getElementById('billno').value),
mobileno = encodeURIComponent(document.getElementById('mobileno').value),
phoneno = encodeURIComponent(document.getElementById('phoneno').value),
netAmount = encodeURIComponent(document.getElementById('netAmount').value);
var params = 'clientId=' + clientId +
'&billno=' + billno +
'&mobileno=' + mobileno +
'&phoneno=' + phoneno +
'&netAmount=' + netAmount +
'&type=' + submittype +
'&name=' + name;
// Replace any instances of the URLEncoded space char with +
params = params.replace(/%20/g, '+');
// Set correct header for form data
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
// Handle request state change events
xhr.onreadystatechange = function() {
// If the request completed
if (xhr.readyState == 4) {
statusDisplay.innerHTML = '';
if (xhr.status == 200) {
// If it was a success, close the popup after a short delay
statusDisplay.innerHTML = 'Saved!';
document.getElementById('save').disabled = false;
// window.setTimeout(window.close, 1000);
} else {
// Show what went wrong
statusDisplay.innerHTML = 'Error saving: ' + xhr.statusText;
}
}
};
// Send the request and set status
xhr.send(params);
statusDisplay.innerHTML = 'Saving...';
document.getElementById('save').disabled = true;
}
Now, the above code works perfectly and returns 200 on POST. But I want it to return custom message on the UI based on the value posted.
If the value POSTed is less than the value in the database, I want it to give "Enter Valid number" or something like this.
I am quiet new to XMLHttpRequest . I do not know how to achieve that. Any help would be highly appreciated.
Instead of statusDisplay.innerHTML = 'Saved!'; have you considered:
statusDisplay.innerHTML = xhr.responseText;
If you do this, then your statusDisplay will be equal to whatever your post.php echos out.
For example, in post.php
<?php
//handling $_POST['clientId'] ... etc
if (error)
echo "Enter Valid Number";
else
echo "Saved!";
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.
i have a javascript function as follows
function GetSelectedItem()
{
var e = document.getElementById("country");
var strSel = e.options[e.selectedIndex].value;
alert(strSel);
var url = "${createLink(controller:'country', action: 'wholeTestUnits', id: strSel)}"
alert(url);
}
i want to go to that url action when i click the submit button like
<button class="submit_small" onClick="GetSelectedItem();">
<span><g:message code="default.button.submit.label" /></span>
</button>
This ${createLink} is not working.
A better way of doing this which doesn't require the JavaScript code be in your GSP would be the following:
<button class="submit_small" onClick="GetSelectedItem();" data-url="${createLink(controller:'country', action: 'wholeTestUnits')}">
<span><g:message code="default.button.submit.label" /></span>
</button>
function GetSelectedItem() {
var button = event.target;
var e = document.getElementById("country");
var strSel = e.options[e.selectedIndex].value;
var url = button.getAttribute("data-url") + "/" + strSel;
}
I think you have a serverside/clientside problem. The createLink is run on the server, the JS is run on the client...
Try:
var url = '${createLink(controller:'country', action: 'wholeTestUnits')}' + strSel ;
As I think , you are not getting value of strSel in your link.
You can try this.
function GetSelectedItem()
{
var e = document.getElementById("country");
var strSel = e.options[e.selectedIndex].value;
alert(strSel);
var url = "${grailsApplication.config.grails.serverURL}/country/wholeTestUnits/" + strSel
alert(url);
}
Instead of using the createLink you could build your own URL and use that one instead. You have to pay attention to capital letters in the controller name, though.
var url="${ createLink(controller:'testcontroller', action:'getData') }";
is equivalent to
var url = "/testcontroller/getData;
If you want to pass in arguments from javascript to the controller you can do like this.
var url = "/testcontroller/getData?arg0=" + arg0 + "&arg1=" + arg1;
To extract the arguments in the controller you do use the params keyword.
So to print the parameters in the controller you do this:
println params.arg0
println params.arg1
--in gsp file--
<a href="#" onclick="callAjax('${createLink(controller:'shift',action: 'addShift')}');" >Add/Edit Shift</a>
--in js file--
function callAjax(path){
//path->/shift/addShift
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("updateContent").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", path, true);
xmlhttp.send();
}
try this:
var url = "${createLink(controller:'country', action: 'wholeTestUnits', params:[id: strSel], absolute: true)}"