Issue sending AJAX request to another domain - javascript

I am trying to use this API: https://zipcodedistanceapi.redline13.com/API
But when I make the AJAX call, I'm getting this error:
XMLHttpRequest cannot load
https://zipcodedistanceapi.redline13.com/rest//radius.json/30341/10/mile.
No 'Access-Control-Allow-Origin' header is present on the requested
resource.
Here is the request:
$.ajax({
type: "GET",
url: 'https://zipcodedistanceapi.redline13.com/rest/<api key goes here...>/radius.json/30341/10/mile',
dataType: "json",
success: function(zipback) {
}
});
I know it has something to do with making the request from a different domain, but I don't not how to resolve the issue.

$.ajax({
type: "GET",
url: 'https://zipcodedistanceapi.redline13.com/rest/<api key goes here...>/radius.json/30341/10/mile',
dataType: "json",
jsonpCallback:'somename',
success: function(zipback) {
}
});

Related

AJAX how to pass api key in header [duplicate]

This question already has answers here:
CORS error when jquery ajax request on api
(2 answers)
Closed 5 years ago.
I have here a strange situation with AJAX call, how to pass api key in header:
My full url for my json is: https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&APIkey=fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0
And I am trying now to pass API key in headers of ajax call, but still have this error from console:
"Failed to load https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://bigsportlive.com' is therefore not allowed access."
Here is my ajax call:
var apiKey = "fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0";
$.ajax({
type: "GET",
url: "https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01",
headers: { "APIkey": apiKey },
success: function(result){
result[i].league_name
}
});
May be I am doing something not correct?
Thanks!
If you want to add a header (or a set of headers) to each request, use the beforeSend hook with $.ajaxSetup ():
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('x-my-custom-header', 'some value');
}
});
// Sends your custom header
$.ajax({ url: 'your/url' });
// Sends both custom headers
$.ajax({ url: 'your/url', headers: { 'x-some-other-header': 'some value' } });
Another solution consist to use lowercase for headers
$(document).ready(function () {
$.ajax({
url: "http://xx.xx.xx.xx:xx/api/values",
type: "GET",
dataType: "json",
headers: { "HeaderName": "MYKey" }
});
});
Yes, there is an Access-Control-Allow-Origin error.
If so, you may want a php backend to get this for you, I believe, using
<?php
$data = file_get_contents("https://apifootball.com/api/?action=get_events&from=2017-10-30&to=2017-11-01&APIkey=fd6b8ec7d651960788351ee2b1baffba6ac1a9c8eb047118a1a823c247bdade0");
echo json_encode($data);
?>
Then use an ajax call to this file.
$.ajax({
type: "GET",
url: 'name_of_php_file.php',
dataType: "json",
success: function(result){
alert(result);
}
});

error in sending a post request using ajax

I'm trying to send a post request using ajax but I keep getting the following error :
XMLHttpRequest cannot load http://192.168.1.123:8080. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
here is my code
$.ajax({
type: "POST",
url: "http://192.168.1.123:8080",
data: JSON.stringify([{"VisitorName ": " "+document.getElementById("VisitorName ").value}
]),
contentType: "application / json ",
crossDomain: true,
dataType: "json",
success: function (data) {
alert(data);
},
failure: function (errMsg) {
alert(errMsg);
}
});
$.ajax({
type: "POST",
url: "http://192.168.1.123:8080,
data: JSON.stringify([
{
"
VisitorName ": "
"+document.getElementById("
VisitorName ").value,
}
From what I can tell the comma next to value is causing a syntax error. Also within the code you do not close the " for "http://192.168.1.123:8080

Ajax specified as POST but making a GET

What is wrong with the AJAX request? for some reason my browser picks it up as a GET request, when I specified it as a post???
var body = "<tsRequest><credentials name='username' password='password'><site contentUrl=''/></credentials></tsRequest>";
var url = "http://172.18.74.145/api/2.0/auth/signin";
$.ajax({
url: url,
crossDomain: true,
data: body,
type: 'POST',
contentType: "text/xml",
dataType: "jsonp",
success : console.log("too"),
error : function (xhr, ajaxOptions, thrownError){
console.log(xhr.status);
console.log(thrownError);
}
});
I get the error:
GET http://172.18.74.145/api/2.0/auth/signin?callback=jQuery1720699254485778510…%20contentUrl=%27%27/%3E%3C/credentials%3E%3C/tsRequest%3E&_=1442263213074 405 (Method Not Allowed)
and if I change the "ajax" to "post" then the url is messed up.
You need to specify the HTTP method as
type: 'POST',
and not as
method:'POST',
But anyway you basically can't use JSONP with POST.

ajax post method treated as get by restclient

I got an url let’s say abc its type is post. if I try to call it as $.ajax method post it is showing method not allowed 405 error. it I sent by method get it is working fine but the business is not done how to solve the issue?
js code:
$.ajax({
type: "POST",
url: url,
data: data,
beforeSend: function (request){
request.setRequestHeader("X-CSRF-TOKEN", token)
},
success: function(res){
console.log(res)
},
error: function(){
JSON.parse(this.error.arguments[0].responseText).error.message.value
},
dataType: "json"
});
You should use 'method' instead of 'type'. Try this:
$.ajax({
method: "POST",
url: url,
data: data,
beforeSend: function (request){
request.setRequestHeader("X-CSRF-TOKEN", token)
},
success: function(res){
console.log(res)
},
error: function(){
JSON.parse(this.error.arguments[0].responseText).error.message.value
},
dataType: "json"
});
Or you can use the jQuery.post method.
405 Method Not Allowed
The method specified in the Request-Line is not allowed for the resource identified by the Request-URI. The response MUST include an Allow header containing a list of valid methods for the requested resource. 405 Method Not Allowed

Setting request header in ajax

I have trouble with a piece of ajax code. This is the error message I get from mod security:
/ajaxController.php?mod=catalog&op=ajaxSeenProducts HTTP/1.1
Access denied with code 400 (phase 2). Operator EQ matched 0 at
REQUEST_HEADERS. [file "/usr/local/apache/conf/modsec2.user.conf"]
[line "12"] [id "960012"] [msg "POST request must have a
Content-Length header"] [severity "WARNING"] [tag
"PROTOCOL_VIOLATION/EVASION"]
There is a module in the web shop I am working on, which shows the last viewed products, and the jquery code I have is this:
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
While searching for the solution, I have found in various places that I need to set the
Content-length
parameter, but all I have found is in this format:
xmlHttp.setRequestHeader("Content-length", params.length);
Is there any way to set the request header in the code format I have provided above? I have already tried something like:
headers: {
"Content-Length": params.length
}
but with no result. Any help would be appreciated.
use code like:
var url = '{HOME}ajaxController.php?';
var data = "mod=catalog&op=ajaxSeenProducts";
$.ajax({
url: url,
data: data,
dataType: "html",
type:'post',
success:function(seenProducts){
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
},
error:function(response){
}
});
you can use the beforeSend function to set the headers
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", authorizationToken);
},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
or other way you can do it like
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
headers: {"X-Test-Header": "test-value"},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});

Categories

Resources