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.
Related
Following the guide here: https://shopify.dev/tutorials/display-data-on-an-online-store-with-an-application-proxy-app-extension
GET requests are working fine for me.
But when I try to do a POST request, my parameters are not coming through.
I'm building a simple wishlist app, where a user can click on a heart on a product and it adds it to a database.
So my code, when they click the heart, looks something like this:
$.ajax({
url: '/apps/wishlist/save',
type: 'POST',
data: {
shop: shop,
customerId: customerId,
productId: productId
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
When I inspect this post in Network tab in Chrome Dev Tools, the original POST is hitting a 301, then Shopify is creating a GET request to the original URL with different/missing parameters that look like this:
shop: example.myshopify.com
path_prefix: /apps/wishlist
timestamp: 1585769299
signature: examplesignature
If I change my original AJAX request to a GET, then my original parameters are passed as expected.
Are POST requests not allowed here?
Try to add / to the end of your url i.e. change it to /apps/wishlist/save/.
Just to give a clearification.
Vladimir answer works, why?
It seems that Shopify changed their authentication flow for some POSTs request.
You have to send requests without cookies or you can send requests with X-Shopify-Access-Token header and use your app's password for it. They should work both but there are some cases of use that doesn't permit you to send request without cookie or only uses basic auth (depending on wich method and software you use to send request). Shopify's devs are not crazy of course, this was implemented due to avoid some kind of hackers attack based on specific attacking methods, but maybe it should be better clearly specified in their documentation. Even if the solution explained above should be preferred, as said it could not work in some cases so the Vladimir 's solution is a valid alternative (you could also add a dot at the end of the URL so for example: www.example.com./etc/etc), this because this way "blocks" the cookie seending.
You can know more about that following Sopify's community discussion here
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 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
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 want to get xml data from google server using it's API. so, i can't make any changes to response. So, How do I make this call that work for me:
$.ajax({
type: 'POST',
url: 'https://www.google.com/accounts/ClientLogin',
contentType: 'application/x-www-form-urlencoded',
data: { accountType : "HOSTED", Email : ""+Adminemail+"", Passwd : ""+adminpass+"", service : "cp"}, // cp for contact service..
success: function (response) {
alert(response); });
I want make some GET, PUT, DELETE call as well so, I don't want to use any function like $.getJSON();I want to make it possible through $.ajax() only.
I think only way to do this is use of server side scripting language.
Most browsers won't allow cross site scripting. (An ajax call that is not in your own domain).
So if you want to call such an url (https://www.google.com/accounts/ClientLogin), do it server side.
Cross domain posting is blocked by the browser. You could write your own browser. Since this is probably not an option, you could post to your own server and from there post to the other server. I think you can post data to another server using cUrl if you're using PHP.
There's a nice example here.
The third party must provide a jsonp api.