jQuery Ajax request failed for get request to other domain - ajax

I want to send a request to other domain like
http://ccv.viatelecom.com/services/?item=viacall&aid=XXXX&gid=XXXX&sid=XXXX&&num=XXXXXX
I have used Ajax request as below:
$.ajax({
type: "GET",
url:'http://ccv.viatelecom.com/services/?item=viacall&aid=XXXX&gid=XXXX&sid=XXXX&&num=XXXXXX',
success:function(data){
alert(data);
},
error:function(XMLHttpRequest, textStatus, errorThrown){
alert("XMLHttpRequest="+XMLHttpRequest.responseText+"\ntextStatus="+textStatus+"\nerrorThrown="+errorThrown);
}
});
but it does not go to success function and the alert erro is:
XMLHttpRequest=
textStatus=error
errorThrown=
if I write same url address bar it display message not in Ajax request.
Is this the correct way to send request or is there another way or something I am missing?

You can not perform a cross domain ajax call.
Work around for this
Method 1
JavaScript
Create a function
function getMyData(data) {
alert(data);
//Do the magic with your data
}
Server side
On server end wrap your data inside function syntax
getMyData("Enter your data here");
JavaScript
Then create a script tag and add a link to your cross-domain page
<script type="text/javascript"
src="cross ref url">
</script>
For reference: wikipedia
Method 2
Another option is Create a proxy on your domain. ie create a page in your domain which internally calls the cross-domain page and return the same data to your Ajax call.

Related

POST Django form with AJAX and JavaScript

I would like to get some data within a Django form
In order to do that, I define a javascript which is:
$(document).ready( function() {
$('#newcase_form').on('change', function() {
pathology_type = ($('input[name="pathology_type"]:checked','#newcase_form').val());
console.log(pathology_type);
$.ajax({
url:"/pathology/",
type :'POST' ,
data : {'pathology_type' : pathology_type},
success : function(data){
console.log(date.resultat);
}
});
});
});
It works, I can retrieve the parameter inside the form
but I am unable to post it in the URL i always have an Error 500 and the paramater is not send to the URL .
here is my URL.py
url(r'^pathology/(?P<pathology_type>[A-Z]{1})/', 'myapp.views.pathology'),
Inside my form, I have a submit with another ajax, so I send an ajax request to another URL
Am I wrong, or is it possible to post to 2 different URL in the same form?
Thanks in advance for your help
I am not sure to understand your problem, but it think your javascript and url.py are inconsistent.
If you keep your javascript, the url should be:
url(r'^pathology/', 'myapp.views.pathology'),
and then get pathology_type from request.POST of your view
If you keep your url, javascript should be:
...
$.ajax({
url:"/pathology/" + pathology_type + "/",
success : function(data){
...

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.

how to call ajax method recursively

I have a problem in my ajax call.
In the below code, pageReload() function is automatically called when the page gets loaded which in-turn calls the ajaxCall() function for every 10 seconds.
I'm calling a method in grails controller through ajax by passing the parameters needed in the url. The controller method returns an array that contains 3 elements which are the Name of the book, the Author of the book and the year published.
<htmL>
<head>
<script type="text/javascript">
function pageReload() {
var timeInterval = setInterval('ajaxCall()',10000);
}
function ajaxCall() {
jQuery.ajax({
url: '/getBook?rowName=${row}&columnName=${column}',
success: function(data){
bookReturned(data);
},
error: function() {
alert('Error occured in AJAX call');
}
});
}
function bookReturned(values){
alert("Values are : "+values);
}
window.onload=pageReload;
</script>
<head>
</html>
For every 10 seconds I'm getting the alert for Values which are returned from the controller method. But the controller method is getting executed only for the first call by ajax (I have given println in controller method which gets displayed in console only one time).
How to make the ajax call to execute the controller method every time when it is called.
Please help me in this as I'm new to Grails and ajax.
Thanks in advance.
Your requests are being cached. Set the cache option to false.
If set to false, it will force requested pages not to be cached by the
browser. Note: Setting cache to false will only work correctly with
HEAD and GET requests. It works by appending "_={timestamp}" to the
GET parameters. The parameter is not needed for other types of
requests, except in IE8 when a POST is made to a URL that has already
been requested by a GET.
See jQuery documentation on cache here
jQuery.ajax({
cache: false,
url: '/getBook?rowName=${row}&columnName=${column}',
success: function(data){
bookReturned(data);
},
error: function() {
alert('Error occured in AJAX call');
}
});

Pass Codeigniter CSRF string to server via AJAX

I have enabled Codeigniter's CSRF protection on my site that uses AJAX to submit a user form and handles some other user interaction which require data submission via AJAX. As a result I came up against the "action not allowed" server side error. I quickly worked out that only the data my javascript collected and submitted via AJAX was passed to the server and as a result the CSRF code was not being sent.
The generated token tag looks like:
<input type="hidden" name="csrf_test_name" value="dsflkabsdf888ads888XXXXXX" />
So it seems to me the simplest way to submit the token to the server for verification is using a jQuery selector on csrf_test_name to get the value and then adding this to my post data for the server to verify. As per the code below:
//get CSRF token
var csrf = $('[name="csrf_test_name"]').val();
//build the form data array
var form_data = {
csrf_test_name: csrf,
... ... ...
... ... ...
}
//send the form data to the server so it can be stored
$.ajax({
type: "POST",
data: form_data,
url: ...,
dataType: "html",
success: function(msg){
... ... ...
}//end success
});//end ajax
I have followed this procedure for every ajax submission that sends data to the server and the server side error is fixed and everything works fine.
To test this I have hard coded in an incorrect CSRF token and the server detects the inconsistency and returns an erro code 500 so on the surface this works.
My question is this, is this a safe way to do this and is there an expected best practice to follow? I have done some google searching on this and it seems all the other methods are more complex and I am wondering if my way creates an attack vector that I can't see/workout.
I like to add it to the Ajax setup. Set it once and have it automatically add it to the post data for all of your requests.
$.ajaxSetup({
data: {
csrf_test_name: $("input[name='csrf_test_name']").val()
}
});
an easier method is to pass that csrf to $.ajaxSetup() that way it's included with any $.ajax() request afterward.
var csrf = $('input[name="csrf_test_name"]').val();
var data = {};
data[CSRF] = csrf;
$.ajaxSetup({ 'data': data });
then no need to include data: { csrf_test_name: 'xxx', ... } in requests after setup.

Why is this jQuery Ajax request failing?

The FCC recently made available a small set of API calls to access FCC data. In particular, I'm interested in the Consumer Broadband Test API. I'm trying to access this API through jQuery but am failing. Please let me know if I'm doing something wrong with my code or if this seems to be a problem with FCC's API.
If you visit this API request in a browser, it returns a XML response just fine: http://data.fcc.gov/api/speedtest/find?latitude=30.240236062827297&longitude=-97.64787337499999
So I've tried to load this data in jQuery using various methods:
var url = "http://data.fcc.gov/api/speedtest/find?latitude=30.240236062827297&longitude=-97.64787337499999";
$.ajax({
type: "GET",
url: url,
success: function(data) {
console.log("ajax: " + data);
}
});
$.getJSON(url, function(data) {
console.log("getJSON: " + data);
});
$.get(url, function(data) {
console.log("get: " + data);
});
In the Firebug console, all three requests show a 200 (OK) status, but the response body is empty. Also, the resulting console.log messages are:
ajax:
getJSON: null
get:
Am I doing something wrong here?
To work around the Same Origin Policy, you'll need to use JSONP. It is supported by the API. Add callback=? to the URL string in your .getJSON() call:
If the URL includes the string
"callback=?" in the URL, the request
is treated as JSONP instead. See the
discussion of the jsonp data type in
$.ajax() for more details.
So, something like this:
var url = "http://data.fcc.gov/api/speedtest/find?...&callback=?";
$.getJSON(url, function(data) {
// do stuff
});
References: http://api.jquery.com/jQuery.getJSON/
You can't make cross-domain calls using AJAX. It doesn't work like that.
What you probably want to do is to have your AJAX query URL be a local script on your own server, then have that script run a request for the API url (using cURL or something).

Resources