I m trying to convert the following code to another AJAX call, in order to not have cross-domain problems!
This is my original code:
<script>
$(document).ready(function() {
$("#os").load('http://www.a.gr/os #livesos');
var refreshId = setInterval(function() {
$("#os").load('http://www.a.gr/os #livesos');
}, 60000);
$.ajaxSetup({ cache: false });
});
</script>
And here is a sample code for what i want to do, but i dont know how...
$.ajax({
type: "GET",
cache: false,
url: 'http://www.a.gr/os',
dataType: "???",
.
.
.
.
});
Can someone help me please?
Your best bet to avoid cross-domain issues is to have the phone call your server, and the server can call the other servers to get the data needed.
There are a couple of benefits to this, one being that you can cache recent calls, if it doesn't change often, and more quickly send it back to the client.
Also, if you want to later change the url or make additional calls to return richer data, you can do that without affecting the client.
Related
In my project, I have a long-running process which is called by AJAX. Duration can be 1 to 15 mins.
While AJAX is running, I want to give updates to users. It just should show simply how many rows left to add into the database.
I found out that there are a few different options to realize this. Polling, SSE or WebSockets. I never worked with WebSockets, and I couldn't find a good example.
I'm trying now with SSE which I quite understand, and it is working properly.. but when the AJAX start running the connection to the eventSource will be pending. So while AJAX is running, there are no updates received.
Code:
<script type="text/javascript">
var es;
function checkProgress(id){
es = new EventSource('checkProgress.php');
es.addEventListener('message', function(e) {
console.log(e.data);
}, false);
}
checkProgress(1);
$(function() {
$('.submit').on('click', function() {
var form = $('form')[0];
var form_data = new FormData(form);
$.ajax({
type: 'POST',
url: 'submit.php',
contentType: false,
processData: false,
data: form_data,
success:function(response) {
console.log(response);
}
});
return false;
});
});
</script>
Screenshots:
Network log
Now actually I still didn't find any reference or example of how to implement SSE while there is an AJAX process running. All reference or examples give examples to let the getProgress file to do something.
I see you're using PHP. My best guess would be that you're also using the built-in PHP session management. The problem with this is that accessing the session is an exclusive operation. I would guess that your AJAX operation has opened and locked the session, preventing your SSE script from also opening the session. You might consider not opening the session or opening it read-only(Dead Link) (Archived).
Im new to ajax. I was trying to find the answer but was not lucky to find the corresponsing one. Basically I need to use an ajax to get some data and after that to put this data to the variable that later will be used as an attribute for the callback function with custom code.
This ajax part is just a method of myObject.
So, in the end I need this kind of functionality:
myObject.getData(url, callback(data) {
//my custom code of what I wanna do after ajax is complete
});
My code
/*
HERE COME SOME PROPERTIES AND OTHER METHODS WICH IS NOT THE CASE
*/
//This is where Im stuck
var getData = function getFromUrl($url) {
$.ajax({
type: 'get',
url: $url,
dataType: 'html',
success: function(html) {
$obj = html;//Im lost on this step!
},
});
};
P.S. Im trying to find an async way (without using async:false). Hope its possible
First I encountered many problems. My first problem was No Access-Control-Allow-Origin, most websites dont allow you to just scrap get their data for security reasons. Luckily someone already made a proxy: http://cors.io/ . Second problem is that you cant embed http on https, so I cant use jsfiddle to show you this working, it works on my local enviroment. After you get the raw html you have to parse it, you can do it with full regex, or you can power yourself with jquery like I'm doing on this example. What we're doing is checking stackoverflow.com and getting the amount of featured questions with .find(".bounty-indicator-tab").first().html(); But once you have the full html you can get any data you need.
var getData = function getFromUrl(url) {
$.ajax({
url: 'http://cors.io/?' + url,
crossDomain: true,
dataType: 'html',
success: function (html) {
var match = $(html).find(".bounty-indicator-tab").first().html();
console.log(match);
return match;
},
error: function(e) {
console.log('Error: '+e);
}
});
};
url = 'http://stackoverflow.com/';
data = getData(url);
//You cant use data yet because its working async
I have two Ajax requests that I am wanting to combine together into one. I'm having trouble figuring how to do this as one is using $.ajax() and another is using $.get().
As I'm fairly new to Ajax, this is causing me much pain. If you could help, it would me much appreciated.
Ajax Request #1
$.ajax
({
type: "GET",
url: "new_arrivals_data.php",
data: "page="+page,
success: function(msg)
{
$("#gallery_container").ajaxComplete(function(event, request, settings)
{
gallery_show();
loading_hide();
$("#gallery_container").html(msg);
});
}
});
Ajax Request #2
$.get("new_arrivals_data.php",{imgs: value}, function(data){
$("#gallery_container").html(data);
});
Thanks for any help you can offer.
They are actually both GETs $.get is short hand for $.ajax({ type:'GET'.
So combining them might work depending on your server's response:
$.ajax
({
type: "GET",
url: "new_arrivals_data.php",
data: {page:page, imgs: value},
success: function(msg)
{
gallery_show();
loading_hide();
$("#gallery_container").html(msg);
}
});
Not sure what you're looking for, but Ajax Request #2 is equivalent to:
$.ajax({
type: 'GET',
url: "get_images.php",
data: {imgs: value},
success: function(data){
$("#imgTray").html(data);
}
});
Hope this helps.
You can't just 'combine' requests - you'll still need to make two separate requests to each of these URLs. Since by default, ajax requests are asynchronous, you can fire them both almost simultaneously (if one doesn't depend on the other. As marko points out in the comments, if they are dependent, you could force the requests to be synchronous. $.ajax has an async property.).
if(condition){
makeRequest1();
makeRequest2();
}
Also $.get() is simply a convenience method for $.ajax() with certain options preset (such as using GET as the request type).
I'm trying to use AJAX to send a query to Google Books and display the results on my website. I'm using JQuery to send the request and handling the response, like so:
var query = [formatted input from a form];
var URL = "http://books.google.com/books/feeds/volumes?q="+query+"&start-index=1&max-results=5";
$.ajax({
type: "GET",
url: URL,
dataType: "xml",
success: function(data, status){
alert(status);
}
});
Currently, I just have the script alerting "success" if a response is received. If I use my script to send that query to a local page for testing, this works just fine. But when I set the URL to the Google one listed above, as instructed on the Developer API page, I never see the alert. According to Firebug, I am receiving a response and a status of 200 ok as I should, but it's not getting to that "success" path. Does anyone know why?
Edit: I should add that if I follow the URL directly, to http://books.google.com etc. with some random q, it displays the feed XML with no problems, so the query is not the issue.
You can't make cross-domain requests using XMLHttpRequest under the standard browser security settings. One possible solution is to write a local proxy function (assuming you can create server-side code) that forwards the query to the external site, and then returns the response.
Edit: It looks like Google provides a JavaScript API as well. I would assume that they've crafted in such a way to avoid the cross-domain XHR issue.
http://code.google.com/apis/books/docs/js/devguide.html#execute
Edit: The JavaScript API for books was deprecated. While it's no longer practically useful, you can see the original referenced documentation text via the Wayback Machine archive: http://web.archive.org/web/20120414070427/http://code.google.com/apis/books/docs/js/devguide.html#execute
It's a cross-domain problem with ajax calls because browsers have a security model based on a domain policy.
if you don't wan to include the whole Google Books API, you can also use Google Ajax API with jsonp for cross-domain ajax calls.
Docs here:
http://code.google.com/apis/books/docs/js/jsondevguide.html#basic_query
jQuery example
var query = 'jquery';
var URL = 'https://ajax.googleapis.com/ajax/services/search/books?v=1.0&q=' + query;
$.ajax({
type: 'GET',
url: URL,
dataType: 'jsonp',
success: function( data, status ){
alert( data.responseData.results.length + ' results found!' );
},
error: function() {
alert( 'Something goes wrong!' );
}
});
Ciao!
$(document).ready(function() {
$('#content').html('');
$.ajax({
url:'data.json',
dataType: "json",
success: function(data) {
$('#content').append('<p>'+data.rank+'</p>');
}
});});
In this code (it works) data.json contains the JSON data in this format:
{
"user_id":"3190399",
"user_name":"Anand_Dasgupta",
"followers_current":"86",
"date_updated":"2009-06-04",
"url":"",
"avatar":"205659924\/DSC09920_normal.JPG",
"follow_days":"0","started_followers":"86",
"growth_since":0,
"average_growth":"0",
"tomorrow":"86",
"next_month":"86",
"followers_yesterday":"86",
"rank":176184,
"followers_2w_ago":null,
"growth_since_2w":86,
"average_growth_2w":"6",
"tomorrow_2w":"92",
"next_month_2w":"266",
"followersperdate":[]
}
This data comes from the URL:
http://twittercounter.com/api/?username=Anand_Dasgupta&output=json&results=3
(Click the URL to get the data)
But when I replace data.json in the $.ajax function with the URL which contains the same data, this code below doesn't seem to work...
$(document).ready(function() {
$('#content').html('');
$.ajax({
url:'http://twittercounter.com/api/username=Anand_Dasgupta&output=json&results=3',
dataType: "json",
success: function(data) {
$('#content').append('<p>'+data.rank+'</p>');
}
});});
Any help with the problem will be highly appreciated.
Thanks in anticipation,
Anand
The thing is that you are trying to access an url on a different domain (unless you actually are on twittercounter.com of cause). Anyways, if you want to do cross-site AJAXcalls which browsers don't permit due to safety, you have to use the JSONP "trick". You can use JSONP with jQuery, which it seems like you are using. Last I checked though, jQuery required some server side configuration, so unless you can alter the data you get, you would have to do the AJAX request manually, in which case you would be able to get it, using the JSONP method.
Basically you are trying to access a cross-domain AJAX request. This is not allowed because it tends to compromise browser security. Here is a way that you can get around it:
http://code.google.com/p/cross-domain-ajax/
Noah
Edit: Mon Jun 29 10:24:51 CDT 2009 googletorp FTW!