I've got a problem with displaying JSON data called via JSONP. I've got a complex JSON file delivered cross domain via a URL and I'm quite the novice at JSON and ajax. I followed a JSONP article here at https://learn.jquery.com/ajax/working-with-jsonp/ and that worked a treat. Now I am trying to iterate through the JSON object and display data in the HTML page after following this question How do I iterate through this JSON object in jQuery? and I'm not going anywhere. The data is not defined and I'm not sure what I am doing wrong:
// Using LibCal and JSONP
$.ajax({
url: "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41",
// The name of the callback parameter, as specified by the YQL service
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Tell LibCal what we want and that we want JSON
data: {
q: "select Room name,booked timeslots,booking name from LibCal room bookings",
format: "json"
},
// Work with the response
success: function( response ) {
console.log( response ); // server response
}
});
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
I hope it's an obvious fix to a more advanced user our there :)
Thats because your data object doesn't exist. The data key you're referring to is a on the object you're passing to the $.ajax method.
You need to execute your function inside the success callback in order for it make any sense.
$.ajax({
...
// keep all your original stuff
...
success: function( response ) {
var data = response;
$.each(data.bookings, function(index, element) {
alert(element.timeslots.room_name);
});
}
});
I did the request like this. You need to go one level more to access the array to loop.
var json_url = "https://api2.libcal.com/1.0/room_bookings_nickname/?iid=3356&group_id=12306&key=92a47e5c854dee620cca071648c3fc41"
$.ajax({
url: json_url,
crossDomain:true,
dataType:"jsonp"
}).done(function(response) {
// at the end of request
//Yours --->response.bookings
//Mine --->response.bookings.timeslots
//access the array to loop
var rooms = response.bookings.timeslots;
$.each(rooms, function(index, element) {
create_elem(element.room_name, index);
});
});
Here is a working version in jsFiddle - https://jsfiddle.net/9e746pkh/
Hope this helps.
Related
So i am not sure if i am doing this right.
I want to send markup over HTML (i am trying to create a widget)
Here is the mocky response that i am expecting
so I create a simple jquery get like this
var jsonp_url = "http://www.mocky.io/v2/5c9e901a3000004a00ee98a1?callback=myfunction";
$.ajax({
url: jsonp_url,
type: 'GET',
jsonp: "callback",
contentType: "application/json",
success: function (data) {
$('#example-widget-container').html(data.html)
},
error: function (data) {
alert('woops!'); //or whatever
}
});
then created myFunction
function myfunction(data) {
console.log(data);
}
The problem being that while, i get the response it comes as a string instead of a json or function. i am not sure how to extract the json from this (unless i do string manupulation).
Any pointers would be helpful.
JSFiddle here
P.S. Per https://www.mocky.io/ ,
Jsonp Support - Add
?callback=myfunction to your mocky URL to enable jsonp.
Delete function myfunction.
In the URL, replace callback=myfunction with callback=?.
jQuery will generate a function (your success function) and a function name for you.
I'm new to javascript and JSON and I've been given a task to complete. Please find the JSON in the following link,
http://pastebin.com/0BY3eptF
According to me the above is a very complex JSON.
I'm trying to fetch the out from a WSDL via ajax
success: function(api) {
console.log(api.SearchResult); // trying to fetch information on SearchResult object
}
This doesn't work. I would like to learn how to iterate each JSON string loop. I also see an array which is WSResult[]. A neat javascript with explanation will help me a lot. Thank you.
Some web services return content type as plain text instead of json, you have to manually convert into json. below code will help you do the same.
success: function(api) {
if (api.constructor === String) {
api = JSON.parse(api);
}
console.log(api.SearchResult);
}
To loop through api.SearchResult.Result.WSResult array, please find below code
$(api.SearchResult.Result.WSResult).each(function (index, val) {
// here val is single object of WSResult array
});
success: function(api) {}, here, api is still a string, you have to parse it to JSON first:
success: function(api) {
var api = JSON.parse(api);
console.log(api.SearchResult); // trying to fetch information on SearchResult object
}
Not a complete answer, but some useful pointers:
$ajax({
url: 'http://myURL',
// specify the datatype; I think it overrides inferring it from the document MIME type
dataType: 'json',
success: function (api) {
// provided your data does come back as a JSON document
// you should be able to access api.SearchResult
},
error: function( jsXHR, textStatus, errorThrown) {
// always have an error handler, so you can see how it went wrong.
}
);
Read the section on dataType here, as it may solve your problem
I am working with an API from another website and I am trying to get a JSON object back. Unfortunately due to the site origin issue I have to use JSONP to retrieve my data.
The function is working but I am stack on how to sanitize the data coming as a JSONP format to be able to use it as JSON?
This is my function
$('.loginForm').click(function(){
var url = 'https//api.example.com';
$.ajax({
type:'GET',
url: url,
dataType: 'jsonp',
error: jsonpCallback,
success: jsonpCallback,
jsonp: "callback"
});
function jsonpCallback(response){
console.log(response);
}
});
EDIT
This is the response I get before the error
Object { readyState=4, status=200, statusText="success", more...}
And this is the error i'm getting
SyntaxError: missing ; before statement
{"accountID":1328031,"authToken":"D81CDCB......
I went through every post in SO and the web in general to find where I am making a mistake but so far I can't find anything.
If you are getting the response in jsonP then you can use jXHR for making cross domain request , below is the link of jXHR (Library) :
https://gist.github.com/1576277/f4aead6741e0d7b0c40db6601048d9db6be1a5f9
And here is an example to use jXHR :
function sendRequest()
{
var xhrReq = new jXHR();
xhrReq.onreadystatechange = function(data)
{
if (xhrReq.readyState === 4)
{
//data contains your jsonp response..
}
};
var url = "http://" + SERVER_NAME + "yourCodeFile.aspx?callback=?";
xhrReq.open("GET",url);
xhrReq.send();
}
Always remember to add 'callback=?' as a query string parameter in url for jXHR request as the respone is jsonP.
Hope this helps you.
try using JSON.parse
function jsonpCallback(response){
console.log(JSON.parse(response));
}
Please excuse this question but I cant quite get my head around what I am doing wrong, I am trying to make a jsonp request via ajax and jquery - if i look at the response my data shows fine, however I cant get my head around how to display it in the console.
here is my code
$(document).ready(function(){
var jsondata = [];
$.ajax({
type: 'GET',
url: '<myurl with json response in a form of an array >?callback=?',
cache: false,
dataType: 'jsonp',
success: function (data) {
console.log(data);
}
});
});
just to clarify my response shows like this:
[{"content":asdf,"created_at":"date","asdf":"asdf"}]
Your response is an ARRAY of objects, so reference the array index, followed by property:
console.log(data[0].content);
var content = data.content;
var created_at= data.created_at;
var asdf= data.asdf;
console.log(content);
console.log(created_at);
console.log(asdf);
Try this
A jQuery function receives a string from a database using GET, after that I would like to inject that string into HTML in place of a div. Pretty standard stuff so it seems.
However I am not quite managing it.
Here is what I have going on:
<h1>Whatever</h1>
<div id="replace_me">
</div>
<a id="click_me" href="#">Click Me</a>
<script>
//AJAX
var brand_id = 8
var dataX = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$(function(){
$("#click_me").click(function(){
$.ajax({
type: 'GET',
url: '/ajax_request/',
data: dataX,
datatype: "json",
success: function(data) {
alert(data);
$("#replace_me").load(data);
},
error: function() {
alert("Nope...");
}
});
});
});
</script>
When the alert is set off I receive my string which shows everything is working fine, but how can I input that string I just received into the div "replace_me" without having to load from another url?
You have an error in your success function. Check documentation on jQuery load(). Instead, you should do
success: function(data) {
//alert(data);
$("#replace_me").html(data);
},
or, slightly better style
success: function(data) {
//alert(data);
$("#replace_me").empty().append($(data));
},
Also note, that you specified "json" in your datatype option. As a consequence, if your server responds in proper JSON, your data will be a JavaScript object, as jQuery will parse the JSON format for you. If you really want to see the object, you will need to use, e.g. JSON.stringify():
$("#replace_me").empty().append($(JSON.stringify(data)));
If your server does not produce valid JSON, your success method will not be called in most cases.
load() is a convenience method to do the two steps of calling the ajax url, then putting the data into the element all in a single function. Instead of calling .ajax(), just call .load()
i.e.
var brand_id = 8
var data = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$("#replace_me").load('/ajax_request/', data);