How to get/post/delete/put information with jQuery and AJAX - ajax

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/

Related

Ajax in Phonegap not working

I know this question has been address many times on Stack Overflow, but none of the solutions are working for me.
I can't get ANY ajax requests to complete within my phonegap application when running on the device (Android 4.4.2), yet everything works fine from desktop browsers.
First I tried AngularJS $http
Then I tried jQuery .get
Then I tried raw xhr
In all cases, the request immediately fails with no response. I've tried requesting data from my own servers, and from google servers, and elsewhere, all the same. I've tried whitelisting my domains in config.xml, in many forms, still no effect. I've even opened the console, and manually created an XHR and tried to GET on it, and the same thing happens. The request immediately fails. If anyone can please help me out, that would be great. I'm on the latest version of pretty much all my software, having set up my dev environment just today.
Cross domain request headaches. The browser allows the cross domain request but phonegap on the device kills it. I've been there and it took some work getting used to dealing with it. Try using jquery and jsonp in an ajax get request.
Try adding <access origin="*" /> to your config.xml for testing.
Here's an example of an jquery ajax request taken from working code.
$.ajax({
timeout: 5000,
url: 'https://yourdomain.com/yourfile.php',
dataType: "jsonp",
jsonpCallback: 'yourcallbackfunction',
type: "GET",
crossDomain: true,
data: {'somedata':'your data string'},
error: function(xhrObj,text,errorObj){
if(xhrObj.status !== 200) {
var errorTxt='Error Log: ';
errorTxt=errorTxt+"Error code specific:'"+xhrObj.status+"'\n";
errorTxt=errorTxt+"Error status specific:'"+xhrObj.statusText+"'\n";
errorTxt=errorTxt+"Error code general:'"+text+"'\n";
errorTxt=errorTxt+"Error status general:'"+errorObj.message+"'\n";
console.log(errorTxt);
}
}
});
function yourcallbackfunction(data) {
// do cool stuff here
console.log(data);
}
Be sure to handle the headers on your servers response so that the response gets back to your client. Here's a sample processing function I used to return data. Sorry if php isn't your server side scripting language but hopefully you'll get the idea.
`function SendResults($data) {
// Allow from any origin
if (isset($_SERVER['HTTP_ORIGIN'])) {
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers: {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
}
header("content-type: application/json");
$callback = filter_input(INPUT_GET, 'callback', FILTER_SANITIZE_SPECIAL_CHARS);
echo "$callback(" . json_encode($data) . ")";
}`
Good luck.. Hope this helps you.

AJAX post not working with HTTPS

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

jQuery and Ajax with json - fails in IE

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/

AJAX/JSONP Question. Access id denied using IE while requesting corss domain

Ok, Here we go. I have already searched the Stack for the answer i have found some useful info but i want to clear up some more things. I also search the net for the answer but no real help.
I have worked with some api (yelp, ouside.in). In yelp i use to inject the script to head with the url request to the api with a callback funcion. I worked fine in all browsers. But while using outside.in api when i call the url the callback in not working.
In yelp they have a url field can be used like that callback=callbackfuncion so the callback will automatically called.
But in outside.in there is not such field available. Is there are any standard command for callback function which will work regardless of any server/api?
I also tried a standard ajax request using jQuery $.ajax() function. It worked for my local pc for both IE and other browser but did not working in IE showing the error: access denied, other borwser seems ok. Firebug in my FF also don't notice any errors.
Outside.in has an javascript example but it is too hard to me to understand
github.com/outsidein/api-examples/tree/master/javascript/browser/
site i am working: http://citystir.com
yelp: yelp.com
outside.in: outside.in
Techniqual info:
i am using: wampserver in local, wordpress for hosting, Godaddy, apache for remote with linux.
Codes:
Using Jquery $.ajax
url is like: "http://hyperlocal-api.outside.in/v1.1/states/Illinois/cities/chicago/stories?dev_key="+key+"&sig="+signeture+"&limit=3
function makeOutsideRequest(url){
$.ajax({
url: url, dataType: 'json', type: 'GET',
success: function (data, status, xhr) {
if (data == null) {
alert("An error occurred connecting to " + url +
". Please ensure that the server is running and configured to allow cross-origin requests.");
}else{
printHomeNews(data);
}
},
error: function (xhr, status, error) {
alert("An error occurred - check the server log for a stack trace.");
}
});
}
Thanks!
This question was asked in the Outside.in developer forums this morning as well (presumably by the same person). Here's a link to that discussion: http://developers.outside.in/forum/read/97053
To summarize, the Outside.in API does not support JSONP, but CORS support is included in the next release of the API, which will hit in the near future.

JQuery .ajax request does not hit the server

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.

Resources