JSONP ajax callback failing - javascript

I have following script running on my local test drive. It imports a JSON file and builds a webpage, but for some reason, there is an error in handling the data. No data is shown...
But whenever I use (the same) data hard-coded, I get the result I want. So this made me think it has something to do with the way I handle the JSON import...
This is my AJAX callback:
getGames: function(fn) {
$.ajax({
type: "GET",
url: App.Config('webserviceurl')+'games-payed.js',
dataType: "jsonp",
success: function (data) {
console.log('streets', data);
if(fn){
fn(data);
}
},
error: function (msg) {
if(fn){
fn({status:400});
}
}
});
}
And this code isn't working, nor am I getting any errors in my console...
When I load the data hard coded, it works perfectly:
getGames: function(fn) {
var games = App.Config('dummyGames');
if(fn){
fn(games);
}
}
Is there something wrong with my AJAX callback?
EDIT:
The JSON file looks like this:
jsonp1({
"status": "200",
"data": [
{
"id": "1",
"title": "Title 1",
"publishDate": "2013-03-27T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game1.png",
"html5": "http://mysite.com/index.html"
},
{
"id": "2",
"title": "Title 2",
"publishDate": "2013-03-20T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game2.png",
"html5": "http://mysite.com/index.html"
},
{
"id": "3",
"title": "Title 3",
"publishDate": "2013-03-18T15:25:53.430Z",
"thumbnail": "images/thumbs/image_game3.png",
"html5": "http://mysite.com/index.html"
}
]
});

In your example, I see that you wrap your json data inside jsonp1. I suppose that is a fixed name. If that's the case, try this:
getGames: function(fn) {
$.ajax({
type: "GET",
url: App.Config('webserviceurl')+'games-payed.js',
jsonp: false,
jsonpCallback:"jsonp1",
dataType: "jsonp",
success: function (data) {
console.log('streets', data);
if(fn){
fn(data);
}
},
error: function (msg) {
if(fn){
fn({status:400});
}
}
});
}
Notice the jsonpCallback:"jsonp1" and jsonp: false. The reason for this is: by default, jquery will generate the callback function name automatically and randomly and append ?callback=generatedFunctionName to the end of your url. Thanks to the callback parameter, the code on server side could use the same function name to call the callback on browser.
In your case, you're using fixed function name (jsonp1), so you have to:
Specify your function name explicitly using jsonpCallback="jsonp1"
Set jsonp = false to prevent jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation.

Related

Bad request:Error function and timeout in ajax never fired

Here is my ajax call
var settings = {
"async": true,
"crossDomain": true,
"url": "http://sample.com/customer/api/v1/meetings/meeting",
"method": "POST",
"headers": {
"x-api-key": token
},
"dataType":'json',
"data": {
"title": meetingData.title,
"end_date": meetingData.endtdate,
"from_date": meetingData.startdate,
"description": meetingData.description,
"reminder_type": meetingData.remainder,
"priority": meetingData.priority
}
}
$.ajax(settings).done(function (response) {
console.log(response);
},function(err){
alert('error');
});
Problem is error callback function is never fired if any error is present.
Also i want to add a timeout this ajax call ,how can i do that??
I've added timeout:20000 parameter in my settings variable but the error call back is not fired
UPDATE
I will get a bad request error from the console ,how to solve that error??
I doubt the .done() has a error callback, instead you should use .then(successCB, errorCB) which has both callbacks:
$.ajax(settings).then(function (response) {
console.log(response);
},function(err){
alert('error');
});
Update
As per updates: I will get a bad request error from the console ,how to solve that error??
Then in this case the doubtful entities could be your data object you are sending, one of them or more might have some data which is causing this error. So you can inspect what data is getting through here:
"data": {
"title": meetingData.title,
"end_date": meetingData.endtdate,
"from_date": meetingData.startdate,
"description": meetingData.description,
"reminder_type": meetingData.remainder,
"priority": meetingData.priority
}
Write success and error within settings variable itself:
var settings = {
"async": true,
"crossDomain": true,
"url": "http://sample.com/customer/api/v1/meetings/meeting",
"method": "POST",
"headers": {
"x-api-key": token
},
"dataType":'json',
"data": {
"title": meetingData.title,
"end_date": meetingData.endtdate,
"from_date": meetingData.startdate,
"description": meetingData.description,
"reminder_type": meetingData.remainder,
"priority": meetingData.priority
},
"success":function(resp){
//your work here
},
"error":function(resp){
//your work here
}
}
$.ajax(settings);
Or remove it from settings and bind it globally to document as
$(document).ajaxSuccess(function( event, xhr) {
//error code here
}).ajaxError(function(event,xhr){
//error code here
});

selectize.js doesn't work with remote url

I'm using selectize like this:
$('#category_field').selectize({
valueField: 'name',
searchField: 'name',
delimiter: "/",
options: [],
load: function(query,callback)
{
if(!query.length) return callback();
$.ajax({
url: '/categories/autocomplete',
type: 'GET',
dataType: 'jsonp',
data: {
},
error: function() {
callback();
},
success: function(res) {
callback(res.movies);
}
});
}
}
);
"#category_field" is just a form input of type text.
I verified that the ajax request is being made and the response from the server looks like this:
[
{
"_id": {
"$oid": "568bee09421aa908fe000009"
},
"depth": 0,
"name": "math",
"parent_id": null,
"parent_ids": [],
"picture": {
"url": "/uploads/category/picture/568bee09421aa908fe000009/Screenshot________________.png",
"thumb": {
"url": "/uploads/category/picture/568bee09421aa908fe000009/thumb_Screenshot________________.png"
}
}
}
]
My problem is that the autocomplete dropdown menu doesn't even show, what to do ?
Edit
I just wanted to mention that I'm using bootstrap 3 , the input field and the label for it are wrapped inside <div class=field>...</div>, this div is wrapped inside the form which is wrapped inside container inside panel.
Does this relate to the problem ?
This response not looks like a valid JSON. Check console, or/and use trycatch
try { $.ajax(...) } catch (err) { console.error(err); }
And JSONP is crossDomain method, maybe you can try delete it.
What i noticed
You are not passing any query to the service
You have to set preLoad true to load the options or have to set preLoad in focus to set the options initially
or
You have to initialize the option with the array as like your response

returning another page's variables using AJAX

I am using AJAX to try and return list items. The list items are stored on another page as a var. The var is called WPQListData. This var is viewable in the page source.
var WPQ2ListData = { "Row" :
[{
"ID": "1",
"PermMask": "0x7fffffffffffffff",
"FSObjType": "0",
"Title": "test",
"FileLeafRef": "1_.000",
"Created_x0020_Date.ifnew": "",
"FileRef": "\u002fsites\u002fResilient\u002fLists\u002fNewsSliderList\u002f1_.000",
"File_x0020_Type": "",
"File_x0020_Type.mapapp": "",
"HTML_x0020_File_x0020_Type.File_x0020_Type.mapcon": "",
"HTML_x0020_File_x0020_Type.File_x0020_Type.mapico": "icgen.gif",
"ContentTypeId": "0x0100B87D22D691BA4B419255256292F918AA00B2962D0F358E9442AFF496C5DFF6AB1F",
"Body1": "test"
}
Id like to get this variable using AJAX. I'm currently trying the following:
$.ajax({
url: ctx.HttpRoot+"/Lists/NewsSliderList/AllItems.aspx",
type: "GET",
success: function (data) {
var dataDom = $(data);
var stripped_data = $(dataDom).find("WPQ2ListData");
},
error: function () {
// your error logic
alert("AJAX failed");
}
})
Is it possible to get Vars via AJAX, and if so then what am i doing wrong?
thanks

Accessing elements in single Json Object

I have a book in the form of a single Json object returned from an ajax request:
{
"status": "success",
"bytes": 2598,
"book": {
"isbn": 9781449397227,
"title": "jQuery Pocket Reference",
"author": "David Flanagan",
"description": "As someone who uses jQuery on a regular basis, blah blah.",
"published": "2000-05-02",
"cover": "http://bks9.books.google.co.uk/books?id=rK6YPwAACAAJ&printsec=frontcover&img=1&zoom=1&source=gbs_api",
"pages": 402,
}
}
And I wish to access the isbn, title, author elements etc to append to my output . My question is how to access these in my
success: function(data) {
};
I have used console.log(data); in success and Firebug shows me that the data is there. My other ajax calls return a books array and I can just use something like:
$.each(data.books, function(i,book)
and it works fine. But with the example above its just a single object 'book'.
Thanks
success: function(data) {
console.log(data.book.isbn);
console.log(data.book.title);
console.log(data.book.author);
};
I'm not sure I understand the problem (because of my little english). But if your ajax call has dataType:'json', you can access the data with
success: function(data) {
console.info(data)
otherwise you have to parse the data with
success: function(data) {
data = $.parseJSON(data);
or in case use are using Crockford JSON lib
success: function(data) {
data = JSON.parse(data);

Javascript alert if JSON response has designated row

I'm trying to build an app that gets JSON from server and then shows a javascript alert if the JSON response has designated row. The JSON I get from server looks like this:
{
"key": [
{
"IND": "406",
"NUMBER": "9",
"MESSAGE": "this is a test",
"status": "ok"
}
]
}
And this is the code I use to show the alert:
function UpdateRecord(update_id) {
var id = getUrlVars()["id"];
jQuery.ajax({
type: "POST",
url: serviceURL + "test.php",
data: 'id=' + id,
cache: false,
success: function(data) {
if (data.status == 'ok') {
alert(data.message);
} else {
alert("no");
}
}
});
}​
But this code alerts "no" even though the JSON has a row "status": "ok"
Try with if (data.key[0].status), and replace alert(data.message) with alert(data.key[0].MESSAGE). You have to be careful with capitalization!
you have "key" defined in your jSON, sohould it not be
if(data.key[0].status == "ok")
Do a console.log(data) in the success handler to see what the data is. You will see that there is no data.status, but instead it would be data.key[0].status.

Categories

Resources