$(document).ready(function() {
$.getJSON('https://jira.atlassian.com/rest/api/latest/project?callback=?', function(data) {
console.log("success");
});
});
Why this code is not working? Its not giving error also in browser. But a project file is being downloaded as script in Chrome as shown by Inspect Element tool. How can I get data from the file?
It looks like Atlassian use jsonp-callback instead of callback as the parameter in a query string for JSONP callbacks.
See here.
I would suggest you configure your JSONP-call with the jQuery.ajax API like:
$(function() {
$.ajax({
type: "GET",
url: "https://jira.atlassian.com/rest/api/latest/project",
dataType: "jsonp",
jsonp: "jsonp-callback",
data: { /* additional parameters go here */ }
}).done(function(data) {
console.log("success");
});
});
The option jsonp renames the JSONP-callback parameter as #mccannf suggested from the API.
Also, for future reference, you might consider using the jqXHR object to add error-handling functionality, so you can tell if the JSON request is failing. See jQuery's reference (http://api.jquery.com/jQuery.getJSON/)
$(document).ready(function() {
var jq = $.getJSON('https://jira.atlassian.com/rest/api/latest/project?callback=?',
function(data) {
console.log("success");
})
.error(function() { console.log("error occurred"); });
});
Related
I have a strange issue using jQuery and JSON, especially JSONP.
My goal is to simply GET JSON data, but I always end up with the following error:
Uncaught SyntaxError: Unexpected token
Here is the code:
<script type="text/javascript">
$(document).ready(function() {
var myurl = "someurl";
$.ajax({
url: myurl,
method: 'GET',
contentType: 'application/javascript',
dataType : 'jsonp',
success: function(result){
//Do something with JSON result
}
});
</script>
And of course the JSON (raw format):
{"result":[{"targetView":"powerUsage","myData":{"someItems":["9","5","8"],"someItems2":[{"text":"protoText","currentRecord":"45.38","absolute":100}]}}]}
I tried the webservice with the Advanced Rest Client App in Google Chrome and it is working perfectly. I have no clue why this simple example gets this syntax error message.
Your Ajax code looks like fine. I think you are trying to make a Cross domain call as JSONP is a hack for dealing cross domain ajax call. If you Server code if ready for dealing with JSONP request then you must have send a callback parameter like
?callback=my_callback_method
than you service will return result with a callback see below links for more details:
https://learn.jquery.com/ajax/working-with-jsonp/
http://stackoverflow.com/questions/11736431/make-cross-domain-ajax-jsonp-request-with-jquery
You missed to put ready function close, that is }); at the last before script tag close:
<script type="text/javascript">
$(document).ready(function()
{
var myurl = "someurl";
$.ajax(
{
url: myurl,
method: 'GET',
contentType: 'application/javascript',
dataType: 'jsonp',
success: function(result)
{
//Do something with JSON result
}
});
});
</script>
I am trying to use JQuery to access Transloc's API (https://www.mashape.com/transloc/openapi-1-2#!documentation). I have not used JQuery or this API before. If anyone could shed some light on this I would appreciate it.
I can't test this as I don't have a key but it should work in theory.
Using the endpoint you linked to. Change the url for what you need.
$.ajax({
type:"GET",
beforeSend: function (request)
{
request.setRequestHeader("X-Mashape-Authorization", <mashape-key>);
},
url: "https://transloc-api-1-2.p.mashape.com/agencies.json?agencies=12%2C16&geo_area=35.80176%2C-78.64347%7C35.78061%2C-78.68218&callback=call",
processData: false,
success: function(data) {
//use data
},
error: function(data) {
//handle error
}
});
I wrote this jquery code:
$(document).ready(function () {
$("#testDiv").load("http://localhost:7908/ToLoadAjax.aspx");
});
It seems it is a Get http request.
How to make it a post call please?
$(document).ready(function () {
$.post('http://localhost:7908/ToLoadAjax.aspx', function(data) {
$("#testDiv").html(data);
});
});
Use $.post() see the documentation for more informations.
Since you asked:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
Btw, read the documentation! https://api.jquery.com/jQuery.post/
But it doesn't make any difference do either a GET or a POST unless you are really sending in any data.
I want to read the contents of a local file using JavaScript/jQuery. I understand this is often discussed, but my example is a little different because I want to return the contents after the fetch is done rather than manipulate HTML.
I don't want to talk about security issues and local files because this code is meant to run within my own browser (Chrome, which I start with the --allow-file-access-from-files flag).
I have the following function to get the data...
function readData() {
$.ajax({
type: "GET",
url: "data.xml",
async: false, // this does not change the outcome
dataType: "xml",
success: function(xml) {
// Got the data, find entries and return them.
console.log("Returning data");
var doc = $(xml).find('entry');
// This is where most examples manipulate dom, I want to
// return the data instead
return doc;
}
});
}
Now I want to do...
var xmlDoc = readData();
// undefined, why?
and have the document in the variable. Instead I get undefined. It seems that the function returns before the file is fetched. Or maybe I have a problem with variable scope?
Does anyone know how to accomplish this? Yes, I am sure I want to use JavaScript even though I am doing this locally.
The stackoverflow answer regarding handling of $.ajax calls has a good example of a nice way this can be used. This example can be slightly modified to give you something close to what you are looking for.
function xhr_get(url) {
return $.ajax({
url: url,
type: 'get',
dataType: 'xml',
beforeSend: showLoadingImgFn
})
.always(function() {
// remove loading image maybe
})
.fail(function() {
// handle request failures
});
}
The examples of implantation of the above method is:
xhr_get('/index').done(function(data) {
// do stuff with index data
});
xhr_get('/id').done(function(data) {
// do stuff with id data
});
You might want to something like:
function readData() {
var returnData;
xhr_get('data.xml').done(function(data) {
returnData = data;
});
return returnData;
}
Hope that helps.
Following is my code :
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error);
},
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
Here my url variable is the link which contain the following data and as per I know it is in the JSON format:
[{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}] etc..
I want to call jsonpCallback function after passing successive data to it. But success argument of $.ajax is not calling the function thats why I am not getting any data into it. But my debugger window showing response there, so why its not coming $.ajax function?
Any help...thanks in advance.
Try to pass type of ajax call GET/POST.
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
The URL you are trying to load data from doesn't support JSONP, which is why the callback isn't being called.
If you own the endpoint, make sure you handle the callback GET parameter. In PHP, your output would look like this:
<?php
echo $_GET['callback'].'('.json_encode($x).')';
This will transform the result to look like this:
jsonp2891037589102([{"destination":"United States","destinationId":"46EA10FA8E00","city":"LosAngeles","state":"California","country":"United States"}])
Of course the callback name will change depending on what jQuery generates automatically.
This is required as JSONP works by creating a new <script> tag in the <head> to force the browser to load the data. If the callback GET parameter isn't handled (and the URL returns a JSON response instead of a JSONP response), the data gets loaded yes, but isn't assigned to anything nor transferred (via a callback) to anything. Essentially, the data gets lost.
Without modifying the endpoint, you will not be able to load the data from that URL.
One weird thing I've noticed about $.ajax is that if the content-type doesn't match exactly it's not considered a success. Try playing around with that. If you change success to complete (and fix the arguments) does it alert?
It's not working because your server does not render a JSONP response. It renders a JSON response.
For JSONP to work, the server must call a javascript function sent by the ajax request. The function is generated by jQuery so you don't have to worry about it.
The server has to worry about it, though. By default, this function's name is passed in the callback argument. For example, the URL to the server will be http://some.domain/ajax.php?callback=functionName (notice callback=functionName).
So you need to implement something like the following on the server side (here in PHP):
$callback = $_GET['callback'];
// Process the datas, bla bla bla
// And display the function that will be called
echo $callback, '(', $datas, ');';
The page returned will be executed in javascript, so the function will be called, so jQuery will call the success function.
First check in which event you are calling $.ajax function...
<script type='text/javascript'>
jQuery('#EnrollmentRoleId').change(function(){
alert("ajax is fired");
$.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) { alert(error); },
success: function(data) {
alert(data);
jsonpCallback(data);
}
});
});
function jsonpCallback(response){
//JSON.stringify(response)
alert(response);
}
</script>
second try to replace $ with jQuery.
Try to give no conflict if you thinking any conflict error..
jQuery ajax error callback not firing
function doJsonp()
{
alert("come to ajax");
$.ajax({
url: url,
dataType: "jsonp",
crossDomain: true,
jsonpCallback:'blah',
success: function() { console.log("success"); },
error: function() { console.log("error"); }
});
}
Then check your json data if it is coming it is valid or not..
Thanks