Trying to update Google Groups with PATCH via Javascript - google-groups-api

I am trying to update a Google Group using PATCH and cannot get it to work. I am not sure if it is a syntax issue or it cannot be done via Javascript. I can successfully perform a "get" operation using OAUTH, but not the PATCH.
Should I be using OAuth or Bearer in setRequestHeader "Authorization" (both seem to work fine for the GET and fail in the same manner during "PATCH".
The get works fine. The error on PATCH is { "error": { "errors": [ { "domain": "global", "reason": "invalid", "message": "Permission denied: Cannot hide from Groups directory." } ], "code": 400, "message": "Permission denied: Cannot hide from Groups directory." } }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttppatcher;
var xmlhttp;
var data;
if (window.XMLHttpRequest) {
xmlhttppatcher = new XMLHttpRequest(); xmlhttppatcher.open("PATCH","https://www.googleapis.com/groups/v1/groups/nogads2%40mydomain.org", false);
xmlhttppatcher.setRequestHeader("Content-Type", "application/json");
xmlhttppatcher.setRequestHeader("Authorization", "OAuth " + "ya29.AHES6ZR_yljyMvWCv0gWbwIASYYp29S8rFUA-dd-YkyyjTHz");
//xmlhttppatcher.setRequestHeader("Authorization", "Bearer " + "ya29.AHES6ZR_yljyMvWCv0gWbwIASYYp29S8rFUA-dd-YkyyjTHz");
data = '{"replyTo": "REPLY_TO_MANAGERS"}';
alert(data);
xmlhttppatcher.send(data);
alert('Your data was sent');
document.getElementById("myDiv1").innerHTML = xmlhttppatcher.responseText;
alert('readystate: ' + xmlhttppatcher.readyState + ' status: ' + xmlhttppatcher.status); //this should return 4 & 200
if (xmlhttppatcher.status == 200)
alert("The request succeeded!\n\nThe response representation was:\n\n" + xmlhttppatcher.responseText);
else
alert("The request did not succeed!\n\nThe response status was: " + xmlhttppatcher.status + " " + xmlhttppatcher.statusText + ".");
}
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "https://www.googleapis.com/groups/v1/groups/nogads2%40mydomain.org?alt=json", false);
xmlhttp.setRequestHeader("Authorization", "OAuth " + "ya29.AHES6ZR_yljyMvWCv0gWbwIASYYp29S8rFUA-dd-YkyyjTHz");
xmlhttp.send();
alert('readystate: ' + xmlhttp.readyState + ' status: ' + xmlhttp.status); //this should return 4 & 200
document.getElementById("myDiv2").innerHTML = xmlhttp.responseText;
if (xmlhttp.status == 200)
alert("The request succeeded!\n\nThe response representation was:\n\n" + xmlhttp.responseText);
else
alert("The request did not succeed!\n\nThe response status was: " + xmlhttp.status + " " + xmlhttp.statusText + ".");
}
}
</script>
</head>
<body>
<div id="myDiv1"><h2>Let AJAX change this text (DIV1)</h2></div><br />
<div id="myDiv2"><h2>Let AJAX change this text (DIV2)</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>

Hey I got the same problem, and I fixed it by creating a new Groups object[Java] and just setting the specific attribute that I wanted to update

Related

ERR_NAME_NOT_RESOLVED in OpenWeather Api Call

I'm putting together my first Api project and I'm using OpenWeather to request conditions for a city. When I run my code, I get "ERR_NAME_NOT_RESOLVED." I've checked and rechecked my URL formatting and I'm not getting any errors when running my code. Could anyone point me in the right direction?
My HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script defer src="./js/script.js"></script>
<title>Weatherd</title>
</head>
<body>
<h1>Weatherd</h1>
<form>
<input type="text" placeholder="Search by city"/>
<input type="submit" value="Search"/>
</form>
<main>
<p>Weather for</p>
<p id="weatherFor"></p>
<p>Temperature: </p>
<p id ="temp"></p>
<p>Currently feels like: </p>
<p id="feelsLike"></p>
<p>Conditions: </p>
<p id="desc"></p>
</main>
</body>
</html>
My JS
const $weatherFor = $('#weatherFor');
const $temp = $('#temp');
const $feelsLike = $('#feelsLike');
const $desc = $('#desc');
const $input = $('input[type="text"]');
let weatherData, userInput;
$('form').on('submit', handleGetData);
function handleGetData(event) {
event.preventDefault();
userInput = $input.val();
$.ajax({
url: 'https://www.api.openweathermap.org/data/2.5/weather?q='+userInput+'&APPID=15ff99dd07f18bda25869ab24d06891e'
}).then(
(data) => {
weatherData = data;
render();
},
(error) => {
console.log('bad request', error);
}
);
}
function render() {
$weatherFor.text(weatherData.weatherFor);
$temp.text(weatherData.temp);
$feelsLike.text(weatherData.feelsLike);
$desc.text(weatherData.desc);
}
It's been a while since the question was asked, but given the amount of visits this question has had so far, this answer might help someone.
const url = "api_url_here";
const result = await axios
.get(url)
.then((res) => {
const { status } = res;
return status && status == 200
? { ...res.data, status: 200 } // return data + status 200
: { status: 400 }; // create and return status 400 on error
})
.catch((err) => {
return { status: 400 }; // create and return status 400 on error
});
// work with the returned status
if(result.status == 200) {
// success
} else {
// error
}
I used axios, but the idea is very much transferable to Fetch Api or Ajax.

SOAP webservice call by ajax in phonegap error

I'm having a problem with trying to set up a working web service in my application I'm making using Phonegap. I need to get data from an existing web service. I found that by using a simple ajax request, this should be working. Am I not using the ajax request correctly?
The web service I'm trying to call can be found here: http://ws.swinggift.com/SGServices.asmx
EDIT: I tested it on http://wsdlbrowser.com/ and I'm getting my xml file back, how does this site work ?
I'm working in the ripple emulator so I have a cross domain proxy.
I'm suspecting that my request header may be off ?
error that I'm getting:
Failed to load resource: the server responded with a status of 400 (Bad Request) (10:26:26:851 | error, network)
at https://rippleapi.herokuapp.com/xhr_proxy?tinyhippos_apikey=ABC&tinyhippos_rurl=http%3A//ws.swinggift.com/SGServices.asmx%3Fop%3DGetVouchers
(I can't make my logon code public)
my test html file:
<html>
<head>
<title>Calling Web Service from jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$("#btnCallWebService").click(function(event) {
var wsUrl = "http://ws.swinggift.com/SGServices.asmx?op=GetVouchers";
var soapRequest =
'<?xml version="1.0" encoding="utf-8"?>' +
'<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/">' +
'<soap:Body>' +
'<GetVouchers xmlns="http://tempuri.org/">' +
'<logoncode>ICantGiveYouThis</logoncode>' +
'</GetVouchers>' +
'</soap:Body>' +
'</soap:Envelope>';
$.ajax({
type: "POST",
url: wsUrl,
contentType: "text/xml; charset=utf-8",
dataType: "xml",
crossDomain: true,
data: soapRequest,
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
XMLHttpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/GetVouchers");
XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
},
success: processSuccess,
error: processError
});
});
});
function processSuccess(data, status, req) {
if (status === "success")
$("#response").text($(req.responseXML));
}
function processError(data, status, req) {
console.log(req.responseText + " " + status);
}
</script>
</head>
<body>
<h3>
Calling Web Services with jQuery/AJAX
</h3>
<input id="btnCallWebService" value="Call web service" type="button" />
<div id="response" >
</div>
</body>
</html>
Thanks!
EDIT:
I don't know if it helps but if I do a 'GET' with the this code, I get the webpage in HTML format if I ask for the responseText
<html>
<head>
<title>SOAP JavaScript Client Test</title>
<!-- jQuery / jQueryMobile Scripts -->
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/jquery.mobile-1.3.1.min.js"></script>
<script type="text/javascript">
function soap() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'http://ws.swinggift.com/SGServices.asmx?op=GetVouchers', true);
// build SOAP request
var sr =
'<?xml version="1.0" encoding="utf-8"?>' +
'<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/">' +
'<soap:Body>' +
'<GetVouchers xmlns="http://tempuri.org/">' +
'<logoncode>something</logoncode>' +
'</GetVouchers>' +
'</soap:Body>' +
'</soap:Envelope>';
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
console.log('done' + xmlhttp.responseText);
$("#response").text($(xmlhttp.responseXML));
}
};
// Send the POST request
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.setRequestHeader("Accept", "application/xml, text/xml, */*");
xmlhttp.setRequestHeader("SOAPAction", "http://tempuri.org/GetVouchers");
xmlhttp.send(sr);
// send request
// ...
}
</script>
</head>
<body>
<form name="Demo" action="" method="post">
<div>
<input type="button" value="Soap" onclick="soap();" />
<div id="response" >
</div>
</div>
</form>
</body>
</html>
Try setting processData: false. This flag is true by default and jQuery is converting your XML to string.
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
$.ajax({
type: "POST",
url: wsUrl,
contentType: "text/xml; charset=utf-8",
dataType: "xml",
crossDomain: true,
data: soapRequest,
processData: false,
beforeSend: function(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
XMLHttpRequest.setRequestHeader("SOAPAction", "http://tempuri.org/GetVouchers");
XMLHttpRequest.setRequestHeader("Accept", "application/xml, text/xml, */*");
},
success: processSuccess,
error: processError
})
It was an emulator problem ... Working now with the code above.

Username availability checking using Ajax in JSP and stopping form submission

I am new to ajax and I am trying to create a gmail type username availability check by using Ajax and JavaScript in JSP.
My code works well for username availability check but I am not able to stop the form submission when a username is not available.
For checking username availability I used onkeyup() which checks each character, but for preventing the form submission I used onsubmit() in form tag.
For execution flow check I used alert statements in this code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
function returnFunction(str)
{
alert("1");
var flag = new Boolean(false);
usernameValidation(str);
alert("2");
function usernameValidation(str)
{
alert("3");
var xmlHttpRequest;
if(window.XMLHttpRequest)
{
alert("4");
xmlHttpRequest = new XMLHttpRequest();
alert("5");
}
else
{
alert("6");
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function()
{
alert("7");
if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
{
alert("8");
if(xmlHttpRequest.responseText=="available")
{
flag=new Boolean(true);
alert("9 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is available";
}
else
{
flag=new Boolean(false);
alert("10 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is already taken";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
alert("before return flag is:"+flag);
return flag;
};
function formValidation(){
if(returnFunction(document.f1.username.value))
{
alert("caught flage:true");
return true;
}
else{
alert("caught flage:false");
return false;
}
}
</script>
</head>
<body>
<form method="post" action="register" name="f1" onsubmit="return formValidation()">
User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="returnFunction(this.value)"></div>
<span id="myDiv" style="color: red"></span>
<input type="submit" value="register">
</form>
</body>
</html>
Ajax is asynchronous so your call to returnFunction , need not return the correct flag, it will return false always as most probably success function will be triggered only after method is completed(onresponse).
So you need to ensure that response of Ajax cal is recieved using a completed boolean, and continuously checking it until it is true.
<script type="text/javascript" language="javascript">
function returnFunction(str)
{
alert("1");
var flag = new Boolean(false);
var completed = new Boolean(false);
usernameValidation(str);
alert("2");
function usernameValidation(str)
{
alert("3");
var xmlHttpRequest;
if(window.XMLHttpRequest)
{
alert("4");
xmlHttpRequest = new XMLHttpRequest();
alert("5");
}
else
{
alert("6");
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function()
{
alert("7");
if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
{
alert("8");
if(xmlHttpRequest.responseText=="available")
{
flag=new Boolean(true);
alert("9 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is available";
}
else
{
flag=new Boolean(false);
alert("10 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is already taken";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
alert("before return flag is:"+flag);
return flag;
};
function formValidation(){
returnFunction(username);
while(!completed) {
//wait for ajax response
}
if(flag)
{
alert("caught flage:true");
return true;
}
else{
alert("caught flage:false");
return false;
}
}
</script>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
var flag = new Boolean(false);
function returnFunction(str)
{
alert("1");
usernameValidation(str);
alert("2");
function usernameValidation(str)
{
alert("3");
var xmlHttpRequest;
if(window.XMLHttpRequest)
{
alert("4");
xmlHttpRequest = new XMLHttpRequest();
alert("5");
}
else
{
alert("6");
xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpRequest.onreadystatechange = function()
{
alert("7");
if(xmlHttpRequest.readyState==4 && xmlHttpRequest.status==200)
{
alert("8");
if(xmlHttpRequest.responseText=="available")
{
flag=new Boolean(true);
alert("9 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is available";
}
else
{
flag=new Boolean(false);
alert("10 flag:"+flag);
document.getElementById("myDiv").innerHTML="username is already taken";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
alert("before return flag is:"+flag);
return flag;
};
function formValidation(){
if(returnFunction(document.f1.username.value))
{
alert("caught flage:true");
document.f1.submit();
}
else{
alert("caught flage:false");
alert("Username chossen by u is already taken.Please choose different Username");
}
}
</script>
</head>
<body>
<form method="post" action="register" name="f1" >
User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="returnFunction(this.value)"></div>
<span id="myDiv" style="color: red"></span>
<input type="submit" value="register">
</form>
</body>
</html>
make changes like this it will work .if any prob let be know.
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" language="javascript">
function getXMLHttpRequest(){
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions
// of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
};
function usernameValidation(str)
{
if (str.length==0)
{
document.getElementById("uname").innerHTML="should not be empty";
return false;
}
else if(str.length<=4)
{
document.getElementById("uname").innerHTML="need more than 4 charachers";
return false;
}
else{
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange =function()
{
if (xmlHttpRequest.readyState < 4 && xmlHttpRequest.readyState > 0)
{
document.getElementById("uname").innerHTML = "<img src='images/load.gif' alt='checking...' width=16 height=16/>";
}
if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200)
{
if(xmlHttpRequest.responseText=="available")
{
document.getElementById("uname").innerHTML = "<img src='images/ok.png' alt='username available' width=16 height=16/>";
document.getElementById("uname1").innerHTML = ".";
}
else
{
document.getElementById("uname").innerHTML = "username not available";
}
}
};
xmlHttpRequest.open("POST", "UsernameCheck", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttpRequest.send("uname="+str);
};
};
function userSubmitValidation(){
var msg = document.getElementById("uname1").innerHTML;
if(msg=='.'){
return true;
}
else{
return false;
}
};
</script>
</head>
<body>
<form method="post" action="register" name="f1" onsubmit="return userSubmitValidation()">
User Name:<div id="myDiv1"><input type="text" name="username" size="20" onkeyup="usernameValidation(this.value)" onblur="usernameValidation(this.value)"></div>
<span id="uname" style="color: red"></span><span id="uname1" style="color: white"></span>
<input type="submit" value="register">
</form>
</body>
</html>
i am new at ajax too and i am kind of trying to do the same thing as you are doing. I have successfully checked the username availability using ajax and jsp. Then the thing i stuck at that even if a username is not available the page still submit after clicking submit button. Then I used javascript to solve this problem. I compared the returned text with another text declared before. If check successful then it will go to next page otherwise not. For details please check this page->"Ajax based username availablity checking and then generating some username to use in jsp". There check out the sample.jsp code. In that code a i did the checking part in the function named "conditions()". In that function the variable "checkvalue" hold the returned text which is generated by availability check. Then i compare it with the text "available". If matches then the page will submit other wise not. I am not sure is this what you wanted to know or not and if it is then my answer helps you or not. Thank you and good luck..

How to retrieve oAuth Accees token from Redirect Window

I am working on an app where i am communicating to Windows API. I am using oAuth 2.0 for the same.
Complete code has been done using JS/HTML5 only. However i am facing one issue,
whenever i request for access token, it opens a new windows with my redirect url appended with access token and other parameters. But the token is not sent back to my code. I have to manually copy the code and thus it defeats purpose of my application. Is there any way , when i click on button (that invokes my oAuth call), a new pop up window appears and redirects back to my called url with access token ?
here is what i have done so far:
var APPLICATION_CLIENT_ID = 'SOME_NUMBERS',
REDIRECT_URL = "http://www.myweb.com";
WL.Event.subscribe("auth.login", onLogin);
WL.init({
client_id: APPLICATION_CLIENT_ID,
redirect_uri: REDIRECT_URL,
scope: 'wl.skydrive_update',
response_type: "token"
});
WL.ui({
name: "signin",
element: "signInButton",
brand: "hotmail",
type: "connect"
});
function greetUser(session) {
var strGreeting = "";
WL.api(
{
path: "me",
method: "GET"
},
function (response) {
if (!response.error) {
strGreeting = "Hi, " + response.first_name + "!"
document.getElementById("greeting").innerHTML = strGreeting;
}
});
}
function onLogin() {
var session = WL.getSession();
if (session) {
greetUser(session);
}
}
var tokenAuth = //Adding Manually//
var apiURL = "https://apis.live.net/v5.0/me/";
var tokenAuthParam = "?access_token=" + tokenAuth;
And this is where i am stuck. Can anyone pls help. Also greetUser function is not working. I want this to work as client side only using js/html only. `
Not sure what you are trying to do with the tokenAuth. Got this working which should help you with the greeting part:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JScript Win 8 example</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
<script type="text/javascript" src="/LiveSDKHTML/js/wl.js"></script>
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
</head>
<body>
<div id="signin"></div>
<br />
<label id="infoLabel"></label>
<br />
id: <label id="id"></label><br />
firstname: <label id="first_name"></label><br />
lastname: <label id="last_name"></label><br />
fullname: <label id="name"></label><br />
gender: <label id="gender"></label><br />
locale: <label id="locale"></label><br />
<script>
WL.Event.subscribe("auth.login", onLogin);
WL.init({
scope: "wl.signin",
});
WL.ui({
name: "signin",
element: "signin"
});
function onLogin(session) {
var session = WL.getSession();
if (session.error) {
document.getElementById("infoLabel").innerText = "Error signing in: " + session.error;
}
else {
document.getElementById("infoLabel").innerText = "Signed in.";
WL.api(
"/me", "GET",
function (response) {
if (!response.error) {
document.getElementById("id").innerText = response.id;
document.getElementById("first_name").innerText = response.first_name;
document.getElementById("last_name").innerText = response.last_name;
document.getElementById("name").innerText = response.name;
document.getElementById("gender").innerText = response.gender;
document.getElementById("locale").innerText = response.locale
}
else {
document.getElementById("infoLabel").innerText = "API call failed: " + JSON.stringify(response.error).replace(/,/g, "\n");
}
}
);
}
}
</script>
</body>
</html>

Ajax (jQuery) cross domain output -

As is such function doesn't support cross domain request
function makeRequest(url) {
var http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
} else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
}
if (!http_request) {
alert('Cannot create an XMLHTTP instance');
return false;
}
http_request.onreadystatechange = function() { alertContents(http_request); };
http_request.open('GET', url, true);
http_request.send(null);
}
function alertContents(http_request) {
if (http_request.readyState == 4) {
if (http_request.status == 200) {
receiveData(http_request.responseText);
} else {
alert("error");
}
}
}
so decided to use jQuery (with this plugin) but function
$.ajax({
url: suchurl,
type: "GET",
//dataType: "text",
dataType: "text",
//global: false,
//async:false,
cache: false,
success: function(data) {
//alert(data);
alert(data.responseText);
}
});
output like
<html>
<head>
<meta content="HTML Tidy for Java (vers. 26 Sep 2004), see www.w3.org" name="generator"/>
<title/>
</head>
<body>
<p>new_towns = [ {id:"0", name:" "},
{id:"205",
name:"City205"},
{id:"17",
name:"City17"}
];</p>
</body>
</html>
Why?.. when expecting just
new_towns = [ {id:"0", name:" "}, {id:"205", name:"City205"}, {id:"17", name:"City17"} ];
What you advice?
Thanking you in advance.
such example code - doesn't work
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("jquery", "1.6.2");
google.setOnLoadCallback(function() {
$.ajax({
url: suchurl,
type: "GET",
dataType: "text",
crossDomain:true,
async:true,
cache: false,
success: function(data) {
alert("all right");
}
});
});
</script>
</head>
<body>
</body>
</html>
OK, guys, it's more simple and more fast&understandable decision use script
get.php
<?php
if(isset($_POST['geturl']) and !empty($_POST['geturl'])) {
$data = file_get_contents($_POST['geturl']);
print $data;
}
?>
and then just
$.ajax({ url: 'get.php',
data: {geturl: suchurl},
type: 'POST',
dataType: "text",
cache: false,
success: function(data){
alert(data);
//do something else
}
});
TNX VERY MUCH FOR YOUR ATTEMPTS TO HELP AND TIPS!
I don't guess you need to rely on a plugin for getting cross domain JSON. You can use jquery's 'jsonp' dataType.
You can follow the 'JSONP' section in the following URL:
http://api.jquery.com/jQuery.getJSON/
The output you are getting may be something that the URL returns. Make sure the requested URL returns only the expected output.
Thanks
Looks like in your first example, you are requesting text/xml, but in the second one, your type is just "text" which might be causing the url to send back a differently formatted response. For JSON data, you could also try a type of "application/json".
The JQuery $.ajax() function includes native JSONP support. You must add the parameter crossDomain:true
You can read about it here: http://api.jquery.com/jQuery.ajax/

Resources