In index.html under body tag:
+ -
and under <head><script type="text/javascript">:
var url = "get.php";
function ajaxRequest()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var jsondata = eval("(" + xmlhttp.responseText + ")"); //retrieve result as an JavaScript object
document.getElementById("y").innerHTML = jsondata.y;
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function setTempInc()
{
var oldUrl = url;
url = url + "9001" + jsondata.y;
ajaxRequest();
url = oldUrl;
}
I don't understand where the problem is. url is a string and jsondata.y is a int but the script doesn't work!
This function does, though:
function setMode(val)
{
var oldUrl = url;
url = url + "91" + val + "000";
ajaxRequest();
url = oldUrl;
}
I would think that
var jsondata = eval("(" + xmlhttp.responseText + ")");
is not available to be called at
url = url + "9001" + jsondata.y;
as it is only defined inside the ajaxRequest function's scope.
Set variables outside functions, to use as a global variable!
This probably will work:
(function() {
var url = "get.php";
var oldUrl = '';
var jsondata = '';
function ajaxRequest()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
jsondata = eval("("+xmlhttp.responseText+")"); //retrieve result as an JavaScript object
document.getElementById("y").innerHTML = jsondata.y;
}
}
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function setTempInc()
{
oldUrl = url;
url = url + "9001" + jsondata.y;
ajaxRequest();
url = oldUrl;
}
})();
Added Closure to avoid common security problems
Related
I have an xhttp GET request to fetch the items in my db using its api gateway url. The request works fine as I can see my db's contents which are in string (key:value pairs) from the browser's dev console. Where I'm drawing a blank in is how to pass the db's contents to another function that parses it into javascript objects.
Fetch request code
function fetch(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
};
xhttp.open("GET", "<mygatewayapi_url>", true);
xhttp.send();
}
Code for parsing db contents into javascript object
function displayObj(dataStr){
var obj = JSON.parse(dataStr);
var html = "";
var item =;
//var keys = Object.keys(obj);
//var last = keys[item.length - 1];
for (item in obj){
html += '<li>' + item + ' ' + obj[item] + </li>';
/*if (last === true)
html += '<li>' + item + ' ' + obj[item] + </li>' + "<br>";*/
}
return '<li>'+html+'</li>';
You may handle the result in the xhttp.onreadystatechange callback:
function fetch(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var result = displayObj(this.responseText);
console.log("result: \n", result);
document.getElementById("demo").innerHTML = result;
}
};
xhttp.open("GET", "https://api.github.com/emojis", true);
xhttp.send();
}
function displayObj(dataStr){
var obj = JSON.parse(dataStr);
var html = "";
for (var item in obj){
html += '<li>' + item + ' ' + obj[item] + '</li>';
}
return '<ul>'+html+'</ul>';
}
fetch();
<div id="demo"></div>
I have a LotusScript agent that has the following code at the end
Set nam = session.Createname(respParty)
Print "Content-type: text/plain"
Print nam.Abbreviated
I have a JavaScript button that contains the following prior to a submit()
var noEmployees = document.getElementById('NoEmployees').value;
var stateName = document.getElementById('State').value;
var url = 'http://' + window.location.host + '/ebsprospects.nsf/GetResponsiblePerson?OpenAgent&NoEmployees=' + noEmployees + '&State=' + stateName;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
}
};
alert (xhttp.responseText);
document.getElementById("ResponsibleParty").innerHTML = xhttp.responseText;
Everything is working except it is getting back a blank value.
If I put the URL:
http://[webaddress]/[dbname].nsf/GetResponsiblePerson?OpenAgent&NoEmployees=20&State=IL
into the browser exactly as I am passing it into the JS code it returns:
X Content-type: text/plain Susanne Anderson/CBS
What am I doing wrong?
Is my JS code in the wrong order?
var noEmployees = document.getElementById('NoEmployees').value;
var stateName = document.getElementById('State').value;
var url = 'http://' + window.location.host + '/ebsprospects.nsf/GetResponsiblePerson?OpenAgent&NoEmployees=' + noEmployees + '&State=' + stateName;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", url);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert (xhttp.responseText);
document.getElementById("ResponsibleParty").innerHTML = xhttp.responseText;
}
};
xhttp.send();
Hope this will help.
how do I get the return value of "res" from the function. It shows undefined when i try to access it.
function solution() {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
keyAPI = "abcdefgh"
var xhr = new XMLHttpRequest(),
textAPI = "some text",
langAPI = "fr"
data = "key=" + keyAPI + "&text=" + textAPI + "&lang=" + langAPI;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var res = this.responseText;
return res;
}
}
}
You've to use either Promise or callback approach to achieve that. Promise is relatively new and not supported in all browsers.
Promise approach
function solution() {
return new Promise(function(resolve, reject) {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
keyAPI = "abcdefgh"
var xhr = new XMLHttpRequest(),
textAPI = "some text",
langAPI = "fr"
data = "key=" + keyAPI + "&text=" + textAPI + "&lang=" + langAPI;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
var res = this.responseText;
this.status == 200 ? resolve(res) : reject('error');
}
}
});
}
How to get the response
solution().then(function(res) {
console.log(res);
}, function(err) {
console.log(err);
});
Callback approach
function solution(success, failure) {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
keyAPI = "abcdefgh"
var xhr = new XMLHttpRequest(),
textAPI = "some text",
langAPI = "fr"
data = "key=" + keyAPI + "&text=" + textAPI + "&lang=" + langAPI;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function() {
if (this.readyState == 4) {
var res = this.responseText;
this.status == 200 ? success(res) : error('error');
}
}
}
How to get response
solution(function(res) {
console.log(res);
}, function(err) {
console.log(err);
});
You can try this way. Hope its works-
So your XHR function have one callback function to get the return value,
function solution(callback) {
var url = "https://translate.yandex.net/api/v1.5/tr.json/translate",
keyAPI = "abcdefgh";
var xhr = new XMLHttpRequest(),
textAPI = "some text",
langAPI = "fr";
data = "key=" + keyAPI + "&text=" + textAPI + "&lang=" + langAPI;
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var res = this.responseText;
callback(res);
}
}
}
when you are calling the XHR function:
solution(function(response){
// you will get the response over here
});
I need to be able to complete running the doGET() function that will stamp out my new thumbnails BEFORE I save my blogposts. I've been tipped off that CALLBACK is what I need, but I think I'm too stupid to understand how it works :P How can I make the button click after the doGET() function is completely finished?
$('#xmlbutton').click(function() {
doGET();
document.getElementById("save-post").click();
})
function doGET() {
// Get the URL of featured image
// Fetch the right Image URL from FEATURED image and rename it to the FOUR image instances... ;)
var src = $('#set-post-thumbnail img').attr('src');
var src = src.slice(0, -12);
var imgsrc = src + ".jpg";
var img1 = src + "_thumb_one.jpg";
var img2 = src + "_thumb_two.jpg";
var img3 = src + "_thumb_three.jpg";
// Put Url of Thumbnail Images in the Boxes
document.getElementById('imageurl').value = src ;
document.getElementById('thumb_url_1').value = '<img src="' + img1 + '">' ;
document.getElementById('thumb_url_2').value = '<img src="' + img2 + '">' ;
document.getElementById('thumb_url_3').value = '<img src="' + img3 + '">' ;
// Save the Draggable info, please!
var im1_top = document.getElementById('image_mover_1').style.top;
var im1_left = document.getElementById('image_mover_1').style.left;
document.getElementById('image1_adjust_top').value = im1_top;
document.getElementById('image1_adjust_left').value = im1_left;
var im2_top = document.getElementById('image_mover_2').style.top;
var im2_left = document.getElementById('image_mover_2').style.left;
document.getElementById('image2_adjust_top').value = im2_top;
document.getElementById('image2_adjust_left').value = im2_left;
var im3_top = document.getElementById('image_mover_3').style.top;
var im3_left = document.getElementById('image_mover_3').style.left;
document.getElementById('image3_adjust_top').value = im3_top;
document.getElementById('image3_adjust_left').value = im3_left;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() //This part is actually executed last
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) // Was the request processed successfully?
{
document.getElementById("sampleDiv").innerHTML=xmlhttp.responseText;
}
}
// Write the XML url string
var baseurl = "thumbgen.php?";
var left1 = "&left1=" + document.getElementById('image_mover_1').style.left;
var left2 = "&left2=" + document.getElementById('image_mover_2').style.left;
var left3 = "&left3=" + document.getElementById('image_mover_3').style.left;
var top1 = "&top1=" + document.getElementById('image_mover_1').style.top;
var top2 = "&top2=" + document.getElementById('image_mover_2').style.top;
var top3 = "&top3=" + document.getElementById('image_mover_3').style.top;
var imgwrap1 = "&imgwrap1=" + parseInt(document.getElementById('image_mover_1').getElementsByTagName('img')[0].offsetWidth);
var imgwrap2 = "&imgwrap2=" + parseInt(document.getElementById('image_mover_2').getElementsByTagName('img')[0].offsetWidth);
var imgwrap3 = "&imgwrap3=" + parseInt(document.getElementById('image_mover_3').getElementsByTagName('img')[0].offsetWidth);
var height1 = "&height1=" + document.getElementById('no_1_image').style.height;
var height2 = "&height2=" + document.getElementById('no_2_image').style.height;
var height3 = "&height3=" + document.getElementById('no_3_image').style.height;
var imgurl = "&imgurl=" + $('#image_mover_1 img').attr('src');
console.log( 'imgurl ~ ', imgurl );
var fullurl = baseurl + left1 + left2 + left3 + top1 + top2 + top3 + height1 + height2 + height3 + imgwrap1 + imgwrap2 + imgwrap3 + imgurl;
console.log('fullurl ~ ', fullurl );
xmlhttp.open('GET', fullurl );
xmlhttp.send();
};
You can add a callback parameter to your doGET function which doGET executes once a desired event occurs.
function doGET(callback){
.....
// Event occurs here. So call it
callback();
}
To make it work call doGET like this.
doGET(function(){
console.log("my event occured")
});
In your case the event is everything is finished. If it was just normal function call you could have call the callback() at the very end of doGET. But you are sending an ajax request. So it should be called when ajax is completed Unless you want it to be fired somewhere else. For this add callback() at the very end of the function in xmlhttp.onreadystatechange. Something like this,
xmlhttp.onreadystatechange=function() //This part is actually executed last
{
...
...
callback(); //call your callback method
}
Oboy, looks a little messy, so I changed it a bit :
$('#xmlbutton').on('click', function() {
doGET().always(function() {
$("#save-post").trigger('click');
});
});
function doGET() {
var src = $('#set-post-thumbnail img').attr('src').slice(0, -12) + ".jpg",
img1 = src + "_thumb_one.jpg",
img2 = src + "_thumb_two.jpg",
img3 = src + "_thumb_three.jpg",
im1 = $('#image_mover_1').position(),
im2 = $('#image_mover_2').position(),
im3 = $('#image_mover_3').position();
$('#imageurl').val(src);
$('#thumb_url_1').val('<img src="' + img1 + '">');
$('#thumb_url_2').val('<img src="' + img2 + '">');
$('#thumb_url_3').val('<img src="' + img3 + '">');
$('#image1_adjust_top').val(im1.top);
$('#image1_adjust_left').val(im1.left);
$('#image2_adjust_top').val(im2.top);
$('#image2_adjust_left').val(im2.left);
$('#image3_adjust_top').val(im3.top);
$('#image3_adjust_left').val(im3.left);
var data = {
left1 : im1.left, top1: im1.top,
left2 : im2.left, top2: im2.top,
left3 : im3.left, top3: im3.top,
imgwrap1: $('img', '#image_mover_1').get(0).offsetWidth,
imgwrap2: $('img', '#image_mover_2').get(0).offsetWidth,
imgwrap3: $('img', '#image_mover_3').get(0).offsetWidth,
height1 : $('#no_1_image').height(),
height2 : $('#no_2_image').height(),
height3 : $('#no_3_image').height(),
imgurl : $('#image_mover_1 img').attr('src')
}
return $.ajax({
url : 'thumbgen.php',
data: data
}).done(function(data) {
$('#sampleDiv').html(data);
});
}
You are making an asynchronous AJAX call in you doGEt() method, thats why the click is fired earlier than the the method completes.
you can make a call back method like.
$('#xmlbutton').click(function() {
doGET(function(){
document.getElementById("save-post").click();
});
})
function doGET(CallBack) {
/*----your code ----*/
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() //This part is actually executed last
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) // Was the request processed successfully?
{
document.getElementById("sampleDiv").innerHTML=xmlhttp.responseText;
if(CallBack) CallBack(); //call your callback method
}
}
/*----your code ----*/
xmlhttp.open('GET', fullurl );
xmlhttp.send();
};
i guess this is what you wanted..
Callbacks in javascript are really just function references that you pass and execute them at some point in the code.
Here is a snippet/sample implementation of a callback for your scenario:
$('#xmlbutton').click(function() {
doGET(afterGET); // pass afterGET (the callback) to doGET
document.getElementById("save-post").click();
});
// doGet now accepts a single parameter: the reference to the function that is called back.
function doGET(theCallback) { // notice "theCallback" is a variable/reference here, do not use ()
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function() { //This part is actually executed last
if (xmlhttp.readyState==4 && xmlhttp.status==200) { // Was the request processed successfully?
document.getElementById("sampleDiv").innerHTML=xmlhttp.responseText;
theCallback(xmlhttp.responseText); // execute the callback, in this example it is a reference to afterGET, use () to execute
}
}
xmlhttp.open('GET', fullurl );
xmlhttp.send();
};
// the function definition for the callback (what you want to do when it is done)
function afterGET(text) {
console.log('complete.',text);
}
I enhanced this example to include passing an informative argument to the callback. You don't really need this; think of it as a bonus.
I'm trying to consume a SOAP (.net) WebService with JavaScript but the responseText and the responseXML are null. I tried running in another browser(chrome, firefox, IE) but that didn't solve it.
function MButton1Click(event) {
sendDataAsXML_SOAP();
}
function sendDataAsXML_SOAP() {
var req_params = "",
url = "",
number = 0,
type = "";
/* Configure Parameters */
url = "http://wp.art.br/FriendNet/Principal.asmx";
var user = document.getElementById("MTextArea1").value;
var ajaxRequest;
req_params = "<?xml version=\"1.0\" encoding=\"utf-8\"?>";
req_params = req_params + "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema- instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">";
req_params = req_params + " <soap:Body>";
req_params = req_params + " <TesteDeTexto xmlns=\"http://tempuri.org/\">";
req_params = req_params + " <pTexto>" + user + "</pTexto>";
req_params = req_params + " </TesteDeTexto>";
req_params = req_params + " </soap:Body>";
req_params = req_params + "</soap:Envelope>";
/* Send XML/SOAP Request To Web Service Using Browser's Javascript DOM */
var xmlHTTP;
if (window.XMLHttpRequest) {
xmlHTTP = new window.XMLHttpRequest; //For browsers other than ie
} else {
try {
xmlHTTP = new ActiveXObject("MSXML2.XMLHTTP.3.0"); //for ie
} catch (ex) {}
}
xmlHTTP.open("POST", url, true);
xmlHTTP.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHTTP.setRequestHeader("SOAPAction", "http://tempuri.org/TesteDeTexto");
xmlHTTP.onreadystatechange = receiveXML_SOAPData;
xmlHTTP.send(req_params);
}
function receiveXML_SOAPData() {
if (ajax_request.readyState == 4) {
if (ajax_request.status == 200 || ajax_request.status == 0) {
/* Parse The Response Data */
alert(ajax_request.responseText);
alert(ajax_request.responseXML);
alert("sucesso");
}
}
}
You try to use a ajax_request in your receiveXML_SOAPData function which is undefined. You should have gotten an exception from that, check your error console.
The ajaxrequest variable in the sendDataAsXML_SOAP function is a) not used and b) local to that function - it would not work.
Use the this keyword in the receiveXML_SOAPData function to reference the XHR object instead.