I don't know if I am just thinking too hard about this or what. I just want to be able to select a specific option based on the result I get from a call. Currently call produces City, State, Country based on Zip code. The response from the GET is "Sacramento | CA | United States" I can easily put the responses into input boxes, but I can't figure out how to select an option based on the response. Is this possible? I've been looking through some of the method properties and i'm not really seeing anything that I can use.
Here is the Get script.
<script type="text/javascript">
var req;
var oldData;
var doesNotSupport = true;
function getAddress(url, number)
{
if (number == "" || oldData == number || !doesNotSupport)
return;
oldData = number;
document.getElementById('city').value = "Searching ...";
document.getElementById('state').value = "Searching ...";
document.getElementById('country').value = "Searching ...";
if (window.XMLHttpRequest) {
req = new XMLHttpRequest;
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
}
if (req) {
req.onreadystatechange = processReqChange;
req.open("GET", url + '?number=' + number + '&zip=' + number, true);
req.send(null);
} else {
alert("Your browser does not support XMLHttpRequest technology!");
doesNotSupport = false;
}
}
</script>
Here is the Response script
<script type="text/javascript">
function processReqChange() {
// only if req shows "loaded"
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
var Result = req.responseText.split("|");
document.getElementById('city').value = Result[0];
document.getElementById('state').value = Result[1];
This is the problem child.
document.getElementById('country').value = Result[2];
} else {
alert("There was a problem retrieving the XML data:\n" + req.statusText);
}
}
}
</script>
option setup
<option name="(abbr.)" value="(full name)">Full Name</option>
i.e.
<option name="CA" value="California">California</option>
I'm just looking for something to replace the .value property. Something like document.getElementById('state').childNode.attribute.name = Result[1] or something.
Here is a link to the full page file http://ge.tt/99dJ1J9?c
The problem is that you do not have the abbrev for the state in option value and the response contains the abbrev.
Also, i would recommend you some javascript framework. It would help you very much with common taks like Ajax, form validation and so on.
Just google javascript framework and find one that would fit your needs best :-)
Use this to set the value in your SELECT object (below code is for city):
var selObject = document.getElementById('city_select_id');
selObject.value = document.getElementById('city').value; //value received in the response
Related
Hey everybody I have a problem.
I am building a website and I want to fetch data from two different xml files with two different functions.
ShowResult is used to get a game score and the name of a specific user.
GiveFeedback also needs the score from the first function to fetch a fitting feedback about this score from a different xml file.
I don´t get an error Message. My only problem is that the second function (giveFeedback) isn´t able to fetch data from the xml because it needs a variable (score) from the first function (showResults). Both functions work on their own but I am unable to “transfer” the score data from showResults to giveFeedback.
How can I transfer the score data to the function GiveFeedback or is there a better way to resolve this problem?
Thanks!
i tried some solutions (global variable, inserting the first function in the second,..) which were already posted but unfortunately i didn´t managed to get it running.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
showResult(xhttp.responseXML);
}
};
xhttp.open("GET", "user.xml", true);
xhttp.send();
function showResult(xml) {
var name = "";
var score = "";
path1 = "/userdb/user/name";
path2 = "/userdb/user/score";
var nodes = xml.evaluate(path1, xml, null, XPathResult.ANY_TYPE, null); var result = nodes.iterateNext();
name = result.childNodes[0].nodeValue;
var nodes = xml.evaluate(path2, xml, null, XPathResult.ANY_TYPE, null); var result = nodes.iterateNext();
//Thats wehere the variable (score) is, which i need for the second function (giveFeedback)
score = result.childNodes[0].nodeValue;
document.getElementById("user").innerHTML = "Congratulations " + name + ", you made " + score;
}
var xhttp2 = new XMLHttpRequest();
xhttp2.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
givefeedback(xhttp2.responseXML);
}
};
xhttp2.open("GET", "feedback.xml", true);
xhttp2.send();
function givefeedback(xml) {
var feedback = "";
// This is where it´s needed
if (score > 1){
path = "/feedback/congratulations[percentage=25]/text";
}
else if (score > 8){
path = "/feedback/congratulations[percentage=50]/text";
}
var nod = xml.evaluate(path, xml, null, XPathResult.ANY_TYPE, null);
var res = nod.iterateNext();
feedback = res.childNodes[0].nodeValue;
document.getElementById("feedback").innerHTML = feedback;
}
</script>
i managed to resolve my problem.
first of all i had to declare a global variable outside the functions.
Then i had to convert the fetched variable (score) to a Number.
I'm working on tableau and I have to build my own web data connector.
I wrote it and it works perfectly on Chrome.
But when I use it into Tableau I get the foolowing error :
ReferenceError: Can't find variable: Promise file: http://localhost:9000/json-connector line: 246
My connector is devided in two parts. The first part call a web service to get a list of destinations and fill two lists with their names. The second part call another web service to get every paths beetween two selected destinations.
The error occured while I want to get the first list. I want to insist that it works on chrome, but not in tableau.
The portion of code where the error occured :
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
console.log("Something went wrong with the destination")
reject(status);
}
};
xhr.send();
});
};
I think that tableau doesn't support Promise. But I don't know how to make a work around. Thank's a lot for your help !
This is how I use this function :
getJSON('http://localhost:9000/stations').then(function(data) {
//alert('Your Json result is: ' + data.result); //you can comment this, i used it to debug
//result.innerText = JSON.stringify(data); //display the result in an HTML element
console.log("starting parsing on : " + data.length);
var listArrival = document.getElementById('Arrival'); //get the list where you want to add options
var listDeparture = document.getElementById('Departure');
if(listArrival == null || listDeparture == null) console.error("Impossible to retrieve the list")
var op;
var addedStations = [];
for(var i = 0; i < data.length ; i++){
var obj = data[i];
var overflowControler = 0;
for(var key in obj){
console.log(key + '=' + obj[key]);
if(key == 'name' && addedStations.indexOf(obj[key]) == -1){
op = new Option(obj[key], obj['nlc'], true);
op2 = new Option(obj[key], obj['nlc'], true);
if(op == null) console.error("Impossible to create the new option")
listArrival.add(op);
listDeparture.add(op2);
addedStations.push(obj[key]);
}
overflowControler ++;
if(overflowControler > maxLengthOfEachRecordFromJson) break; // overflow control
}
if(i > maxStationsRecordNumberFromJson) break; //overflow control
}
}, function(status) { //error detection....
alert('Something went wrong.');
});
As suggested by Tomalak I added a library to my script and Tableau is able to use Promise.
<script src="https://cdnjs.cloudflare.com/ajax/libs/es6-promise/3.2.1/es6-promise.min.js" type="text/javascript"></script>
I didn't make other changes in the code.
I have tried and tested various methods for completing this task for about a day now. Please be forewarned that I am building this simply, and then working my way up!
I have a form that consists of a textarea, and two input fields. The input fields allow a XMLHttpRequest to send information pertaining to a username, and message - sent to a chatroom that I am trying to make.
The problem that I have with my request, is simply that I can send the information, and insert a row into a database, but I can't get any information back! You will see from the code below, that I have put an alert in, to check what the response text is, but it comes back as null (not undefined, but ""). Please check the code below:
function insertMessage() {
var username = document.getElementById('username').value;
var message = document.getElementById('message').value;
var queryString = "username=" + username + "&message=" + message;
// send the username and message information to be inserted into the database
var url = 'classes/chatroom/chatroom.upload.php';
// create xml request
var request = createCORSRequest("POST", url)
// create a function that will receive data sent from the server
request.onreadystatechange = function () {
if (request.readyState == 4 && request.status == 200) {
alert(request.responseText);
}
}
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send(queryString);
}
function createRequest(method, url) {
var thisRequest = new XMLHttpRequest();
if ("withCredentials" in thisRequest) {
// thisRequest has 'withCredentials' property only if it supports CORS
thisRequest.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") { // if IE use XDR
thisRequest = new XDomainRequest();
thisRequest.open(method, url);
} else {
thisRequest = null;
}
return thisRequest;
}
The code that pertains to the insertion of a database row is:
<?php
include 'chatroom.config.inc.php'; // the database file
$message_username = $_POST['username'];
$message_content = $_POST['message'];
if ($message_username == "Username: Once entered, you don't have to enter again" || $message_username == "") {
$message_username = "Guest";
}
if ($message_content == "Message:" || $message_content == "") {}
else {
$users->post_message($message_username, $message_content); // insert database row using PDO query
}
?>
Could anyone provide a clue as to where I'm going wrong?
The code looks good to me, your PHP code is inserting the data in DB but it isn't returning back any text or value.
For values to be retrieved on the client side i.e. on successful completion of your ajax request, you will have to send the data to client side.
Try using php's echo function and return the text / value.
I have a web application that receives json from a server. I was using this code:
var http_request = new XMLHttpRequest();
var url = "url where I have the json"
http_request.onreadystatechange = handle_json;
http_request.open("GET", url, true);
http_request.send(null);
var obj;
function handle_json() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var json_data = http_request.responseText;
obj = eval("(" + json_data + ")");
processData(obj);
} else {
alert("A problem ocurred");
}
http_request = null;
}
}
But now I want to receive json from two url's and show the information. How can I do this using JavaScript? I know eval is not the appropiate thing to do but this is just a prototype.
Thank you so much! :)
As others have mentioned, you simply need to make 2 requests. In order to re-use the code you have already written, you could define a function to get json that takes a url argument. Something like this:
function getJson(url, callback){
function handle_json() {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
var json_data = http_request.responseText;
var parser = (JSON && typeof JSON.parse == 'function') ? JSON.parse : eval;
var obj = parser("(" + json_data + ")");
callback(obj);
} else {
alert("A problem ocurred");
}
http_request = null;
}
}
var http_request = new XMLHttpRequest();
http_request.onreadystatechange = handle_json;
http_request.open("GET", url, true);
http_request.send(null);
}
I replaced the call to eval with some logic that will call JSON.parse if it is present, otherwise it will use eval. Using this function would allow you to make multiple requests by calling it multiple times, like so:
getJson("some url", processData);
getJson("some other url", processData");
If you wanted to process data from different urls in different ways, just define another function similar to processData and pass it along instead, like getJson("some crazy url", processCrazyData);
Using a framework like jQuery would reduce the amount of code that you have to write, but this solution should get it done using basic javascript.
The easiest way would be to put it into a function.
function getJson(url) {
//Remove the var url="string" line
//Rest of code
}
function handleJson() {
//Other code
}
Alternatively, you could use jQuery, in which case your code would be:
$.getJSON('url goes in here',function(data){
processData(data);
});
And just use that whenever you want to grab a page.
In JSP page I have written:
var sel = document.getElementById("Wimax");
var ip = sel.options[sel.selectedIndex].value;
var param;
var url = 'ConfigurationServlet?ActionID=Configuration_Physical_Get';
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
httpRequest.open("POST", url, true);
httpRequest.onreadystatechange = handler(){
if (httpRequest.readyState == 4) {
if (httpRequest.status == 200) {
param = 'ip='+ip;
param += 'mmv='+mmv;
param += "tab="+tab;
}};
httpRequest.send(param);
I want this param variable in my ConfigurationServlet. Can anyone tell me how to get this json object in servlet?
Update: I changed my statements and now it is showing status code as 200.
var index = document.getElementById("Wimax").selectedIndex;
var ip = document.getElementById("Wimax").options[index].text;
httpReq = GetXmlHttpObject();
alert(httpReq);
var param = "ip=" + ip;
param += "&mmv=" + mmv;
param += "&tab=" + tab;
alert("param "+param);
var url="http://localhost:8080/WiMaxNM/ConfigurationServlet?ActionID=Configuration_Physical_Get";
url = url+"?"+param;
httpReq.open("GET",url,true);
alert("httpReq "+httpReq);
httpReq.onreadystatechange = handler;
httpReq.send(null);
But new problem has occured. Control is not at all going to the servlet action ID as specified in url. Please tell me what is wrong here.
The code in the handler will only be invoked AFTER the request is been sent. You need to populate param before this. You would also need to concatentate separate parameters by &.
Thus, e.g.
// ...
httpRequest.onreadystatechange = handler() {
// Write code here which should be executed when the request state has changed.
if (httpRequest.readyState == 4) {
// Write code here which should be executed when the request is completed.
if (httpRequest.status == 200) {
// Write code here which should be executed when the request is succesful.
}
}
};
param = 'ip=' + ip;
param += '&mmv=' + mmv;
param += "&tab=" + tab;
httpRequest.send(param);
Then you can access them in the servlet the usual HttpServletRequest#getParameter() way.
That said, the Ajax code you posted there will only work in Microsoft Internet Explorer, not in all the four other major webbrowsers the world is aware of. In other words, your Javascript code won't work for about half of the people in the world.
I suggest to have a look at jQuery to lessen all the verbose work and bridge the crossbrowser compatibility pains. All your code could be easily replaced by
var params = {
ip: $("Wimax").val();
mmv: mmv,
tab: tab
};
$.post('ConfigurationServlet?ActionID=Configuration_Physical_Get', params);
And still work in all webbrowsers!
Update: as per your update, the final URL is plain wrong. The ? denotes a start of the query string. You already have one in your URL. You should use & to chain parameters in the query string. I.e.
url = url + "&" + param;