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);
}
});
}
Related
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?
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 need to redirect to a page from response. I made a ajax call and can handle success. There is html page in response, but how to redirect it to that page.
Here's my code.
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = response;
}
});
});
Not using ajax would make this easier:
<form type="POST" action="xyz.json">
<label for="id">Enter ID:</label><input id="id" name="id">
<button type="submit" id="launchId">Send</button>
</form>
If you really want to use ajax, you should generate a distinct server response, containing only the HTML parts you want to update in your page or actual JSON.
If you insist on using the response which you currently get, the appropriate way of dealing with it would be document.write:
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'html', // it's no JSON response!
success: function(response) {
document.write(response); // overwrite current document
},
error: function(err) {
alert(err+" did happen, please retry");
}
});
Please try this.
var newDoc = document.open("text/html", "replace");
newDoc.write(response.responseText);
newDoc.close();
Your response is an object containing the full HTML for a page in the responseText property.
You can probably do $(body).html(response.responseText); instead of window.location.href = ...; to overwrite the current page content with what you got a response.
...
complete : function(response) {
$(body).html(response.responseText);
}
But i suggest you don't and there could be style and other conflicts with whats already there on the page.
In your HTML add a div with id as 'content', something like this
<div id='content'/>
Since your response is html in your complete function append the content into the div like this -
complete : function(response) {
$('#content').append(response.responseText);
}
Let me know if you still face issues.
try this
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = '/yourlocation?'+response;
}
});
});
This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
jQuery AJAX seems to be sending two requests. As I'm using a two-factor authentication method, based on time, the second request is failing hence the original request is "failing".
The first is a post request, that's fine, but then there's a GET request, which isn't fine.
Here's the javascript I'm using to generate the query.
$('#form').live('submit', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel3';
$.ajax({
type: "POST",
url: url,
data: $('#form').serialize(),
dataType: 'json',
success: function(data, status) {
$.getJSON(url, function(data) {
if (!data.resultCode) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
} else {
location.reload();
}
});
}
});
event.preventDefault();
});
Any ideas how I can work around this?
That is because you are doing 2 ajax calls (.ajax and .getJSON)
Try doing this instead (using document event delegation instead of .live):
$(document).on('submit', '#form', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel3';
$.ajax({
type: "POST",
url: url,
data: $('#form').serialize(),
dataType: 'json',
success: function(data, status) {
if (!data.resultCode) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
} else {
location.reload();
}
}
});
event.preventDefault();
});
You are sending 2 requests. One with .ajax and another with .getJson.
Remove the .getJson request. With no dataType property passed to .ajax, jquery will attempt to guess the response type. You may also specify the dataType as json to force the conversion. The 'data' parameter of the success callback should be converted to a javascript object for both of these options.
getJSON is an AJAX method for retrieving JSON from a server, not for processing the data returned by another ajax method. Just remove it.
$('#form').live('submit', function(event) {
var target = $('#ajax');
var url = '/ajax/user/authenticateLevel3';
$.ajax({
type: "POST",
url: url,
data: $('#form').serialize(),
dataType: 'json',
success: function(data, status) {
if (!data.resultCode) {
$('#ajax').html($.base64.decode(data.html));
$('#ajax').modal();
} else {
location.reload();
}
}
});
event.preventDefault();
});
Since you mentioned you are switching over to .on, the syntax will be like this:
$(parent).on('submit', '#form', function(event) {
/*
* ...
*/
});
where parent is the nearest static parent element of #form.
I am trying out JQuery Ajax methods. I wrote a simple Ajax request to fetch certain 'tagged' photos from Flickr. Following is the snippet I am using:
function startSearch() {
$(function() {
var tagValue = $("#tagInput").attr("value");
alert(tagValue);
$.ajax({
url: "http://api.flickr.com/services/feeds/photos_public.gne?tags=" + tagValue + "&tagmode=any&format=json&jsoncallback",
dataType: 'json',
async: false,
success: function(data) {
alert("Success");
$.each(data.items, function(i, item) {
var pic = item.media.m;
$("<img/>").attr("src", pic).appendTo("#images");
});
},
error: function(data, error) {
alert("Error " + error);
}
}); });
'startSearch' is associated with a Search button. User is supposed to input a 'tag' to search and on click this function gets called.
Problem is that I am not receiving any 'data' in response. Hence no images gets displayed.
What am I doing wrong here?
Thanks & Regards,
Keya
I think the problem is that you're trying to make a cross-site request, which doesn't work because of security concern. You could use JSONP instead, e.g. as described in http://www.viget.com/inspire/pulling-your-flickr-feed-with-jquery/
You can also try searching for "cross site ajax" on this site, there's plenty of discussion about it.