Get json response with jquery or ajax or angular js - javascript

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.

Related

building wikipedia viewer with their API, always get error

I can't seem to get it working, I followed other code, and it didn't seem to get success, I then written it letter to letter, stil can't get success.
The url works great, I can put it in browser and it will show me the array which I need.
$(document).ready(function(){
$("#submitSearch").on("click", function() {
var searchInput = $("#txtName").val();
var url = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" + searchInput;
var wikiItemArray = [];
$.ajax({
url: url,
type: "GET",
async: false,
dataType: "json",
success: function (data) {
console.log(data);
},
error: function(error){
console.log("There was an error somewhere in &.ajax: " + url);
}
});
});
});
Change the dataType from "json" to "jsonp".
That api is not CORS enabled but does serve jsonp

Is it possible to use conditions within an AJAX call to avoid duplicate code?

For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:
var URL = RESOURCE + "?param1=" + param1 + "&param2=" + param2 + "&param3=" + param3();
if(URL.length>=2048) {
// Use POST method to avoid IE GET character limit
URL = RESOURCE;
var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
});
}else{
// Use GET
$.ajax({
type: "GET",
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("GET error");
},
success: function(data) {
alert("GET success");
}
});
}
Is there a way of me avoiding writing out this ajax twice? Something like
if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}
N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.
The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.
Principle:
var myAjaxSettings = {
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
}
if ( <condition a> )
myAjaxSettings.type = "GET";
if ( <condition b> )
myAjaxSettings.success = function (data) { ...make something different ... };
$.ajax(myAjaxSettings);

Get location from JSON in javascript

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

Error with Google finance match

I'm using jQuery, jQuery-UI auto complete along with this link as source
https://www.google.com/finance/match?matchtype=matchall&callback=callback&q=aa&_=1379423108762
here is my code:
$("#searchinput").autocomplete({
source: function (request, response) {
var q=request.term;
$.ajax({
type: "GET",
// url: "http://d.yimg.com/autoc.finance.yahoo.com/autoc", for http use only
url: "https://www.google.com/finance/match?matchtype=matchall",
data: {q: q},
dataType: "jsonp",
contentType: 'application/json; charset=utf-8',
jsonp : "callback",
jsonpCallback: "callback",
});
// call back function
callback = function (data) {
var suggestions = [];
//alert(JSON.stringify(data.matches));
$.each(data.matches, function(i, val) {
suggestions.push("Name:"+ val.n+" #Symbol:"+val.t+" #Exchange:"+val.e);
});
response(suggestions);
}
},
minLength: 1,
select: function (event, ui) {
$("#searchinput").val(ui.item.value.split("#")[0]);
},
});
I get the following error
Uncaught SyntaxError: Unexpected token :
here you can see the bug image: http://i.stack.imgur.com/NYMPG.jpg
The URL is not returning JSON-P. The error message is because JSON-P works by loading a remote JavaScript (and that isn't what the URL returns).
Since you aren't Google, you can't make that URL return JSON-P.
I'd suggest alternative approaches to getting the data, but Google don't provide an API for that data so you would be walking into Terms of Service violation territory.

How to show output in a div using partial rendering concept in MVC

I am using render partial concept in MVC. Its not showing the output in div. While debugging everything is OK (Showing Staus 200 OK) but its not going inside success block.Below is my jquery function.
function ShowNavigation() {
var jsonObj = {
'Display': 'Index',
taFormula: $('#taFormula').val()
};
$.ajax(
{
url: "/Home/Index",
type: "POST",
data: jsonObj,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (data) {
var message = data.Message;
$("#contentDiv").html(message).val();
}
});
}
My Controller code is:
[HttpPost]
public ActionResult Index(FormCollection collection)
{
var val = collection["taFormula"].ToString();
ViewBag.Output = GetValue(val);
return View();
}
Remove the datatype: "json" bit. You're receiving html back from the server, not json data, but because of that setting it's trying to parse it and failing. If you had an error callback function it would go into that.
Also, you don't need the .val() on $("#contentDiv").html(message).val();
Try adding an error handler to the ajax call and see if that gives you any more information:
error: function (xhr, status, error) {
alert(status + " : " + error);
}
Try this for your json object:
data: JSON.stringify(jsonObj),
You might need to include json.js for older browsers.

Categories