Not able to send POST request through jQuery Ajax - ajax

I was trying to send an ajax request as POST request. But when i verified it on httpFox on firefox, the request is sent as GET. I tried both $.ajax() and $.post().
Many had a query regarding the same and had missed the "type" in $.ajax(), but even if i mention the type as "POST", the request will be of type GET.
Here is my code:
$('.test').click(function(){
alert("clicked");
$.ajax({
type: "POST",
url: "www.testsite.com",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
});
Any idea why it happens?

A possible cause might be the fact that you are trying to send an AJAX request to a different domain: www.testsite.com than the one hosting your page which of course is not possible and jQuery tries to use JSONP instead which works only with HTTP GET.

Related

jQuery Cross Domain Request to get JSON Response without Callback

I am trying to retrieve a JSON from this URL
http://www.iheartquotes.com/api/v1/random?format=json
via jQuery. I know the solution is JSONP, but since I have no control over the response text of the service or to wrap it in my own callback function, my aim is to somehow retrieve the response of the above URL using client-end scripts.
I have tried almost all the methods suggested from several answers from StackOverflow.
These are the code blocks I have tried and the response's I've got.
1 . A direct call which returned the expected Access-Control-Allow-Origin error
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json",
function(data) {
alert(data);
});
Response:
XMLHttpRequest cannot load
=1376682146029">http://www.iheartquotes.com/api/v1/random?format=json&=1376682146029.
Origin http://stackoverflow.com is not allowed by
Access-Control-Allow-Origin.
2 . The above code with the callback parameter added:
$.getJSON("http://www.iheartquotes.com/api/v1/random?format=json&callback=?",
function(data) {
alert(data);
});
Response:
Uncaught SyntaxError: Unexpected token :
Please note that when I click on the error, it takes me to the expected JSON response.
{"json_class":"Fortune","tags":["simpsons_homer"],"quote":"Holy Moly! The bastard's rich!\n\n\t\t-- Homer Simpson\n\t\t Oh Brother, Where Art Thou?","link":"http://iheartquotes.com/fortune/show/5501","source":"simpsons_homer"}
This is also expected as there is no callback function defined in the response.
3 . Through jQuery's Ajax method
$.ajax({
type: "GET",
dataType: "jsonp",
url: "http://www.iheartquotes.com/api/v1/random?format=json",
success: function(data){
alert(data);
},
});
Response:
Uncaught SyntaxError: Unexpected token :
Adding the callback parameter to the above function doesn't change the response.
Any help or pointers from the experts to retrieve the JSON from the URL? I am testing this from the Chrome Dev Tools. I know I could call the service from the server-end code and then send it across to the client-end. But I want to see if this can be done through jQuery alone from the client-end.
EDIT:
Based on Kevin B's comment:
Got the expected output via YQL using jQuery's Ajax. But my question remains the same. Is there a native way to do it via jQuery as YQL is still a dependency?
// Using YQL and JSONP
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql",
// the name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// tell jQuery we're expecting JSONP
dataType: "jsonp",
// tell YQL what we want and that we want JSON
data: {
q: "select * from json where url=\"http://www.iheartquotes.com/api/v1/random?format=json\"",
format: "json"
},
// work with the response
success: function( response ) {
console.log( response.query.results.json ); // server response
}
});
This gives the expected response.
This won't work in all browsers, but depending on which version of JQuery you're using try:
$.support.cors = true;
Obviously this also depends on the headers of the server response.

Cross domain Ajax call from HTML page (can't use any proxy)

I was trying to get some information from another server using ajax post call as .
$.ajax({
type: 'POST',
url: testURL,
data: data,
//dataType: 'jsonp',
dataType: "script",
success: function (data) {
alert("Successfully posted (Test) : " + data);
},
error: function (ts) {
alert("Inside Error : " + ts.responseText);
}
});
Here testURL is the URL where i am posting the data (Cross domain requests are only possible if datatype is either jsonp or script), and it suppose to return text/html data back (what fiddler says will be the return type for the data).
I am not sure if i can use any proxy as pages are normal HTML pages.
Isn't there any way to get the [data] as text (as for now success expecting JASONP data and alert("Successfully posted (Test) : " + data); only showing data as undefined). I can't make any changes to API or whatever it is on the remote Server.
Thanks for the help in advance.
Regards
Without a proxy you cannot do it. If that is in a windows box, you can create a COM object to make the call to that server and from your JavaScript you call that COM.
UPDATE:
Well it seems you can with JSONP
jsonp with jquery

POST request to Picasa API

I'v been struggling with POST on the Picasa API.
Here's code:
$.ajax({
type: "POST",
url: 'https://picasaweb.google.com/data/feed/api/user/' + uid + '/albumid/' + album_id + '/photoid/' + photo_id,
crossDomain: true,
data: { content: content },
success: function() { alert("Success"); },
error: function() { alert('Failed!'); }
});
I've already retrieved some information via GET without problems.
Now comes the fun part, when I try to test the service with Google this error occurs:
XMLHttpRequest cannot load
https://picasaweb.google.com/data/feed/api/user/userid/albumid/albumid/photoid/photoid?content=foo%bar.
Origin http://localhost:3000 is not allowed by
Access-Control-Allow-Origin
.
And when I try in Firefox the request header method is changed to OPTIONS and status is 204: no content.
Also, I've tried to change datatype to jsonp but then HTTP method changes to GET and it retrieves information about the picture.
Access-Control-Allow-Origin is coming because your are making a ajax call to a server which is not same as your current domain.
Read more here
jsonp will not help for POST request because you can only make GET request with jsonp.
IMHO you should try to make the POST request from server side instead of client side script.

Sending javascript dictionary with array values via ajax through a bookmarklet

I have data that I want to send through an ajax GET request in following format -
{'url':['www.google.com','www.yahoo.com']}
Here is the ajax request - $.ajax({type:'GET',url:'http://www.example.com/',processData:false,data:JSON.stringify({'url':['www.google.com','www.yahoo.com']})
And since I am doing this in a bookmarklet it looks like this -
<a href="javascript:function iprl5() { $.ajax({
type:'GET',
url:'http://www.example.com/',
processData:false,
data:JSON.stringify({'url':['www.google.com','www.yahoo.com']}),
dataType:'json',
contentType: 'application/json',
success: function(json){$('#confirm').html('<p>Thanks!</p>');},
error: function(){$('#confirm').html('<p>Something went wrong :( please reload</p>');} })}} iprl5(); void(0)">BLAH</a>
The problem is that when I hit the bookmarklet browser sends a get request like this -
GET http://www.example.com/?{"url":["www.google.com","www.yahoo.com"]}
I want to send a json as a string but unable to do so, I also tried encodeURIComponent to encode string but that didn't work either.
I would try: data: 'url=' + JSON.stringify(['www.google.com','www.yahoo.com']),

Ajax with JQuery: 200 ok, but not "success"

I'm trying to use AJAX to send a query to Google Books and display the results on my website. I'm using JQuery to send the request and handling the response, like so:
var query = [formatted input from a form];
var URL = "http://books.google.com/books/feeds/volumes?q="+query+"&start-index=1&max-results=5";
$.ajax({
type: "GET",
url: URL,
dataType: "xml",
success: function(data, status){
alert(status);
}
});
Currently, I just have the script alerting "success" if a response is received. If I use my script to send that query to a local page for testing, this works just fine. But when I set the URL to the Google one listed above, as instructed on the Developer API page, I never see the alert. According to Firebug, I am receiving a response and a status of 200 ok as I should, but it's not getting to that "success" path. Does anyone know why?
Edit: I should add that if I follow the URL directly, to http://books.google.com etc. with some random q, it displays the feed XML with no problems, so the query is not the issue.
You can't make cross-domain requests using XMLHttpRequest under the standard browser security settings. One possible solution is to write a local proxy function (assuming you can create server-side code) that forwards the query to the external site, and then returns the response.
Edit: It looks like Google provides a JavaScript API as well. I would assume that they've crafted in such a way to avoid the cross-domain XHR issue.
http://code.google.com/apis/books/docs/js/devguide.html#execute
Edit: The JavaScript API for books was deprecated. While it's no longer practically useful, you can see the original referenced documentation text via the Wayback Machine archive: http://web.archive.org/web/20120414070427/http://code.google.com/apis/books/docs/js/devguide.html#execute
It's a cross-domain problem with ajax calls because browsers have a security model based on a domain policy.
if you don't wan to include the whole Google Books API, you can also use Google Ajax API with jsonp for cross-domain ajax calls.
Docs here:
http://code.google.com/apis/books/docs/js/jsondevguide.html#basic_query
jQuery example
var query = 'jquery';
var URL = 'https://ajax.googleapis.com/ajax/services/search/books?v=1.0&q=' + query;
$.ajax({
type: 'GET',
url: URL,
dataType: 'jsonp',
success: function( data, status ){
alert( data.responseData.results.length + ' results found!' );
},
error: function() {
alert( 'Something goes wrong!' );
}
});
Ciao!

Resources