I've a start point zip : 10010
and an array of zips {10011,11015,11008}
Now, I want to find lowest path between start point and arrays zips.
I'm trying google v3 apis for searching. But now successful. Any suggestion ?
I'm using : https://maps.googleapis.com/maps/api/distancematrix/json?origins=10010&destinations=10011|10012&key=AIzaSyBOsjeskUwOLYQZntsv7_34gVZ3xgcXko0
Here is my code:
jQuery(function() {
jQuery("input#search_clinic").click(function() {
var start_point = jQuery("input#zip_code").val();
alert(start_point);
var search_zip = "";
jQuery("select#select_location option").each(function()
{
var option_val = jQuery(this).val();
alert(option_val);
search_zip += option_val + "|";
});
var api_key = "AIzaSyBOsjeskUwOLYQZntsv7_34gVZ3xgcXko0";
var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins="+start_point+"&destinations="+search_zip+"&key=AIzaSyBOsjeskUwOLYQZntsv7_34gVZ3xgcXko0";
jQuery.ajax({
dataType: "json",
url: url,
success: function( data ) {
alert(data);
},
error: function(e) {
}
});
});
});
But return :
XMLHttpRequest cannot load https://maps.googleapis.com/maps/api/distancematrix/json?origins=10010&destinations=44004|44060|&key=AIzaSyBOsjeskUwOLYQZntsv7_34gVZ3xgcXko0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://belsonohearingcenters_two' is therefore not allowed access.
You need to use JSONP instead of JSON in your AJAX.
This is an example:
$.ajax({
url: url,
type: "GET",
dataType: 'jsonp',
cache: false,
success: function(response){
alert(response);
}
});
JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers. (You are not allowed to make AJAX requests to a web page perceived to be on a different server by the browser.) JSON and JSONP behave differently on the client and the server.
Source:
Can anyone explain what JSONP is, in layman terms?
Related
First of all, I have already read this answer, which is to do the Cross-Domain Ajax GET request with php proxy. But what I need is a Ajax POST request.
So in my project, long time ago. Someone wrote this php file and together the ajax call in JavaScript, those are mean to solve the cross origin problem and which works really good! So I never think about to understand this, because I basiclly just need to change the url in the JavaScript and don't need to understand how this Ajax call works together with php.
PHP:
<?php
$nix="";
$type=$_GET['requrl'];
if ($_GET['requrl'] != $nix) {
$file = file_get_contents($_GET['requrl']);
}
elseif ($_POST['requrl'] != $nix) {
$file = file_get_contents($_POST['requrl'], false, $_POST['data']);
}
else {
$file = "false type";
}
echo $file;
?>
JavaScript:
var url = "https://XXXXXXXXXXXXXX";
url = encodeURI(url);
var useProxyPhp = true;
var data = (useProxyPhp) ? {requrl: url} : "";
var ajaxUrl = (useProxyPhp) ? "proxy.php" : url;
var ajaxProperties = {
type: 'GET',
data: data,
url: ajaxUrl,
cache: false
};
res = jQuery.ajax(ajaxProperties).done(function(res) {
// do something with the result here
})
So what I need to do is just take the same ajax GET request (copy and paste in JS) and just replace the url every time ==> job done!
Now, the first time I need to do a ajax POST request to send a xml file to the server, the server will do some calculate on it and give me a response.
I tested first with the POSTMAN and everything works fine, but when I switch to my real project. I become the Cross origin problem. So I think If I could do something to the already existing php and js, so I can solve the cross origin problem.
I tried this in my JavaScript but I got only the "false type" as antwort
function sendWPSRequest(xml) {
var url = "https://XXX.XXX.XXX.XXX:XXXX/wps";
useProxyPhp = true;
var data = (useProxyPhp) ? {requrl: url, data: xml} : "";
var ajaxUrl = (useProxyPhp) ? "proxy.php" : url;
$.ajax({
type: "POST",
url: ajaxUrl,
dataType: "text",
contentType: "application/xml",
data: data,
success:function (response) {
console.log('POST success: ', response);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("POST", textStatus, errorThrown);
}
});
}
Can someone help me a little bit to understand what the php is doing here and what should I do to modify the php and JS.
is it possible to call a page of another website from an ajax call ?
my guess is that is possible since connection is not denied , but i can't figure out how to make my ajax call works , I am calling a list of TV Channels of a website , but I am getting no results , would you please see if my script contains any errors
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl+"&callback=?",
data: "channelType="+all,
type: 'POST',
success: function(data) {
$('#showdata').html(data);
},
error: function(e) {
alert('Error: '+data);
}
});
}
showValues();
html div for results
<div id="showdata" name ="showdata">
</div>
Ajax calls are not valid across different domains.you can use JSONP. JQuery-ajax-cross-domain is a similar question that may give you some insight. Also, you need to ensure thatJSONP has to also be implemented in the domain that you are getting the data from.
Here is an example for jquery ajax(), but you may want to look into $.getJSON():
$.ajax({
url: 'http://yourUrl?callback=?',
dataType: 'jsonp',
success: processJSON
});
Another option is CORS (Cross Origin Resource Sharing), however, this requires that the other server to enable CORS which most likely will not happen in this case.
You can try this :
function showValues(){
var myUrl="http://www.nilesat.com.eg/en/Home/ChannelList";
var all = 1;
$.ajax({
url: myUrl,
data: channelType="+all,
type: 'POST',
success: function (data) {
//do something
},
error: function(e) {
alert('Error: '+e);
}
});
}
I want to call sample service using Ajax. Below is the code i am using.
<script type="text/javascript">
var date1;
var time1;
var time2;
var date2
function CallService() {
date1 = new Date();
time1 = date1.getMilliseconds();
$.ajax({
url: "https://www.google.co.in",
type: "GET",
crossDomain: true,
contentType: "text/xml; charset=\"utf-8\"",
success: OnSuccess,
error: OnError
});
return false;
}
function OnSuccess(data, status) {
alert('success');
}
function OnError(request, status, error) {
alert('error');
}
$(document).ready(function () {
jQuery.support.cors = true;
});
</script>
I know that if we add header('Access-Control-Allow-Origin: *'); in server will remove the issue.
But i don't have access to the server side code so please can some one tell me how can i enable cross domain access in javascript.
Thanks in Advance.
You can use JSONP which stands for “JSON with Padding” and it is a workaround for loading data from different domains. It loads the script into the head of the DOM and thus you can access the information as if it were loaded on your own domain, thus by-passing the cross domain issue
Basic Example : http://jsfiddle.net/yvzSL/714/
Please refer "http://www.sitepoint.com/jsonp-examples/" for more examples
Using the LinkedIn API, I want to get the share count for an URL.
https://www.linkedin.com/countserv/count/share?url=http://www.linkedin.com&format=json
But this gives me an error because of Same-Origin Policy.
I want to use JSONP to then get the data, but I am stuck there.
$.getJSON("https://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=myCallback", function(data) {
elem.find(".count").html(data.count);
});
I still get the Same-Origin Policy error and no data from data.count.
Can anyone help me out? Thanks!
Try
myCallback = function(data) {
// do stuff with `data`
};
var url = "https://www.linkedin.com/countserv/count/share?"
+ "url=https://www.linkedin.com&format=jsonp&callback=myCallback";
$.getScript(url);
See jQuery.getScript()
myCallback = function(data) {
$("body").append("<pre>" + JSON.stringify(data, null, 2) + "</pre>")
};
$.getScript("https://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=myCallback");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Thanks everyone for your answers, but I solved it already myself.
This worked for me:
$.getJSON("http://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=?", function(data) {
elem.find(".count").html(data.count);
});
As of jQuery 1.5.1, this is the recommended way of structuring AJAX requests:
$.ajax({
dataType: "jsonp",
url: "http://www.linkedin.com/countserv/count/share",
data: {
callback: "?",
format: "jsonp",
url: "http://www.example.com/"
}
}).done(function(data) {
console.log(data.count);
});
A few days ago, LinkedIn changed their API and the solutions above are broken :
$.getJSON("http://www.linkedin.com/countserv/count/share?url=https://www.linkedin.com&format=jsonp&callback=?", function(data) {
elem.find(".count").html(data.count);
});
fails because jQuery will replace the ? into a callback with a random name with numbers in it. And Linkedin now prevents using numbers in callback names.
The solution is to use to call "manually" $.ajax to prevent jQuery automation
$.ajax({
dataType: "jsonp",
url: 'https://www.linkedin.com/countserv/count/share',
data: {'url':encodeURIComponent(location.href)},
jsonpCallback: 'this_is_a_random_name',
success: function(data){
elem.find(".count").html(data.count);;
}
});
I Have to do a cross-domain request and fetch content from a url using $.ajax function.
But the below code only displays the first alert i.e alert(myUrl),
After that the execution stops.The second alert is not displayed. I don't know what is wrong with the code i have written.
Can somebody tell me what i am doing wrong here?Thanks in advance.
function getContentFromUrl(){
var myUrl="http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" +
"q=select%20*%20from%20html%20where%20url%3D%22" +
encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
success: function () {
alert("***********"+data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function() {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
});
}
Same Origin Policy:
The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.
You can't use regular JSON for cross-domain requests because of the same-origin policy. Instead, you'll need to use JSONP. In jQuery, you can do so like this:
$.ajax({
dataType: 'jsonp',
crossDomain: true
// other info
});
Note that there are security issues involved with JSONP. Only use JSONP if you trust the host domain.
I assume this is jQuery?
Try the following:
url = "http://query.yahooapis.com/v1/public/yql?" +"q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?";
getContentFromURL(url);
function getContentFromURL(url)
{
$.get(url, function (data) {
console.log(data);
});
}
If it dumps out to the console a response, you can build from there.
The data here is not defined
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
and you forget to add a param for the callback function
success: function (data) {
....
}
The finally code should like this
function getContentFromUrl() {
var myUrl = "http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: {},
success: function (data) {
alert("***********" + data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function () { document.getElementById("displayerrors").innerHTML = "Could not load the page."; }
});
}