I am working now in a phonegap android application, I need the user's current address, so that i have used this
JSON api.
This is my code to get data for location updates from JSON api
$.ajax('http://maps.googleapis.com/maps/api/geocode/json?latlng=26.9008773,75.7403539&sensor=true', {
dataType: 'jsonp',
timeout: 3000,
data: {
_method: 'GET'
},
success: function (data,status) {
if (data._status != 200) {
console.log('received error', data._status);
// handle error
}else{
console.log('received data', data);
// do something useful with the data
}
},
error: function(data,status) {
var myObject = JSON.stringify(data);
console.log("Data Returned is " + myObject);
console.log("Status is " + status);
alert('error');
},
complete: function(data, status) {
alert('complete');
}
});
Every time it goes on error section , then the complete section, never goes into the success part.
the console output is :
12-10 11:11:34.393: I/Web Console(10620): Data Returned is {"readyState":4,"status":404,"statusText":"error"} at file:///android_asset/www/index.html:263
12-10 11:11:34.393: I/Web Console(10620): Status is error at file:///android_asset/www/index.html:264
Can anyone tell me, where exactly the problem is ?
If I remember correctly the default security policy in PhoneGap is to block all network access. You need to whitelist http://maps.googleapis.com.
The api you request does not support jsonp, the final request will like this:
http://maps.googleapis.com/maps/api/geocode/json?callback=jQuery18309743240959942341_1386656119920&latlng=26.9008773,75.7403539&sensor=true&_method=GET&_=1386656120107
with the callback param, but the output is still json, not javsscript file like
jQuery18309743240959942341_1386656119920(jsonDataHere...)
Take a look at this: https://developers.google.com/maps/documentation/javascript/examples/geocoding-reverse, it request url like this
https://maps.googleapis.com/maps/api/js/GeocodeService.Search?5m2&1d40.714224&2d-73.96145200000001&7sUS&9sen&callback=_xdc_._4cni6z&token=46423
And the output is:
_xdc_._4cni6z && _xdc_._4cni6z( { ....
That's jsonp.
ajax_call ='http://maps.googleapis.com/maps/api/geocode/json?latlng=26.9008773,75.7403539&sensor=true';
$.ajax({
type: "GET",
url: ajax_call,
cache:false,
dataType: "json",
success: function(response){
$.each(response.results, function(key, value) {
//alert(value.formatted_address);
console.log(value.formatted_address);
});
}
}).done(function() {
})
Related
Good morning stackoverflow,
I try to get json response from an URL
Click, as expected i got Access-Control-Allow-Origin within GoogleChrome, I switched to FireFox, to avoid this problem and then i got status -1 and data null.
$(document).ready(function () {
var URL = "https://www.infojort.com/axs/search?q=marouani%20zied";
console.log('------------------------');
$.ajax({
url: URL,
dataType: 'application/json;charset=utf-8',
success:function (data) {
console.dir(data);
console.log('yes');
},
complete:function () {
console.log('yes');
}
})
$.ajax({
dataType: "application/json;charset=utf-8",
url: URL,
success: function (data) {
console.dir(data);
}
});
$.getJSON(URL, function (data) {
var items = [];
$.each(data, function (key, val) {
items.push("<li id='" + key + "'>" + val + "</li>");
});
$("<ul/>", {
"class": "my-new-list",
html: items.join("")
}).appendTo("body");
});
Notice :
I can get the response with postman without problems.
Content-Type →application/json;charset=utf-8
I need a solution with jquery, ajax or angularjs.
Thanks you all.
Your problem seems related to the API and not to your JavaScript call itself,
what I mean is that you are trying to Call to your API from a Cross Origin and it is not allowed by default for security reasons, so you have to enable cross origin in the server in order to make this kind of calls https://spring.io/understanding/CORS
Look at this, it is a Cross Origin call (Jquery within AngularJS):
$.ajax({
type: 'POST',
url: CTHelper.ApiUrl() + '/token',
data: {
grant_type: 'password',
username: $scope.UserName,
password: $scope.Password
},
success: function (result) {
alert('OK');
},
error: function (result) {
alert('Error');
}
});
but the API must allows CORS, this is a part of the file Startup.Auth.cs
[This example uses AspNet Web Api, C# as Backend]
public void ConfigureAuth(IAppBuilder app) {
...
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
...
}
Microsoft.Owin.Cors can be downloaded as a nuget package.
I am having a problem when trying to make POST or PUT requests to Firebase RESTful API...
To make the request I am using Valve's Panorama JavaScript which execution is handled by Google V8 engine.
A GET request (which works without problems) looks like this:
$.AsyncWebRequest("https://<project>.firebaseio.com/-KrFV19WfaC7tfY6qys6.json",
{
type: "GET",
complete: function (data){
$.Msg("WOW: " + JSON.stringify(data));
},
error: function (err){
$.Msg("Error: " + JSON.stringify(err));
},
});
And I get the response:
WOW: {"statusText":"success","responseText":"{\"a\":\"1\"}\u0000","status":200}
But when I try to do a PUT or POST request which code looks like this:
$.AsyncWebRequest("https://<project>.firebaseio.com/game.json",
{
type: "POST",
data: {"A":"B"},
success: function (data){
$.Msg("WOW: " + JSON.stringify(data));
},
error: function (err){
$.Msg("Error: " + JSON.stringify(err));
},
});
I get the next response:
Error: {"statusText":"error",
"responseText":"{\n \"error\" : \"Invalid data; couldn't parse JSON object, array, or value.\"\n}\n\u0000",
"status":400}
Can somebody help me understand what could be the problem?
Update
According to this piece of code
you have to wrap your object in a payload property:
data: {payload: JSON.stringify({ "A": "B" })},
Have to tried to use JSON.stringify() around your request data object?
Like:
$.AsyncWebRequest("https://<project>.firebaseio.com/game.json",
{
type: "POST",
data: JSON.stringify({"A":"B"}),
success: function (data){
$.Msg("WOW: " + JSON.stringify(data));
},
error: function (err){
$.Msg("Error: " + JSON.stringify(err));
},
});
Also, is there a contentType property in AsyncWebRequest?
So maybe you have to add
contentType: "application/json; charset=utf-8",
to the request object (after the type property for example).
Background :
this is a simple ajax request to fetch data from database, my query and server side code works just fine.
Problem :
When i put the GET URL in my browser it shows the correct JSON response, but firebug (Firefox extension) doesn't show any response, and the error message is logged.
alert('success'); doesn't show
$('#loadOrderDetails').click(function () {
var id = document.getElementById("order_id").value;
var dataString = 'order_id=' + id ;
alert(dataString);
$.ajax({
type: "GET",
url: "index.php?route=new/orders/GetOrder",
data: dataString,
cache: false,
dataType: 'json',
success: function (data) {
alert ('success');
// my code to show data in table..
},
error: function (req, status, err) {
console.log('something went wrong', status, err);
}
})
});
any suggestions?
thank you all, it seems that my problem was because of www , i solved it in server settings .
i want to create yammer status using php and javascript. this is my sample code for that-
<script type="text/javascript" data-app-id="client-id" src="https://c64.assets-yammer.com/assets/platform_js_sdk.js"></script>
<span id="yammer-login"></span>
<script>
$(function(){
yam.connect.loginButton('#yammer-login', function (resp) {
if (resp.authResponse) {
yam.platform.request({
url: "messages.json",
method: "POST",
data: {
"body" : "Message body",
"group_id": "4728511", //group id
"topic1": "TestTopic1",
"og_url": "http://google.com"
},
success: function (res) { //print message response information to the console
alert("The request was successful.");
console.dir(res);
yam.platform.request({
url: "https://www.yammer.com/api/v1/search.json",
method: "GET",
data: {
"search" : "TestTopic1"
},
success: function (data) { //print message response information to the console
alert("The request was successful.");
console.dir(data);
},
error: function (data) {
alert("There was an error with the request.");
console.log(data)
}
});
},
error: function (res) {
alert("There was an error with the request.");
console.dir(res);
}
});
}
});
The status is updated on yammer but its showing error, also i did not get the topic id.
so how can i correct it..??
thanks in advance
It looks like your second call to search.json is the culprit. When using the JS SDK you should be calling the REST resources directly instead of putting in the URL (like: www.yammer.com or api.yammer.com).
You've done this successfully with your first call to messages.json, but should update your second call to this:
yam.platform.request({
url: "search.json",
method: "GET",
data: {
"search" : "TestTopic1"
},
success: function (data) { //print message response information to the console
alert("The request was successful.");
console.dir(data);
},
error: function (data) {
alert("There was an error with the request.");
console.log(data)
}
});
I'm using the following code to get the dataa from the server:
$.getJSON('http://xxx.xxx.xxx.xx/SampleWebService/Service.svc/SampleMethod?callback=?', dd, function (data) {
alert(data);
});
From the server, I'm sending the byte array as response.
In firebug, in Net > Response tab, I get:
jQuery19101878696953793153_1365677709012([67,37,94,38,42,44,69,67,71,32,97,116,116,97,99,104,101,100,32,102,111,114,32,112,97,116]);
Also in Net > JSON tab, I get data with several keys.
But how to get the data at alert(data);; so that I process on that data.
I don't know, how this thing works.
Edit:
I tried this different approach:
$.ajax({
type: "GET",
dataType: "jsonp",
contentType: "application/javascript",
data: dd,
crossDomain: true,
url: "http://xxx.xxx.xxx.xx/SampleWebService/Service.svc/SampleMethod",
success: function (data) {
alert(JSON.parse(data));
},
complete: function (request, textStatus) { //for additional info
alert(request.responseText);
alert(textStatus);
},
error: function(request, textStatus, errorThrown) {
alert(textStatus);
}
});
But I got: parseerror as alert.
From looking at the docs (I haven't tried this) you need to explicitly tell jQuery that you're making a JSONP call that will invoke the function that's returned. Something like this:-
$.ajax({
type : "GET",
dataType : "jsonp",
url : "http://xxx.xxx.xxx.xx/SampleWebService/Service.svc/SampleMethod",
success: function(data){
alert(data);
}
});
Function you are looking for is JSON.parse. Please try this code :
$.post("YouURL", { 'ParameterName': paramvalue }, function (Data) {
var data = JSON.parse(data);
});
Your response is a function call. If u define function name with name jQuery19101878696953793153_1365677709012 you can process the 'data' else from your server just send the json as a response to $.getJSON's callback to work
The problem was the data was very huge. I was sending array of around 10,00,000+ bytes.
So instead I divided it into list of bytes (each having 1000 bytes) & then sent as response.
I don't know if this is the best solution, but it solved my problem.
BTW, thanks to all for helping me.