parse json data with javascript - 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.

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();
}

Unable to read SQL blob via FileReader in IE 11

I am reading a blob from my SQL database via AJAX and the code below which works fine in FireFox, Edge, and Chrome but I receive an error "invalid state error" in the debugger for the line xmlhttp.responseType = "blob"; in IE11. I have tried all sorts of combinations for xmlhttp.responseType but cannot get it to work in IE11. For example, if I just comment out xmlhttp.responseType = "blob"; I obtain "type mismatch error" for the line xmlhttp.responseType = "blob";. And was wondering if someone could help me with this. Here is the code in my html file to make the ajax request:
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.responseType = "blob";
xmlhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
theResponse=this.response;
theBlobSize=theResponse.size;
reader = new FileReader();
reader.addEventListener("loadend", function()
{
// get data from blob here
});
reader.readAsArrayBuffer(theResponse);
}
};
xmlhttp.open("POST","getImagAlgebraicBlob.php",true);
xmlhttp.send();
}
And here is the php file "getImagAlgebraicBlob.php" being called to read the blob using PDO and is very simple and again, works perfectly in the other browsers:
<?php
include 'algebraicFunctionBlobClass.php';
$blobObj = new algebraicFunctionBlob();
$a = $blobObj->selectImagBlob(132);
echo $a['imagWebGLData'];
?>
Thanks,
IE6/5 are long gone so you don't need to do special treatment for that
you don't have to use the FileReader if you set the responseType to arraybuffer directly...
var xhr = new XMLHttpRequest
xhr.onload = function() {
var buffer = this.response
var size = buffer.byteLength
// construct the arraybuffer as a blob if you ever need it
// var blob = new Blob([buffer])
}
xhr.open('POST', 'getImagAlgebraicBlob.php')
xhr.responseType = 'arraybuffer'
xhr.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") }

Ajax request to load .php file not working

Trying to load contents from postcode.php file into a #postcodeList div, but it is not working (nothing happens). I checked postcode.php file it echoes al correct information.
var loadicecream = document.getElementById("iceCreams");
loadicecream.addEventListener("click", iceAjax, false);
function iceAjax() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","ice-cream-list.php",true);
xmlhttp.send();
document.getElementById("ice-cream-list").innerHTML = xmlhttp.responseText;
}
You want the query to execute asynchronously (the third parameter to open function) and then you synchronously try to read the value. This happens before the query has been sent, so it will always be empty.
Either run the load synchronously, or set the xmlhttp.onreadystatechange to point into a function where you handle the loaded state. The best way is to do it asynchronously since you don't want to block the user from using the page while loading data.
Quick example, only handles the success case:
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("postcodeList").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST","postcode.php",true);
xmlhttp.send();
Read up on the documentation for the onreadystatechange, at least you want to handle the case where there is a timeout or some error, otherwise the user won't know something went wrong.

Returning json result in function

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);
});
});

Categories