error in sending a post request using ajax - javascript

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

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);
}
});

CROS Origin API Call issue?

I host my MVC API in server 'A'.
I tried to call API using jquery ajax call from native server (server 'A'). it's working fine as expected.
But, when tried to call API from server 'B'. I got an error.
No 'Access-Control-Allow-Origin' header is present on the requested resource
My ajax call like below
$.ajax({
url: Url,
type: "GET",
data: Data,
contentType: "application/json charset=utf-8",
async: false,
cache: false,
error: function (xhr, ajaxOptions, thrownError) {
console.log("Exception in ajaxRequest - " + xhr.status + ' - ' + thrownError);
},
success: function (data) {
ResultData = $.parseJSON(data);
}
});

CORS: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'

I'm trying to login to moodle from an external webpage using a post form to moodle, I used the next ajax to send the inputs:
var frm = $('#loginForm');
frm.submit(function(e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
xhrFields:{
withCredentials:true
},
async:true,
beforeSend: function (xhr){
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
},
success: function (data) {
console.log("Logged");
},
error: function (data) {
console.log("NOT Logged");
},
});
});
Now into the moodle's login/index.php I insert the headers to make possible the CORS connection:
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Allow-Origin: http://fabianmurillo.000webhostapp.com");
header("Origin" : "http://fabianmurillo.000webhostapp.com");
When I run the code, the browser returns an error:
..preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin'..
enter image description here
Dunno why browser is blocking the connection for login to moodle.
Thanks for your help.

Jquery authentication error

Consider the following code:
var jsonData1 = $.ajax({
url: 'http://'+domainName+':9898/jolokia/read/*',
dataType:"json",
crossDomain: true,
beforeSend: function(xhr){
var username= '*';
var password= '*';
xhr.setRequestHeader("Authorization",
"Basic " + btoa(username + ":" + password));
},
async: false
}).responseText;
var parsed1 = JSON.parse(jsonData1);
Here when I directly access the url, it asks for a username and password, which when given shows the value.
But when I do it through an ajax call, it throws this error:
Failed to load resource: the server responded with a status of 401 (Unauthorized)
jquery.min.js:5 XMLHttpRequest cannot load http://10.91.240.21:9898/jolokia/read/* No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 401.
(index):1 Uncaught SyntaxError: Unexpected token u
TRY 2:
var jsonData2 = $.ajax({
type:'GET',
url: 'http://'+domainName+':9898/jolokia/read/*',
dataType:"jsonp",
crossDomain: true,
data: {username: '*',password: '*'},
async: false
}).responseText;
var parsed2 = JSON.parse(jsonData2);
I tried using json p.
The unauthorized code got resolved. It is showing status OK. But now this error comes
Uncaught SyntaxError: Unexpected token u
I think I got the answer. The cross domain issue is resolved.
$(document).ready(function() {
var surl = "http://www.anotherdomain.com/webservice.asmx";
$.ajax({
type: 'GET',
url: surl,
crossDomain: true,
contentType: "application/json; charset=utf-8",
data: { UserID: 1234 },
dataType: "jsonp",
async: false,
cache: false
});
});

Issue sending AJAX request to another domain

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

Categories

Resources