Returning json result in function - javascript

I am getting json response from ajax request
I want to return json result to getTwitterVal() function call in var obj. And then getting name and id in $('#loginTwitter').click(function data() {}. How to this this?
Following code returns alert 'undefined'
function getTwitterVal()
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status==200)
{
var result = xmlhttp.responseText;
//result looks like this : {"name": jack,"id":1}
//obj = JSON.parse(result);
return result;
}
}
xmlhttp.open("POST","redirect.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
// api_call();
}
$('#loginTwitter').click(function data() {
var obj = getTwitterVal();
alert(obj.name); // I want retrieve name and id both value here
}
UPDATED code
function getTwitterVal(clb)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
var result = xmlhttp.responseText;
var obj = JSON.parse(result);
clb(obj);
}
xmlhttp.open("POST","redirect.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
// api_call();
}
$('#loginTwitter').click(function data() {
getTwitterVal(function(obj) {
alert(obj.name);
});
});
Gives error
SyntaxError: JSON.parse: unexpected character var obj = JSON.parse(result);

It doesn't work like that. AJAX call is asynchronous. Although it is possible to make it synchronous you should never do it (since it will block all other scripts on the page). Instead pass a callback to getTwitterVal:
function getTwitterVal(clb) {
// some code
if (xmlhttp.readyState == 4 && xmlhttp.status==200)
{
var result = xmlhttp.responseText;
var obj = JSON.parse(result);
clb(obj);
}
// other code
}
and then
$('#loginTwitter').click(function data() {
getTwitterVal(function(obj) {
alert(obj.name);
});
}

Use asynchronous ajax, as mentioned by #freakish. Also, if you already use jquery, then let it makes its ajax work also. Something like that:
$('#loginTwitter').click(function() {
$.post(
'redirect.php',
function(data) {
var obj = JSON.parse(data);
alert(obj.name);
});
});

Related

get finger print using morpho device in https

i want to capture finger print using morpho device. i am able to do that but the thing is, i am getting error because the service i am using is http and my website is https. so i have to allow every time my website to read http url.
what actually they are doing is, they are giving a service which allow me to access http://localhost:8080/CallMorphoAPI. but this is for http not https. i installed morpho driver which started this service. so what i want to know if there any way so i can modify this service. I want Finger print scan using morpho 1300 e2 using java api.
function CallFingerAPI()
{
var url = "http://localhost:8080/CallMorphoAPI";
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
fpobject = JSON.parse(xmlhttp.responseText);
console.log(fpobject.Base64BMPIMage);
// Call Servlet
function uploadThumb(image){
var formdata = image;
var fr = new FormData();
fr.append("data", formdata);
var id = "<%=patientId%>";
var url = "ThumbUpload?patientId="+id;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState === 4 && xmlhttp.status === 200){
var response = xmlhttp.responseText;
response = response.replace(/\r?\n|\r/g, "");
response = response.trim();
if(response === "Uploaded"){
alert("Uploaded");
}
else{
alert("Error");
}
}
};
try{
xmlhttp.open("POST",url,true);
xmlhttp.send(fr);
}catch(e){alert("unable to connect to server");
}
}
uploadThumb(fpobject.Base64BMPIMage);
template = fpobject.Base64ISOTemplate;
}
}
var timeout = 5;
xmlhttp.open("POST",url+"?"+timeout,true);
xmlhttp.send();
}

Giving an attribute to an xmlhttprequest object

I have the following code :
<head>
<script>
function startChanging() {
var elems = document.getElementsByTagName("img");
for(var i=0; i < elems.length; i++)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp["elem"] = elems[i];
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
this["elem"].src = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://myurl.com/somescript.php", true);
xmlhttp.send();
}
};
</script>
</head>
<body onload="startChanging()">
<img src="https://www.google.com/images/srpr/logo11w.png">
<br/>
<img src="https://www.google.com/images/srpr/logo11w.png">
<br/>
<img src="https://www.google.com/images/srpr/logo11w.png">
</body>
Even though I create a new instance of XMLHttpRequest for each iteration and add the current element to an attribute, when the request returns a response only the last img element is changed.
I am looking for a simple solution to change the src of the img element without iterating through all the elements again when the response comes. I would like a pure Javascript solution (read: no JQuery).
I am certainly doing something wrong here I just don't understand what. Any help would be appreciated.
In your for loop, you are overwriting the xmlhttp variable so when you get into the onreadystatechage function and you check the value of xmlhttp.readyState, it will not be checking the right object.
I'd suggest this fix which changes two things:
It puts each ajax call into it's own IIFE which keeps the xmlhttp variable separate for each ajax call.
It passes elems[i] into the closure so you don't have to do the property saving hack.
Code:
function startChanging() {
var elems = document.getElementsByTagName("img");
for(var i=0; i < elems.length; i++)
{
(function(obj) {
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
obj.src = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://myurl.com/somescript.php", true);
xmlhttp.send();
})(elems[i]);
}
};
One possible approach:
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
this.elem.src = this.responseText;
}
}
As you see, I've replaced all the references to xmlhttp within that handler function to this.
The problem is even though you've created a new AJAX-serving object at each step of the loop, each newly-created 'readystatechange' handler function referred to the same object known under xmlhttp variable.
In general, this is quite a common problem when someone works with a variable declared within a loop yet referred by functions created in the same loop. Stumble upon this once or twice, and you'll begin to see the pattern. )
xmlhttp.send();
Put data into the send method:
xmlhttp.send(data);
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
void send();
void send(ArrayBuffer data);
void send(ArrayBufferView data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
Where data is a JavaScript variable, you can put anything into. If you want multipart message, you'd use var data = new FormData(); and put data into it using data.append('image', file); for file upload via ajax for example.
If no multipart, simply put anything in like:
data = { images: document.getElementsByTagName("img") }

Turning a delimited string retrieved via AJAX back into a multidimensional array

I imagine at some point my familiarity with PHP is making me write something incorrectly, but I've been reading up and can't seem to find a way to achieve what the below is intended to achieve. In the end, I should have a multidimensional array like such:
cardArray[#]
'uniqueID' => "#";
'cardName' => "blahblah";
'series' => "blahblah";
(Where the #s are actual numbers, of course.) The string that is returned via AJAX is formatted such that each set of 3 is delimited by a colon and within each set each item is delimited by a pipe. (The final line I just threw in as a test to see if ANYTHING was getting stored.)
Here's the code:
function buildCardList() {
var returnedString;
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
returnedString = xmlhttp.responseText;
}
}
xmlhttp.open("POST","test02.php",true);
xmlhttp.send();
var cardArray = new Array();
cardArray = returnedString.split(":");
for (var i = 0; i < cardArray.length; i++) {
var tempVar = cardArray[i];
var tempArr = tempVar.split("|");
cardArray[i] = {
"uniqueID" : tempArr[0],
"cardName" : tempArr[1],
"series" : tempArr[2]
};
}
document.getElementById("test").innerHTML = cardArray[0]['uniqueID'] + "<br>" + cardArray[0]['cardName'] + "<br>" + cardArray[0]['series'] + "<br><br>";
}

parse json data with javascript

I have a proxy script that outputs json data via php, and I want to be able to manipulate this data using javascript. I have the following code, but it only gets the entire json string outputted by the php script. How do I take the data and be able to access the individual objects with in this json data?
var xmlhttp;
function loadXMLDoc(url, cfunc) {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = cfunc;
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
loadXMLDoc("http://xxxxx.appspot.com/userbase_us.php?callback=userdata", function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var json = xmlhttp.responseText;
alert(json);
}
});
You can use the native JSON.parse method:
var json = JSON.parse(xmlhttp.responseText);
Note that since this is not supported by older browsers, you will most likely want to polyfill it.

what does IE like about the xmlhttprequest?

i have the following code working in all browsers now but IE8.. i read that if i used the xhttp=new ActiveXObject("Microsoft.XMLHTTP"); line it should work for IE but i'm not sure..anyone have experience in getting this to work with ie8
function loadXMLDoc(dname)
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
var xmlDoc = loadXMLDoc("nhl_standings_xml.xml");
var x = xmlDoc.getElementsByTagName("nhlall");
Hmm, the code looks okay. Have you tried an Asynchronous request? When you have xhttp.open("GET", dname, false);, it's synchronous. Change that false to a true, and you're asynchronous. Also, you variable xhttp isn't properly declared (correct me if I'm wrong. Being a Python coder, I can't tell half of the time).
Try this code:
function loadXML(url)
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
return false;
}
}
}
xmlHttp.onreadystatechange = function()
{
if(xmlHttp.readyState == 4)
{
return xmlHttp.responseText;
}
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
var xmlDoc = loadXML("nhl_standings_xml.xml");
var x = xmlDoc.getElementsByTagName("nhlall");
i suggest you this MINIMAL ajax engine.
http://pastebin.com/uXJe9hVC
an example of usuage
ajax POST request
Ajax.call('GET','http://localhost/index.php',function(data) {
{
//doing stuff with the data response
},'ASD');
call arguments: URL,callback,POST
this is so easy.
Try this as a request starter:
if (window.XMLHttpRequest) return new window.XMLHttpRequest();
else if (window.ActiveXObject) {
// the many versions of IE's XML fetchers
var AXOs = [
'MSXML2.XMLHTTP.6.0',
'MSXML2.XMLHTTP.5.0',
'MSXML2.XMLHTTP.4.0',
'MSXML2.XMLHTTP.3.0',
'MSXML2.XMLHTTP',
'Microsoft.XMLHTTP',
'MSXML.XMLHTTP'
];
for (var i = 0; i < AXOs.length; i++) {
try { return new ActiveXObject(AXOs[i]); }
catch() { continue; }
}
return null;
}
The order above should be the correct best-to-worse order, BTW.

Categories