I am trying to make the client side receiving JSON data from the Server, however, it constantly popped up the error method. When I try to use Chrome to debug, it popped up: XMLHttpRequest cannot load http://localhost:8080/TransportationNetwork/rest/paths?st=3,6. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I have tried to change dataType to 'jsonp', but it doesn't work. However, when I use POSTMAN to test the data from Server, everything works fine, I can see the JSON data comes from the server.
Here is the picture shows the testing result from POSTMAN:
Pictures shows POSTMAN testing result from server
The following is my code on both server side and client side:
Could anyone tell me how to add the 'Access-Control-Allow-Origin' header for my java code?(if it is this problem)
The Java Code:
#Path("/paths")
public class PathsResource {
PathDao pathDao;
public PathsResource() {
pathDao = new PathDao();
}
#GET
#Produces(MediaType.APPLICATION_JSON)
//#Consumes("text/plain")
public List<DirectedEdge> pathsInfo(#QueryParam("st") String st) {
System.out.println("Searching paths : " + st);
return pathDao.getEdgeList(st);
}
}
The Javascript:
var serviceURL = "http://localhost:8080/TransportationNetwork/rest/paths";
$('#findPaths').click(function() {
getPaths();
});
function getPaths() {
console.log('display paths');
$.ajax({
type:'GET',
url: serviceURL,
dataType:'json', // data type get back from server
data:'st=' + dataToServer(), //data sent to server
success: renderList,
error: function(jqXHR, textStatus, errorThrown){
alert('Path Finder: ' + textStatus);
}
});
}
function dataToServer() {
var array = "";
str1 = $('#source').val();
str2 = $('#target').val();
array = str1 + "," + str2;
return array;
}
function renderList(data) {
//var parsedData = JSON.parse(data);
var list = data == null ? [] : (data instanceof Array ? data : [data]);
$('#PathList li').remove();
$.each(list, function(index, path) {
$('#PathList').append('<li>'+ path.source + ' -> ' + path.target + ': ' + path.weight + '</li>');
});
}
Related
I have been trying to make an AJAX request from localhost (which is onfigured for https) to a server that is over http. everytime i receive an error from the browser saying it has been blocked since there is some "mixed content" in the call.
How can i avoid such error? sometimes in the browser I can see the JSON response I need but it never makes it to the page due to the error.
Here is the code when i click on a button to request data:
$(document).ready(function () {
var gallery = null;
$("#getSubscriptionWorkflows").click(function () {
gallery = new Gallery($("#apiLocation").val().trim(), $("#apiKey").val().trim(), $("#apiSecret").val().trim());
gallery.getSubscriptionWorkflows(function (workflows) {
var listStr = "";
var len = workflows.length;
if (len === 0) {
listStr = "There are no workflows in the subscription associated with the given api key";
}
for (var i = 0; i < len; i++) {
listStr += "<li>" + workflows[i].metaInfo.name + " - " + workflows[i].id + "</li>";
}
$("#workflowList").html(listStr);
}, function (response) {
$("#workflowList").html(response.responseJSON && response.responseJSON.message || response.statusText);
});
});
});
And here is the API code:
Gallery = function(apiLocation, apiKey, apiSecret) {
this.apiKey = apiKey;
this.apiSecret = apiSecret;
this.apiLocation = apiLocation;
this.getSubscriptionWorkflows = function (success, error){
var type = "GET",
url = this.apiLocation + "/workflows/subscription/",
params = buildOauthParams(this.apiKey),
//add any user parameters before generating the signature
signature = generateSignature(type, url, params, this.apiSecret);
$.extend(params, {oauth_signature: signature});
$.ajax({
type: type,
url: url,
data: params,
success: success,
error: error
});
};
as practicing Ajax, I wrote a Ajax call that sends to a local asp.net Handler.ashx a Json with a username and password, and returns true if they are equal to "jhon" "123456", else false.
I debugged the code, and I saw that the Handler.ashx receives the call, does the validation, and write to response, but the Ajax call not success.
this the Ajax call:
$.ajax({
url: '/Handler.ashx',
dataType: 'json',
data: {
name: document.getElementById("username").value,
password: document.getElementById("password").value
},
success: function (json) {
alert(json.isvalid);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert(textStatus + " " + errorThrown);
}
});
alert("failed");
and this is the server side:
<%# WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
public class Handler : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
Console.WriteLine("check");
var name = context.Request["name"];
var password = context.Request["password"];
string response = IsValid(name, password) ? "true" : "false";
context.Response.ContentType = "appliaction/text";
context.Response.Write("{isvalid:'" + response + "'}");
}
private bool IsValid(string name, string password)
{
Console.WriteLine("isvalid");
return (name == "jhon" && password == "123456");
}
public bool IsReusable
{
get
{
return false;
}
}
}
thanks!
The simplest change (which still isn't very pretty) would be to change this...
string response = IsValid(name, password) ? "true" : "false";
context.Response.ContentType = "appliaction/text";
context.Response.Write("{isvalid:'" + response + "'}");
...to this...
string response = IsValid(name, password) ? "true" : "false";
context.Response.ContentType = "application/json";
context.Response.Write("{ \"isvalid\" : \"" + response + "\" }");
(Note that you'd misspelt "application"... and you should tell your caller than you're returning json data.)
I saw that the Handler.ashx receives the call, does the validation,
and write to response, but the Ajax call not success.
When you say the "AJAX call not success", does an error appear ?
I would recommend running your code in Google Chrome, open the Developer Options (by hitting F12), go into the Network tab, then refresh your webpage.
Watch the Network tab, click on the URL being called, then check the Request being sent, and the Response coming back.
Then also check the Console tab, to see if any JavaScript errors have quietly been thrown.
try adding this to your ProcessRequest method
JavaScriptSerializer serializer = new JavaScriptSerializer();
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public void ProcessRequest(HttpContext context)
{
Console.WriteLine("check");
....
return serializer.Serialize("{ isvalid: '" + response + "' }");
}
And in the client side
.....
success: function (msg) {
console.log(msg); //this is for you to see the response in the JS console
var jsonArray = $.parseJSON(msg.d);
console.log(jsonArray); //and this is the same
alert(jsonArray.isvalid);
}
.....
I have been able to successfully post a status update with image to Facebook using the graph API via an AJAX call. Now I would like to get the URL of the post, and redirect the user to the post as soon as it has been made, but I can't figure out how to get the URL. I thought the URL would be included in the response success data object, but I have tried iterating through it, and all I got was seemingly random numbers. Does anyone know how I can get the URL of the post and send the user there? Thanks. Here is my code below:
$.ajax({
url:"https://graph.facebook.com/" + userID + "/photos?access_token=" + accessToken,
type:"POST",
data:fd,
processData:false,
contentType:false,
cache:false,
success:function(data){
console.log("success " + data);
for (var key in data) {
if (data.hasOwnProperty(key)) {
var obj = data[key];
for (var prop in obj) {
// important check that this is objects own property
// not from prototype prop inherited
if(obj.hasOwnProperty(prop)){
console.log(prop + " = " + obj[prop]);
}
}
}
}
},
error:function(shr,status,data){
console.log("error " + data + " Status " + shr.status);
},
complete:function(){
console.log("Ajax Complete");
}
});
I couldn't able to remove the double quotes from json string. Following is my code.
var values = {};
$.each($('#regForm :input'), function(i, field) {
if (field.name == "submit") {
delete field.name;
} else {
values[field.name] = field.value;
}
});
var json_text = JSON.stringify(values);
var global = JSON.parse(json_text);
console.log(global);
$.ajax({
type : "POST",
dataType : "JSON",
data : global,
url : "http://localhost:8080/SpringRestServices/register",
beforeSend : function(xhr) {
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Accept-Encoding", "utf-8");
xhr.setRequestHeader("Content-type", "application/json");
},
success : function(data) {
alert("success"+data);
console.log("Success:", data);
},
error: function(xhr, textStatus, errorThrown) {
console.log("HI");
alert("Failed to cancel subscription! Message:" + textStatus /*+ jqXHR.errorThrown + xhr.responseText*/);
alert("readyState: " + xhr.readyState);
alert("responseText: "+ xhr.responseText);
alert("status: " + xhr.status);
alert("text status: " + textStatus);
alert("error: " + errorThrown);
}
});
Here is my output when I see it in the firefox debugger:
"{"username":"hi","email":"hi#gmail.com","password":"123"}"
I need the actual result:
{"username":"hi","email":"hi#gmail.com","password":"123"}
Can anyone help me on this.
This is my server code:
#RequestMapping(value = "/register", method = RequestMethod.POST)
#ResponseBody
public RegisterResponse newAccount(#RequestBody Register registration) {
String newAccountSql = "INSERT INTO register (email,password,username) VALUES (:email,:password,:username)";
RegisterResponse regResponse = new RegisterResponse();
regResponse.setResult(-1);
// ServiceDataBean<AuthToken> retBean = new
// ServiceDataBean<AuthToken>();
try {
System.out.println("register service calling.....");
MapSqlParameterSource namedParameters = new MapSqlParameterSource();
namedParameters.addValue("email", registration.getEmail());
messageDigest = MessageDigest.getInstance("MD5");
byte[] md5 = new byte[64];
messageDigest.update(
registration.getPassword().getBytes("iso-8859-1"), 0,
registration.getPassword().length());
md5 = messageDigest.digest();
namedParameters.addValue("password", convertedToHex(md5));
namedParameters.addValue("username", registration.getUsername());
GeneratedKeyHolder generatedKeyHolder = new GeneratedKeyHolder();
// TODO what to do with the updInt also check it's not -1
int updInt = jdbcTemplate.update(newAccountSql, namedParameters,
generatedKeyHolder);
regResponse.setResult(0);
System.out.println("from register");
} catch (Throwable e) {
regResponse.setResult(001);
e.printStackTrace();
}
return regResponse;
}
Try
json_text= json_text.slice(1, json_text.length-1);
See if writing your ajax request like this helps. It removes the explicit dataType that I think could be causing you an issue and also removes the beforeSend function and replaces it with the built in contentType option (and removes the explicit return datatype).
$.ajax({
type : "POST",
data : global, //Or json_text, whichever worked.
url : "http://localhost:8080/SpringRestServices/register",
contentType : "application/json",
success : function(data) {
alert("success"+data);
console.log("Success:", data);
},
error: function(xhr, textStatus, errorThrown) {
console.log("HI");
alert("Failed to cancel subscription! Message:" + textStatus /*+ jqXHR.errorThrown + xhr.responseText*/);
alert("readyState: " + xhr.readyState);
alert("responseText: "+ xhr.responseText);
alert("status: " + xhr.status);
alert("text status: " + textStatus);
alert("error: " + errorThrown);
}
});
I dont think there is a need to replace any quotes, this is a perfectly formed JSON string, you just need to convert JSON string into object.This article perfectly explains the situation : Link
Example :
success: function (data) {
// assuming that everything is correct and there is no exception being thrown
// output string {"d":"{"username":"hi","email":"hi#gmail.com","password":"123"}"}
// now we need to remove the double quotes (as it will create problem and
// if double quotes aren't removed then this JSON string is useless)
// The output string : {"d":"{"username":"hi","email":"hi#gmail.com","password":"123"}"}
// The required string : {"d":{username:"hi",email:"hi#gmail.com",password:"123"}"}
// For security reasons the d is added (indicating the return "data")
// so actually we need to convert data.d into series of objects
// Inbuilt function "JSON.Parse" will return streams of objects
console.log(data); // output : Object {d="{"username":"hi","email":"hi#gmail.com","password":"123"}"}
console.log(data.d); // output : {"username":"hi","email":"hi#gmail.com","password":"123"} (accessing what's stored in "d")
console.log(data.d[0]); // output : { (just accessing the first element of array of "strings")
var content = JSON.parse(data.d); // output : Object {username:"hi",email:"hi#gmail.com",password:"123"}" (correct)
console.log(content.username); // output : hi
var _name = content.username;
alert(_name); // hi
}
url = 'https://api.twilio.com/2010-04-01/Accounts/'+ACCOUNT_SID+'/SMS/Messages/'+Sid+'.json';
var payLoadData = {
'SMSMessageSid' : Sid
};
var options =
{
method : "GET",
payload : payLoadData,
headers : {
'Authorization' : 'Basic ' + Utilities.base64Encode(ACCOUNT_SID + ':' + ACCOUNT_TOKEN)
}
};
var response = UrlFetchApp.fetch(url, options);
Why by using this google_script gives a Method_Not_Allowed
Request failed for https://api.twilio.com/2010-04-01/Accounts/XXXXXXXXXXXXX/SMS/Messages/XXXXXXXXXXXXXXXXXXXXX.json returned code 405. Server response: {"status":405,"message":"Method not allowed","code":20004,"more_info":"http:\/\/www.twilio.com\/docs\/errors\/20004"} (line 374, file "MakePhoneCall")
As we can see, https://www.twilio.com/user/account/developer-tools/api-explorer#GET/2010-04-01/Accounts/[AccountSid]/SMS/Messages/[SMSMessageSid].[format]
it's constructed according to this api ref
It seems that payload shouldn't be used while using GET method, hence using params would do the trick.
Still, the same method works when getting details of call, but not with message, interesting :)