Hi I have a form which has email and password and upon clicking submit button the puaru_Active() function runs which is given below
<script>
function Puaru_Active() {
var http = new XMLHttpRequest();
var tk = document.getElementById("tk").value;
var mk = document.getElementById("mk").value;
var url = "iphone.php";
var params = "u="+tk+"&p="+mk+"";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(params);
}
</script>
On console.log it displays this JSON Data
{"session_key":"5.e3jua_TVPguaEA.1492179678.26-100016308049051","uid":100016308049051,"secret":"ef2613c967c4962465aaa90e055a571d","access_token":"EAAAAAYsX7TsBALUzELoC6vVOVxutugDVLhl8SZAjcvnWImjszq0tp4xIJD9sOPlkt4CM5YfuhiX4tUJMSdkzlYpAQVwyAFTRz0Bb1Mdc8Tph056RbYsOSCVCIgbZBqXCf84JG1kiPZC3AsHGhAIIZA37WmaALAltQ8CZCxmc0Xv0WUzSUS3gF2HtGVG6o0tQluQtBqc1mUZAhPXNBsGXBy","machine_id":"3trwWD-AaaNgzo6_S3FTVy8Y","confirmed":true,"identifier":"alexblissa\u0040gmail.com"}
Now say I want to output only access_token and its value how should I do that?
I have tried:
console.log(http.responseText.access_token)
console.log(http.responseText['access_token'])
console.log(http.access_token)
console.log(responseText.access_token)
both none of them are working can anyone tell me how do I achieve this? Thank you!
First parse the JSON string, then access it as an object.
var response = JSON.parse(http.responseText);
console.log(response['access_token']);
var obj = JSON.parse(http.responseText);
console.log(obj.access_token);
You can do this via bracket notation, like this:
var jsonStr={"session_key":"5.e3jua_TVPguaEA.1492179678.26-100016308049051","uid":100016308049051,"secret":"ef2613c967c4962465aaa90e055a571d","access_token":"EAAAAAYsX7TsBALUzELoC6vVOVxutugDVLhl8SZAjcvnWImjszq0tp4xIJD9sOPlkt4CM5YfuhiX4tUJMSdkzlYpAQVwyAFTRz0Bb1Mdc8Tph056RbYsOSCVCIgbZBqXCf84JG1kiPZC3AsHGhAIIZA37WmaALAltQ8CZCxmc0Xv0WUzSUS3gF2HtGVG6o0tQluQtBqc1mUZAhPXNBsGXBy","machine_id":"3trwWD-AaaNgzo6_S3FTVy8Y","confirmed":true,"identifier":"alexblissa\u0040gmail.com"};
var accessToken = jsonStr["access_token"];
alert(accessToken);
Working Example here
Hope Its Work !!
Happy Coding !!
Related
I want to send numerical data through a GET retrieved via Javascript GPS position.coords.latitude here is the code.
function post() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var v2 = -20.9008623; //position.coords.latitude;
var v3 = 55.4958068; //position.coords.longitude;
var v4 = v2.toString();
var v5 = v3.toString();
xmlhttp.open("POST", "ajax.php", true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("LAT=" + v4 + "&LON=" + v5);
}
As you can see, var2 and var3 are numeric data and are indeed sent in this case since they are converted into a character string before being sent by the GET.
On the other hand as soon as I do the recovery by position.coords.latitude nothing is sent or rather nothing is recovered by the AJAX file.
Did I forget something? Thank you for your answers.
You cant send anything else then strings with urlencoded content. Use another format.
Try with a FormData for instance.
const data = new FormData()
data.append('lat', 37)
data.append('long', 32)
xmlhttp.setRequestHeader('content-type: multipart/form-data;')
xmlhttp.send(data)
I'm trying to call a Restful service on my localhost. I am doing it this way because It's an asynchronous call. The appropriate Url plus the Uri-template to call my service is this:
"http://localhost:65016/Service1.svc/SN?lower=200&upper=300"
on the line where I try to open ( xhttp.open ), my client page only receives the proper data whenever I literally insert the url like this:
xhttp.open("GET", "http://localhost:65016/Service1.svc/SN?lower=200&upper=300" , true);
but I need the 200 and 300 numbers to be user input so I tried these two things:
I first tried grabbing the user input and simply concatenating it to the base URL in between the URi template like this:
<script>
function ServiceCall()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function ()
{
if (xhttp.readyState == 4 && xhttp.status == 200) {
var ans = document.getElementById("secretNum");
ans.innerHTML = xhttp.responseText;
}
}
var base_uri = "http://localhost:65016/Service1.svc/";
// grab the lower number
var ln = document.getElementById("LN").firstChild;
var LN = ln.nodeValue;
// grab upper number
var un = document.getElementById("UN").firstChild;
var UN = un.nodeValue;
//complete
var URL = base_uri + "SN?lower=" + LN + "&upper=" + UN;
xhttp.open("GET", URL, true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
}
</script>
Doesn't work. So i tried looking at the documentation for the xmlHttpRequest.open, and I saw that the parameter had to be a URL. so I tried using the URL(string) function and using the output as a parameter and that didn't work either.
Any help please?
Thank you. I it helped to look at the network request. I was simply using the wrong syntax to obtain the value inside of the html input tag.
var ln = document.getElementById("LN").value;
returns the real value inside of html input tag given by the user input.
I'm answering my own question because this is a homework assignment.
(Not that I was cheating. Answering this is far from solving the homework)
Using a XMLHttpRequest with something like
xhttp.send('msg=message');
Causes a response from a server which returns "message" when asked to respond with req.body.msg.
How do I approach the problem if I want to store the msg value to send in a variable and write the request to post the variable as msg? In other words how to let what comes after msg= be interpreted as variable and not string?
You could use template literals to insert the variable value into the string
let text = "message";
xhttp.send(`msg=${text}`);
You could also just use +
let text = "message";
xhttp.send('msg=' + text);
Please show below code:
let text = "message";
var xhr = new XMLHttpRequest();
var params="msg="+${text};
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status==200) {
alert(xhr.responseText);
}
}
xhr.open('POST', url where you want post data, true);
xhr.send(params);
I am using the following code to check my database for login information and receive it back inside the application but I am having the issue that I cannot parse the JSON information. I have parsed it into an array and when I run the following code the console returns:
I am wondering how do I take this a step further and read the number for "loggedin" and get the "username" also. I have tried replacing myArr with myArr[0].loggedin or even with myArr[0] but then I get a return of undefined.
Anyone any suggestions?
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('loginForm').addEventListener('submit', function() {
var usernameTest = document.getElementById('username').value;
var passwordTest = document.getElementById('username').value;
//alert("username is: " + usernameTest);
//console.log("password is: " + passwordTest);
//alert("test");
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
var myArr = JSON.parse(this.responseText);
chrome.extension.getBackgroundPage().console.log(myArr);
}
};
request.open('GET', 'http://localhost/api/login.php?username='+usernameTest+'&password='+passwordTest);
request.send();
});
});
What worked for me after GaetanoM's comment is:
myArr.UAPlugin[0].loggedin or myArr.UAPlugin[0].username
I want to read data from this link http://starlord.hackerearth.com/gamesext.
I went through this https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/JSON and was able to obtain data from https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json.
Trying similar approach for getting data from http://starlord.hackerearth.com/gamesext is not working for me.
This is how I tried:
var requestURL = 'http://starlord.hackerearth.com/gamesext';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var games = request.response;
document.getElementById("para").innerHTML = "for check";//para is a paragraph id
fun1(games);
}
function fun1(jsonObj){
//getting first title
document.getElementById("para").innerHTML = jsonObj[0]["title"];
}
I would want to know is that data in JSON and how to get it?
Try using the JSON.parse() method:
function fun1(jsonObj){
//getting first title
jsonObj = JSON.parse(jsonObj);
document.getElementById("para").innerHTML = jsonObj[0]["title"];
}
This will turn valid JSON into a javascript object that can be accessed as you are trying to do below.
This works perfectly fine for me:
var requestURL = 'http://starlord.hackerearth.com/gamesext';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.response[0].title) # LittleBigPlanet PS Vita
}
};
xhttp.open("GET", requestURL);
xhttp.responseType = 'json';
xhttp.send();
Give it a try!
Using fetch this is pretty simply.
Below is an example.
const url = 'https://mdn.github.io/learning-area/javascript/oojs/json/superheroes.json';
async function getData() {
const json = await (await fetch(url)).json();
console.log(json);
}
getData();
just put request.send(); after all the code you provided.