Ajax call keeps getting blocked by browser - javascript

I am a bit stuck with an issue.
I am developing a small mobile website. I am trying to call a webservice using an ajax call, but the browser keeps blocking my call. If I start up Chrome using the tags... "--allow-file-access-from-files --disable-web-security​​" Then the call works perfectly. I have no issues whatsoever.
Now my problem is if I host the website, the browser is going to block my ajax call and the user cannot for example login or retrieve information. I present my ajax call below...
$.ajax({
async: true,
beforeSend: function () {
},
complete: function () { },
type: 'POST',
url: 'https://MySecretUrl.com/login?format=json',
contentType: 'application/json',
dataType: 'json',
data: '{"UserId":"mySecretUserId","Password":"mysecretPassowrd"}',
success: function (resultMessage) {
if (resultMessage.WasSuccessful == true) {
alert('YAY');
} else {
alert('Semi Yay');
}
},
error: alert('OOOOPS')
});
Does anybody know a workaround for getting information from the webservice without any browser blocking the ajax call ?
Any suggestions would be greatly appreciated.
Thanks in advance for the help.
EDIT
Hi Guys, Ok so I did some more digging and discovered the following.
When the request is made with browser security, the call changes the POST to a OPTIONS. this is called a preflighted request. One workaround that I have found is if you are making a GET call, then you can use jsonp as your data type. But now my problem is that it is incompatible with POST. Is there any fix that does not require the webservice to be changed ?

Is there any fix that does not require the webservice to be changed ?
No. If changing the webservice isn't an option, your only option is to not use the browser to make this request.
You must either make the server return the data in a format that can be accepted cross-domain, or don't make cross-domain requests with the browser.

Related

jQuery AJAX request to remote API blocked

I have been successfully accessing data from an external weather data service API for some time now using PHP cURL. Sometimes it takes a few seconds, sometimes up to 15 seconds for this web service to process my request. Therefore, I would like to perform this operation asynchronously.
I am trying jQuery AJAX to send this GET request now. However, it keeps throwing the following error:
"No Access-Control-Allow-Origin header is present on the requested resource".
I'm aware of the "same origin policy" restrictions, and have been researching it extensively here on stackoverflow and the jQuery docs. The docs say that JSONP requests are not subject to this restriction. When I try to designate JSONP as the dataType, I get an "unexpected token" syntax error.
I have the user entering in their zip code into a form text box, then click the button to submit. This sends the GET request to the web service. I'm very comfortable with PHP, but a newbie with jQuery and AJAX. I appreciate the help with this, and look forward to the day when I can help others as I've been helped here.
Here is the jQuery code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"> </script>
<script type="text/javascript">
$(document).ready(function () {
$('#btnGetETo').click(function () {
var resultElement = $('#resultDiv');
var requestData = $('#txtZip').val();
$.ajax({
url: 'http://et.water.ca.gov/api/data?appKey=B51CF64B-C37B-406A-83F1-1DBD8CE40EEF&targets=94805&startDate=2015-07-01&endDate=2015-07-01&dataItems=day-asce-eto,day-eto,day-precip&unitOfMeasure=E;prioritizeSCS=Y',
method: 'get',
data: { q: requestData },
dataType: 'json',
success: function (response) {
if (response.message != null) {
resultElement.html(response.message);
}
else {
resultElement.html('ETo: ' + response.DayAsceEto[0].value);
}
},
error: function (err) {
alert(err);
}
});
});
});
</script>
Unfortunately, it seems that the API in question does not support JSONP. In fact, they seem to have gone out of their way to make it difficult to query via JavaScript.
Here's how to test for JSONP (not foolproof, but most mainstream JSONP-enabled services will respond correctly). Take whatever URL you were planning to send, and add &callback=foo to the end of it. (If there are no other query string parameters of course, use ? instead of &.)
If the server supports JSONP, the response should look like:
foo({
...
});
If not, it'll look like:
{
...
}
As you can see, the only difference is that JSONP-enabled servers can wrap the JSON in a function of arbitrary name. Some servers will insert a little extra code for safety/convenience. For example, the following output was generated by the JSONplaceholder API using the URL http://jsonplaceholder.typicode.com/users/1?callback=foo:
/**/ typeof foo === 'function' && foo({
"id": 1,
"name": "Leanne Graham"
...
});
The upshot of all this is that it's the API provider's fault, not yours. If I were giving them feedback I'd make the following suggestions:
Handle cross-origin requests correctly.
Allow fallback to JSONP.

execute a PHP script from Ajax without expecting an answer (and no daemons)

I hope you can help me with this issue:
My sistem runs over Zend Framework, I have installed jQuery in it's latest version. I have an input that receives a file and it makes an Ajax call when changes, and I want that call made in the background, without expecting any response (because that script will send an email when finished). My ajax call is like this:
var formData = new FormData();
formData.append('file', $(this).get(0).files[0]);
$.ajax({
url: 'uploadaddresses.php',
type: 'POST',
data: formData,
dataType: 'json',
async:true,
processData: false,
contentType: false,
beforeSend: function(){
bootbox.alert("You've made your petition correctly. When finished, an email will be sent to you.")
},
error: function(err) {}
});
return false;
Although, the call waits for a response (even FireBug shows me that uploadaddresses.php is still executing...). What i'm doing wrong? How should I do it best? I want to avoid using daemons and system calls, because system restrictions...
Thank you very much in advance :)
If you're wanting uploadaddresses.php to return an HTTP response immediately but continue processing, take a look at pcntl_fork in PHP.
Here's the main doc page: http://php.net/manual/en/function.pcntl-fork.php
Here's a good example that you might want to follow: http://php.net/manual/en/function.pcntl-fork.php#94338
Create a success method for the ajax call and have something like this:
console.log("Done");
This way you know if is complete and successful but only if you are looking at the dev tools. Unless you specify output it should not continue to run after the call has been made. Maybe you have an error in your PHP code?
EDIT: If you can't get this resolved you may want to post your PHP page as well.

Cannot get JSON data from URL

Apologies for asking what looks like a frequently asked question but I cannot seem to be able to get the data from the following URL: http://www.strava.com/stream/segments/860503
I have tried the following:
$(document).ready(function() {
$.ajax({
url: "http://www.strava.com/stream/segments/860503&callback=?",
dataType: "json",
success: function(data) {
$(document.body).append(data.latlng);
}
});
});
And:
$(document).ready(function() {
$.getJSON("http://www.strava.com/stream/segments/860503&callback=?", function(data) {
$(document.body).append(data.latlng);
});
)};
But I am not having any luck. I have fiddled around with 'json' and 'jsonp', adding the '&callback=?' to the URL as well as other things suggested on SO, but to no avail.
Any help is greatly appreciated.
That particular URL does not support JSONP. Neither does it provide support for Cross Origin Resource Sharing (CORS) via the Access-Control-Allow-Origin response header, therefore it is impossible to directly call it via ajax.
The requirement for JSONP support is that the server must output the callback name as a function, passing the JSON as a JavaScript object or array in the argument to the function. For example:
myCallback({ ...... });
A possible solution is to proxy the ajax request through a server side script on the same domain, where cross origin is not a problem for server to server requests.
the data from "http://www.strava.com/stream/segments/860503" has no callback. it is not made for cross-domain. if your script is on the same server use:you have acces to the php of the server use echo $_GET['callback'].'('.json_encode($return) .')';
else try to use [php] cURL;
please watch This Side Example I think usefull for you
http://demos.jquerymobile.com/1.0a2/experiments/api-viewer/docs/jQuery.getJSON/index.html
have you tried ? The difference being the cb instead of ? at the end of the URL.
$(document).ready(function() {
$.getJSON("http://www.strava.com/stream/segments/860503?callback=cb", function(data) {
$(document.body).append(data.latlng);
});
)};

Issue with jQuery ajax post

This is a followup to this question. Since the problem that I'm now facing is different from that, I thought I'll pose a new question.
I'm having an issue with the following code where in, the request is getting POSTed to the server, but whatever response the server has sent is not visible on the browser (in the form of an alert here).
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#login').delegate('input#submit','click',function(){
var request = $.ajax({
type: "POST",
url: "login",
data: {userid: $("#userid").val(), password:$("#password").val()},
datatype: "xml",
cache: false,
success: function(xml){alert(xml);}
});
});
});
</script>
I can see that this request is going to the server - can see it in the logs. But I don't see the server's response in the browser. Here's the server's response:
<result><url>landing-page</url></result>
Not sure what am I doing wrong, but this seems to be simple stuff that I should get it working without issue. Tried Firebug, but no luck. Any idea as to where am I going wrong here or on how to debug this issue further.
Thanks
Either change your "success" callback to a "complete" callback, or add a complete callback. My guess is that it isn't detecting a "success" even though the response is being successfully retrieved. If it fires the "complete" callback, then you can try and fix your webservice to provide a successful response.

Getting 'data is null' on a Twitter API call but displays data in browser

I'm trying to display the follow count of a twitter account, but when I hook into the API using this code:
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true", function(data) {
console.log(data);
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
I get a 200 ok report but with Data is null message.
But if I download the json file to my local machine and change the getJSON call accordingly, it works straight away.
Has anyone got any ideas on what could be causing this?
Thanks
Also just to add, if I put the Twitter API url into my browser it displays all the data, which makes it even weirder.
Maybe the problem lies with jsonP, since you are calling a remote server and you must specify you should use jsonP. Have you tried adding callback=? as a parameter
$.getJSON("https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true&callback=?", function(data) {
if (!data.error) {
$("#followers").html(data.followers_count);
}
});
Taken from jQuery docs
JSONP
If the URL includes the string "callback=?" (or similar, as
defined by the server-side API), the request is treated as JSONP
instead. See the discussion of the jsonp data type in $.ajax() for
more details.
$.ajax({
url: 'https://api.twitter.com/1/users/show.json?screen_name=uswitchTech&include_entities=true',
dataType: 'jsonp',
success: function(data){
console.log(data.followers_count);
}
});

Categories