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.
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 stumped as to how to solve/diagnose ajax/jquery error.
This is my function:
var LogIn = {
Email: $("#Name").val(),
MobileNo: $("#txtMobileNumber").val(),
PinCode: '',
Message: '',
Success:false
};
$.ajax({
type: "POST",
crossDomain: true,
dataType: 'jsonp',
contentType: "application/json",
url: "https://a different server domain/api/LoginRequest",
data: JSON.stringify(LogIn),
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
I get this error:
jQuery doesn't support using POST and jsonp and the reason for that is very simple: when you inject a <script> tag into the DOM (which is what jQuery does when you use jsonp), the browser will send a GET request to the remote endpoint which has been referred to in the src property of this tag.
So basically you will need to use GET instead:
type: "GET"
Also since the data is sent as query string parameters you should remove the content type:
contentType: "application/json",
and do not JSON.stringify the data.
And here's the full example:
$.ajax({
type: "GET",
crossDomain: true,
dataType: 'jsonp',
url: "https://a different server domain/api/LoginRequest",
data: LogIn,
success: function (data) {
$("#divError").html(data);
},
error: function (error) {
jsonValue = jQuery.parseJSON(error.responseText);
$("#divError").html(jsonValue);
}
});
Of course this will work only if the remote endpoint supports JSONP and the GET verb.
Personally I would recommend using CORS instead of JSONP as it would give you much more options. You will be able to use POST in this case. Please refer to the following material as it seems you are using ASP.NET Web API on the server and trying to make a cross domain AJAX call: http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api
I am trying to access and API using jquery/post but its not working in IE8. Its throwing Access denied error in IE8 only.
js code:
var url = 'http://somecomp.cartodb.com:80/api/v1/map?map_key=xxxxxxxxxxxxxxxxxxxx&stat_tag=API';
var data = //some long data of length greater than 3000
$.ajax({
crossOrigin: !0,
type: "POST",
method: "POST",
dataType: "json",
contentType: "application/json",
url: url,
data: JSON.stringify(data),
success: function(a) {
console.log('success');
},
error: function(a) {
console.log('error');
}
})
If I add ?callback=? at the end of url, it still fires the error callback but with statusText: 'success' and code: 200
here is full code: http://textuploader.com/ato0w
Change dataType to jsonp will allow you to make cross-domiain requests. This will work only with GET requests.
If you're using CORS for accessing cross-origin resource, try to add the following line:
$.ajax({
crossDomain: true, // replace "crossOrigin: !0;"
});
If this not working for you, try to add the following line above $.ajax() call.
jQuery.support.cors = true;
I have the following code:
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType:'application/json',
data: JSON.stringify($(this).serializeArray()),
dataType:'json'
});
});
And after I submit the form, I get a JavaScript alert with the json string, so that is made correct (on my server I only log it so it does not matter what it is in it). If I try to send a request to the same link from postman it works, it logs it.
I think I'm doing something wrong in the ajax call, but I am not able to figure out.
Try below piece of code. Add success and error handler for more details
$("form").submit(function()
{
//Checking data here:
$("input").each(function(i, obj)
{
});
alert(JSON.stringify($(this).serializeArray()));
var url='http://127.0.0.1:1337/receive';
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify($(this).serializeArray()),
dataType:'json',
success : function(response) {
alert("success");
},
error: function (xhr, status, error) {
alert(error);
}
});
});
data:{ list : JSON.stringify($(this).serializeArray())}
From the Jquery docs:
Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol.
crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url.
$.ajax({
url:'http://127.0.0.1:1337/receive',
data:{ apikey: 'secret-key-or-any-other-parameter-in-json-format' },
dataType:'jsonp',
crossDomain: 'true',
success:function (data) {alert(data.first_name);}
});
<script>
(function(){
var searchURL = 'http://en.wiktionary.org/wiki/search';
$.ajax({
type: "GET",
url: searchURL,
dataType: "jsonp",
cache: false,
async:false,
success: function(responseData, textStatus, XMLHttpRequest){
iframe(responseData);
}
});
})();
</script>
I added this script to my html file and it is show the following errors, copy pasting the function in console is also showing the same errors.
Uncaught SyntaxError: Unexpected token <
Resource interpreted as Script but transferred with MIME type text/html
could anyone help me resolve this issue, I am using Chrome brower.
You can't request arbitrary pages via AJAX, and jsonp doesn't magically make that work. You need to use the Wiktionary API.
The URL is http://en.wiktionary.org/w/api.php.
$.ajax({
url: 'http://en.wiktionary.org/w/api.php',
dataType: 'jsonp', // will automatically add "?callback=jqueryXXX"
cache: true, // the API complains about the extra parameter
data: { // the parameters to add to the request
format: 'json',
action: 'query',
titles: 'test'
},
success: function(data){
console.log(data);
}
});