I am having a rather frustrating problem with the jquery post function that probably stems from not understanding how it works correctly.
I have a function that should post some form information to a php script that I wrote and that script then runs curl requests against an API to get around the cross-domain policy of javascript. It seems to work fine as long as it submits to "http" but when I send it to "https" the form never gets submitted.
I ran wireshark on my computer and it showed no traffic towards the destination ip until I made the url use http. I have basic auth on the server so I am passing the user and password through the url, but tested without that there and got the same results.
Here is the not working code:
$j.post("https://<api user>:<password>#<ip>:444/ProxyScript.php",
$j("#spoke_ticket").serialize(),
function(msg) {
log_status(msg);
fade_status();
$j(':input','#createtheticket')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
});
Here is the working function:
$j.post("http://<other ip>/ProxyScript.php",
$j("#spoke_ticket").serialize(),
function(msg) {
log_status(msg);
fade_status();
$j(':input','#createtheticket')
.not(':button, :submit, :reset, :hidden')
.val('')
.removeAttr('checked')
.removeAttr('selected');
});
Any ideas as to why the traffic is not being sent?
Let me know if I left out some key information or anything.
Thanks for the help
If you are doing the AJAX post from a http page to a https URL then the Cross-Domain policy kicks in because the protocol is also part of the origin specification, as it is described here. The browser will refuse to make the AJAX call, so that's why you're not seeing any traffic.
A solution is discussed here:
Ajax using https on an http page
So your best bet is the Access-Control-Allow-Origin header which should be supported on most modern browsers now.
So make your server add the following header to the responses:
Access-Control-Allow-Origin: https://www.mysite.com
If for some reason you cannot enforce this, then the only choice left would be JSONP.
Why not use a proxy to get over the cross-domain issue? It sounds more easy. An simple example is when i want to retrieve the danish administration national geo-data for counties,road names and so on (lucky for me, their data is in json or XML optional)
simplified proxy.php
<?
header('Content-type: application/json');
$url=$_GET['url'];
$html=file_get_contents($url);
echo $html;
?>
in ajax, get the lat/longs for a county borderline
var url= "proxy.php?url=https://geo.oiorest.dk/"+type+"/"+nr+"/graense.json";
$.ajax({
url: url,
dataType: 'json',
success: function (data) {
...
});
notice the https - the url could be, real example, https://geo.oiorest.dk/kommuner/0810/graense.json
Related
So I'm working on Bigcommerce to build a website for a client. since Bigcommerce does not allow the upload of PHP files on their system I'm using AJAX in a script tag in an HTML file. The documentation for the API I'm using says to use my API key in the username field for HTTP Basic Authentication, and that all requests must be transmitted over HTTPS.
So firstly, here's my code
$.ajax({
type: 'POST',
url : "https://www.freightview.com/api/v1.0/rates",
data : ({ myRequest }),
dataType : "jsonp",
Accept: 'application/json',
beforeSend : function(xhr) {
xhr.setRequestHeader("Authorization", "Basic " + "MyKey:");
}
})
I've tried doing
Username : 'mykey'
and some other various ways to put the key in there but keep getting
401 Unauthroized
I've searched around for some ways to do this and noted a few possible issues:
Ajax GET request over HTTPS
It's mentioned on this page that AJAX cannot make cross-domain HTTPS requests. Does this mean I have to find another way to make the request? If so, how can I make such a request with the limitations I have?
Is it simply that I'm not properly defining my username for the Authentication? I'm hoping this is the only problem, but I've looked at a lot of questions on this site about Basic Auth in AJAX.
JQuery Ajax calls with HTTP Basic Authentication The user who asks this question seems to have a similar problem to mine, but the answers are quite varied, and I'm not sure if they'll work in my situation or even how to begin implementing them. Do I need CORS? Can I even get CORS to work on Bigcommerce?
So as you can see what I thought would be a relatively simple snippet of code turned out to be a lot more complex than I thought, and I could really use some of that StackOverflow magic!
Edit: grammar and spelling
In BigCommerce you have to encode your credentials with Base64.
Example:
// Define the string
var string = 'Hello World!';
// Encode the String
var encodedString = btoa(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"
// Decode the String
var decodedString = atob(encodedString);
console.log(decodedString); // Outputs: "Hello World!"
Hi i have the following code
var dataString = "email=jdoe#example.com&fname=John&lname=Doe&phone=7851233&vid=726&size=2&date=2013-05-28%202:15%20PM&request=Testing%20A%20Message";
$.ajax({
type: "GET",
timeout: 5000,
url: "http://www.livepicly.com/app/api.php?method=add_reservation",
data: dataString,
success: function(data, textStatus) {
alert(data.result);
},
error: function(xhr, textStatus, errorThrown){
alert("ERROR");
}
});
return false;
Where basically i would like to submit a piece of string to this URL:
http://www.livepicly.com/app/api.php?method=add_reservation
The formatted string (as displayed by firebug) is like this:
http://www.livepicly.com/app/api.php?method=add_reservation&email=jdoe#example.com&fname=John&lname=Doe&phone=7851233&vid=726&size=2&date=2013-05-28%202:15%20PM&request=Testing%20A%20Message
When the string is executed via browser (straight copy-pasting) it works perfectly. It displayed the corresponding message.
However, when i execute the code, it always returns error. Does anyone know why this happen?
Cheers,
The API in question is not RESTful.
Anyway, your problem is a combination of factors. What it definitely is NOT is the API actually throwing an error, as all errors are returned as 200 status codes. (Not RESTful Point #1). So, even if livepicly returned an error, it'd still count as success on jQuery handlers.
In no particular order:
The API is not throwing Access-Control-Allow-Origin headers. It does not support JSONP either. (This can be seen by querying http://www.livepicly.com/app/api.php?method=add_reservation&callback=test ). This will completely prevent jQuery from loading any data of performing any queries to the API due to cross-domain restrictions
That's the only thing that is failing! This is also completely preventing jQuery usage. You'll need to make a choice to go around this one, which may or may not include:
Proxying the API locally. This is trivial if your webserver is running thanks to Apache or nginx. For Apache, use ProxyPass and ReverseProxyPass directives using mod_proxy, or use a rewrite rule with the [P,L,QSA] set of flags. On nginx, use the proxy_pass directives. If you have access to neither, proxy it using curl through PHP.
Giving the developers of the API a slap in order for them to simply add Access-Control-Allow-Origin: * to the headers, which will make your call work
Giving the developers of the API a slap in order for them to support JSONP
Overall, just point them to https://en.wikipedia.org/wiki/Representational_state_transfer and give them a slap for me. Please?
I trying to do a DELETE, PUT, GET and POST a request with ajax and jquery.
The method POST works well by creating a new record, but I cannot make it work the other methods (PUT, DELETE and GET).
This is the code (it works fine, it creates the new record but it doesn't reach the "success" event):
var jsonExample = {"advertisement":{"title":"test"}};
$.ajax({
type: "POST",
url: "http://example.com/advertisements.json",
data:jsonExample,
success: function(response){
alert("test");
}
});
When I change the type "POST" to "DELETE" or "PUT" I have the follow error:
NetworkError: 404 Not Found
And when I change it to "GET" it throws the following message:
200 OK
But it don't any other responses. It should be something like this:
{"advertisement":{"created_at":"2012-04-17T13:20:17Z","from_age":null,"neighbourhood_id":null,"title":null,"date_to":null,"days":null,"promotion_id":null,"updated_at":"2012-04-17T13:20:17Z","date_from":null,"gender":null,"id":3,"display":null,"desc":null,"budget":null,"image":null,"to_age":null,"department_id":null,"town_id":null}}
The
Please note: my app is getting this info from a remote server, but I don't know if that has something to do with this problem. Because I've run it in Google Chrome and I've received the Access-Control-Allow-Origin message on the browser's console.
Any ideas?
You cannot make cross-domain AJAX requests using jQuery for security reasons. You may however be able to use jsonp providing that the URL you are requesting the data from is set up to handle jsonp requests.
This article should help you out alot more than I'm able to: http://www.fbloggs.com/2010/07/09/how-to-access-cross-domain-data-with-ajax-using-jsonp-jquery-and-php/
I'm using jQuery (1.7.0) to make a json/ajax call to Spotify. The following code works fine in Chrome and Firefox, but causes an error (Error: Access is denied.) in IE.
$.ajax({
url: 'http://ws.spotify.com/lookup/1/.json',
type: 'GET',
dataType: 'json',
cache: true,
data: {
uri: "someartist",
extras: "album"
},
success: successfn,
error:function(xhr, status, errorThrown) {
alert("networking error: "+errorThrown+'\n'+status+'\n'+xhr.statusText);
}
});
The success function is called in Chrome and FF, but the error function is called in IE with the above message. I have set cors to true: jQuery.support.cors = true;.
It works on Chrome and FF both locally and on my server, it works in IE locally but not on the server. Changing cache: false causes problems at the spotify end - doesn't line additional parameters, so I get a "bad request" error.
Grateful for any pointers.
Thanks
Abo
You are relying on the spotify url to give a Access-Control-Allow-Origin:* in their header to allow cross domain requests from all domains. Internet explorer however doesn't support this, so it gives access denied.
access-control-allow-origin explained. (TLDR: Servers may allow cross domain ajax in their headers)
If you need this to work in IE, you could use spotify's JSONP API if they have one or make the AJAX request in flash, which works in all browsers and passes the requests response data to your javascript.
The above answer about using jsonp is correct; I want to add:
Don't set
jquery.support.cors = true;
I'm not sure why so many questions begin by stating they took that step. This property is meant to be read to find out if the browser supports CORS. You should only override it if you know differently, and in my experience it's accurate for all major browsers. Setting it to true doesn't enable the browser to use CORS, it just denies you the info that CORS is going to fail.
http://api.jquery.com/jQuery.support/
can you give an example of returned data?
at a /guess/, it either has something to do with the filename ".json", or the JSON returned has something weird about it.
I'm surprised this works on Chrome or Firefox. You shouldn't be able to run cross-domain JSON requests.
If Spotify API supports it, you should use JSONP in order to access resources from other domains.
Also see: No response from jQuery ajax call
I don't see this working in FF. You can't make cross-domain Ajax calls. So I'm not sure what's going on when you say that it works in FF. But I just tried the following in FF and I got the error. So all you can do is make the call on the server side and then include the results in your page.
http://jsfiddle.net/2XWGn/
I am making an ajax request using JQuery that looks like this:
var data = createXMLdata();
$.ajax({
url: 'http://localhost:8080/foo/bar',
type: "PUT",
data: data,
processData: false,
contentType: "application/text",
error: function(xhr, status, error) {
alert("Error: " + status);
},
success: function() {
alert("Success!");
}
});
When the code executes, I get the success alert, but the service is never executed on the server!
Here's some more data:
If I make the same request using a separate REST client, the service is executed correctly
If I shut down the server (nothing is running) so that hitting that URL gives me a 404, I still get a success message.
I have tried replacing the data with "foo". This works from the REST client, but gives the same result from the code.
Any ideas are greatly appreciated!
The documentation about .ajax()'s type attribute says:
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
So probably your browser does not support PUT and the data is sent via POST instead (and therefore not recognized by your service).
Use Firebug or similar to find out which method is used.
One idea to make it working:
Send the data using POST but add an additional field e.g. __http_method=PUT. On the server side, your service has to recognize this and perform the PUT functionality.
This might be not the nicest solution but it is also used by other frameworks I have encountered (e.g. symfony for PHP).
PUT isn't supported by all browsers
Nick Craver made a comment on my question:
Is the page you're running this in served from port 8080?
It turns out this led to me solving the problem. When both the app and the service were hosted on the same server (and port), the problem went away.
This post suggests that if I comment answers the question, and the commenter does not re-post as an answer, I am to post my own answer and accept it. Nick, if you return to post this as an answer, I will accept it over my own.