Ajax call for a Django(Piston) API always fail - ajax

I'm using an ajax call to my API created with Piston/Django. I tested that the API URLs are correct by directly typing them in the browser.
However, the ajax request always triggers the error callback function but returns an undefined error. I think the problem is somewhere inside my ajax call. Could anyone help me? Thanks a lot.
Here is my javascript:
$("#delete_req").click(function(event){
//PUTs data, saving new permissions
alert("delete_req");
event.preventDefault();
$.ajax({
url:"{{SITE_URL}}requests/api/manage/disc={{vialogue.discussion_id}}&puser={{req.userid}}&acc=0/",
type:'GET',
success: function(data, textStatus, jqXHR){
location.reload( true );
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
alert(textStatus);
alert("There was an error deleting this request. Please try again or contact us for help.")
}
});
});

In django 1.2.5 and 1.3, Ajax form submits expect a csrf token.

Are you sure that's the correct URL? It has a very strange structure. I would expect the elements that look like GET parameters to actually be GET parameters:
{{SITE_URL}}requests/api/manage/?disc={{vialogue.discussion_id}}&puser={{req.userid}}&acc=0
Does it work if you make that change?

Related

ajax post returns Object { readyState=0, status=0, statusText="error"}

I have a json string with me {offer.offer.offerId.USSellerId: {$gt: 50}}. All i wanted to do was to call a POST REST Service with this json query as payload and get the returned JSON.
I was able to call that service using chrome advanced rest client and I get the data back. But my problem is when I tried to call this service using below line of code I get the following errors
$.ajax({
url:"http://10.242.172.12:8080/cqs/services/services/cqs/search",
Accept: "application/json",
type: "POST",
contentType: "application/json",
data: {"offer.offer.offerId.USSellerId": {"$gt": 50}},
async:true,
crossDomain: true,
always: function(data, textStatus, errorThrown) {
console.log(data)
console.log(textStatus)
},
success: function (data) {
console.log(data)
alert(data);
},
error: function (data, status, err) {
console.log(data)
console.log(status)
console.log(err)
}
});
I see the following in the console:
Object { readyState=0, status=0, statusText="error"}
error
emptry string..
I could not understand anything from this error. When i did google this error, many suggestion tell that it could be cross browser problem. I have no control over server side code.
How can i fix that cross browser error from client side?
Please check the XMLHttpRequests being stopped:
If you end up with an XMLHttpRequest having status=0 and
statusText=null, it means that the request was not allowed to be
performed. It was UNSENT. A likely cause for this is when the
XMLHttpRequest origin (at the creation of the XMLHttpRequest) has
changed when the XMLHttpRequest is then open(). This case can happen
for example when one has an XMLHttpRequest that gets fired on an
onunload event for a window: the XMLHttpRequest gets in fact created
when the window to be closed is still there, and then the request is
sent (ie open()) when this window has lost its focus and potentially
different window has gained focus. The way to avoid this problem is to
set a listener on the new window "activate" event that gets set when
the old window has its "unload" event fired.

Cross-domain AJAX - not getting the desired result

I am trying to ajax a form to a different domain using the jquery.xdomainajax.js plugin and having issue getting the desired HTML back (follow up to this question: Display form result in same page with only client-side script possible?)
The destination script checks the user id against the membership database, and redirects to an error page if the user has already submitted the form, or redirect to a thank you page if the entry is valid.
Using the script below, I get back the HTML of the ORIGINAL page on which the form is displayed, not the error page or the thank you page. If I change the dataType from "text" or "html" to "jsonp", I get a parse error as expected, but the associated HTML is actually desired HTML. I am not quite sure why.
Any help would be much appreciated!
PS: I do not have control over anything in the remote server.
$.ajax({
type: settings.postType, //GET
url: settings.tourl,
data: aForm.serialize(),
dataType: settings.type, //text or HTML
crossDomain: true,
success: function(data, textStatus, jqXHR){
alert(data.responseText);
settings.success(data);
},
error: function (jqXHR, textStatus, errorThrown){
//alert(errorThrown);
console.log(textStatus);
settings.error();
}
});
Should your request type be a POST instead of a GET? Generally form info will be sent with a POST.

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.

Selectively send files through pseudo-Ajax calls

I already have the HTML and CSS set up for my form, and I have my Ajax call in place to submit it but I can't figure out how to send the images along. Here's my Ajax call:
$.ajax
({
type: "POST",
url: "/manage/processadditem",
data: $("#add_form").serialize(),
dataType: "html",
success: function( response, textStatus, XHR )
{
//Process return data
},
error: function(jqXHR, textStatus, errorThrown){
alert('An error occurred, please try again later.');
}
});
My problem is that there are 3 image inputs on the form, but I'll only use up to two of them at any given time, and one of the variables in the form tells me which ones I'm working with (gender=male/female/neutral).
In the success callback I would like to either examine that variable and decide which pictures to send along based on it, or send the variable along with the images to process in the back end, but looking through links on similar questions I haven't been able to find any examples of selectively sending files or sending additional information with them.
As far as i know you can not send files with a AJAX Post request.
i have tried myself.
It´s because the file data is not in the POST headers that is sent to the URL target.

help debugging an ajax problem

Anyone have any idea why this isn't working?
$(function(){
console.log('ready');
$.ajax({
dataType : 'jsonp',
jsonp : 'js',
url : 'http://monitor.302br.net/MonitorScoreServlet',
beforeSend : function(jqXHR, settings) {
console.info('in beforeSend');
console.log(jqXHR, settings);
},
error : function(jqXHR, textStatus, errorThrown) {
console.info('in error');
console.log(jqXHR, textStatus, errorThrown);
},
complete : function(jqXHR, textStatus) {
console.info('in complete');
console.log(jqXHR, textStatus);
},
success: function(data, textStatus, jqXHR){
console.info('in success');
console.log(data, textStatus, jqXHR);
}
});
});
This was working till recently. The beforeSend handler never fires, but you can see the ajax call being made in firebug, and if you go to the url, it seems to return acceptably formatted results (the same results as before):
http://monitor.302br.net/MonitorScoreServlet?js=jsonp1298046640938
text/javascript:
(84.3);
If I comment out the url, the beforeSend fires, but of course, there's no url....
Any ideas?
AJAX requests are, by definition, restricted to your current domain. Therefore, you cannot request an external URL from your domain.
Ok, I feel dumb. Here's what I think happened: the server used to be set up to take the js param as a callback function. So a url like:
http://monitor.302br.net/MonitorScoreServlet?js=foo
would result in:
foo(84.1);
Whenever we looked in the browser, we were just looking at:
http://monitor.302br.net/MonitorScoreServlet?js
which resulted in:
(84.1);
I assumed jQuery was doing some magic with that to turn it into usable data, but now I think that jQuery was creating something like:
function jsonp1298047240882(data) {
// do something with data
}
So when we changed our back-end code not to create the callback function call, the whole thing stopped working. (It's still weird that the beforeSend handler never gets called, though.)

Resources