We have two domains(xyz.com and zxy.com). and using jquery ajax call to get the data from one domain.
If first one fails, how do i check and redirect to another domain using javascript.
Could you not just use window.location.host to find out which domain the user is currently on?
This way you can make the correct ajax call from the start. There is no reason to make a request to the wrong domain, wait for it to fail then make another request.
If you do however wish to actually make an AJAX request and wait for it to fail then make a different request it would be as follows (this answer is quite verbose on purpose):
var firstRequest = $.ajax({
url: 'http://xyz.com',
timeout: 5000
});
firstRequest.done(function (data) {
});
firstRequest.fail(function () {
var anotherRequest = $.ajax({
url: 'http://xzy.com',
timeout: 5000
});
anotherRequest.done(function (data) {
});
anotherRequest.fail(function () {
});
});
Related
I simply want to know if the request coming in is a standard page load or if the request has come from an ajax request.
Basically, I would like to use the same controller for both my ajax and my normal loading of a page.
Currently I am using:
console.info(req.get('Content-Type')); //undefined.
Here is the node code I am using
getFixtures: function (req, res) {
var passData = {}
console.info(req.get('Content-Type'));
passData.params = req.params;
leagues(app).getLeagues(passData)
.then(filterBarFixtures)
.then(function () {
res.render('games', {
title: 'Fixtures and Results',
passData: passData
})
});
}
app.get('/fixtures/', controllers.getFixtures);
2 way of loading the same controller
Open a browser and navigate to /fixtures
or
$.ajax({
method: "GET",
url: "/fixtures"
})
You would need to either set a header in the client request to look for in the server, or perhaps a search/query parameter
However, as you are using jQuery you don't need to worry
jQuery $.ajax uses XMLHttpRequest, which sets X-Requested-With=XMLHttpRequest request header
Additionally, if the request is for JSON (using $.ajax with appropriate settings or $.getJSON), jQuery usually sets Accept:application/json, text/javascript, etc
note, I've said "usually" to cover my butt in case in some strange browser this doesn't happen :p
Your comment regarding
beforeSend: function(request) { request.setRequestHeader("ajax",true); }
Is probably the safest option, as that header is guaranteed to be present, so that's the header to look for on the server side.
I am trying to get CasperJS to post a form using AJAX - it doesn't seem to work for me, the code is below:
this.then(function() {
response = this.evaluate(function() {
params = $("#offer").serialize();
//require('utils').dump(params);
$.ajax({
type: "POST",
url: 'http://www.example.com/getoffer.php',
data: params,
success: function (data) {
//return data.responseText;
return __utils__.sendAJAX(url, 'POST', params);
},
error: function (xhr,status,error){
return error;
}
});
});
this.echo(response);
});
CORS?
(I'm so tempted to just leave that as my shortest ever StackOverflow answer :-)
Your JavaScript is being executed from inside the browser, and the security model will apply. Your "origin" will be the page that CasperJS is requesting; if that is not "www.mysite.com" (or if it is but is HTTPS), then the browser will refuse to send it.
This answer https://stackoverflow.com/a/16221536/841830 says --web-security=false (give that as a casperjs commandline option) will get around CORS restrictions.
This issue seems to be doing the same as you, so if it is not a CORS problem, it might give you some other ideas: http://code.google.com/p/phantomjs/issues/detail?id=28
Here are the two ways of implementation, that describe the issue.
The first one is the method that works really slow. It tries to get data from server, but the request is pending too long, only after that it returns data and everything's fine (except the terrible synchronous perfomance).
asyncMethod: function(doSmth, param) {
var resp = $.ajax({
type: 'GET',
async: false,
url: 'url'
});
data = resp.responseText;
doSmth(param, data);
}
Here is the same method, but it's asynchronous. The perfomance problem is eliminated here. But it executes the part in success only when page is reloaded. Probably reload stops some executions that were the bottleneck of the previous code sample.
asyncMethod: function(doSmth, param) {
var resp = $.ajax({
type: 'GET',
url: 'url',
success: function () {
data = resp.responseText;
doSmth(param, data);
}
});
}
I don't need to use asynchronous request, if the synchronous one works fast (but now it doesn't). There seem to be some executions, that make the request remain pending for too long. I don't see the execution that may be a bottleneck. Maybe it's somewhere in the libraries that are used, but no other requests are active when resp is being processed.
What are the ways to fix the problem or to analyze it? An advice would be appreciated.
There are two main culprits if a response is sat on "pending" for too long:
The application code that is fulfulling the ajax request is taking longer than expected
Simple network latency (not much that can be done about that in the application layer)
If you have access to the code that is fulfilling the request then I'd start there. Also, it's probably not a network issue if this request is taking an unusually long time compared to all your other requests
Have you tried the async method like this:
asyncMethod: function(doSmth, param) {
$.ajax({
type: 'GET',
url: 'url',
success: function (response, status) {
doSmth(param, response.responseText);
}
});
}
I am calling the web service from other domain using Ajax call and I want to get returned response from server in my application by using following code I get response text in firebug but not in my JavaScript code. Control are not showing success and error response it goes out directly.
I want response in my success or error section but both not handling in this.
I am trying lot but not finding any solution please any one help me.
I am in a trouble. I hope somebody can help me for calling cross domain web service by using Ajax call. I am trying from 1 week but didn't find any solution till. I am getting response on browser but not getting it on my actual code.
My JavaScript code.
crossdomain.async_load_javascript(jquery_path, function () {
$(function () {
crossdomain.ajax({
type: "GET",
url: "http://192.168.15.188/Service/Service.svc/GetMachineInfo?serialNumber="+123,
success: function (txt) {
$('#responseget').html(txt);
alert("hii get");
}
});
crossdomain.ajax({
type: "POST",
url: "http://192.168.15.188/Server/Service.svc/GetEvents/",
// data: "origin=" + escape(origin),
success: function (txt) {
$('#responsepost').html(txt);
alert("hii post");
}
});
});
});
</script>
You can't simply ignore the Same Origin Policy.
There are only three solutions to fetch an answer from a web-service coming from another domain :
do it server-side (on your server)
let the browser think it comes from the same domain by using a proxy on your server
change the web service server, by making it JSONP or (much cleaner today) by adding CORS headers
If I use Ajax to send request and this request take long time ..... if I want to send anther request what should I do?
the current behaviour the second request (I did) waiting until the first request get with response.
NOTE :
i want to do this behaviour on whole application (any new request execute immediately not wait the old one to be finished firstly)
My application using (Ajax + PHP + jQuery + Symfony)
Assume that is the first request take long time:
$.ajax
({
type: "GET",
url: url1,
success: function (html)
{
// do some thing
}
});
In any time I want this request to execute and terminate the first one.
$.ajax
({
type: "POST",
url: url,
success: function (html)
{
// do some thing else
}
});
var xhrReq;
xhrReq = $.ajax(...);
// then if you want to stop the rqest and exit use :
xhrReq.abort();
It’s sort of a manual process, but you can add a global xhr object and test it on each request. If the readystate is "loading", abort it:
var xhr;
var loadUrl = function(url) {
if ( xhr && xhr.readyState > 0 && xhr.readyState < 4 ) {
// there is a request in the pipe, abort
xhr.abort();
}
xhr = $.get(url, function() {
console.log('success', this);
});
};
loadUrl('/ajax/');
The XMLHttpRequest object has an abort function. You can use setTimeout to abort a request that is taking too long.
EDIT: In the case you do not want to use a timer, and a new event occurs that should abort the prior request, then the event handler should do the following
if(!this.request) return; // request contains the XMLHttpRequest
this.request.onreadystatechange = function() {};
if(this.request.readyState != 4) {
this.request.abort();
}
Then after that you can create the new XMLHttpRequest object.
I have been working on this many ways and I feel I found a working solution. I had a caching process that was causing a page to hang until done (average 5 seconds). Yes this is better suited as a CRON job, but I needed to create caching process for the user without knowing the environment they are using for my CMS.
What I had done:
Create the call within a variable and then remove it by a hard delete. By deleting this it seems to be removing the wait. This "hack" seemed to pull the wait from 5 second average to a 325ms wait.
var ignore = $.ajax({
url:something/here.php,
type: "GET",
url: url1,
success: function(){}
});
delete ignore;
Defining the ajax request variable:
var xhr;
Making the ajax call:
xhr = $.ajax(...);
Aborting the ajax call:
xhr.abort();
Browser allows you to handle only limited amount of requests to same host at time (2 or 3 as I remember, depending on browser).
Workaround on requests count is to make fake domains - like img1.domain.com, img2.domain.com, etc. leading to the same host and randomly use them in requests. Then you can just make requests you need. Domains count should be chosen depending on requests quantity in order to keep in bounds - 2 requests per domain. Otherwise 3rd request will wait until one of active finishes.
It allows you to receive responses from all your requests.
For example, Google uses it to make images load faster.
EDIT:
Example: you have http://yourhost.com/ and alias http://alias.yourhost.com which points to the same place.
Then:
$.ajax
({
type: "GET",
url: 'http://yourhost.com/somescript.php',
success: function (html)
{
// do some thing
}
});
and then
$.ajax
({
type: "POST",
url: 'http://alias.yourhost.com/somescript2.php',
success: function (html)
{
// do some thing else
}
});