I have made an account and have my api key currently i just want a simple search box and button that when hit will list the game and the image of that game
Have linked the site info below
http://www.giantbomb.com/api/documentation
I want to run is and get the output using json and jquery any help welcome
This is a working search now some what does not allow the user to enter in a new value and there is a problem bring up the image
two main problems wont load the image just says undefined and cant figure out how to make it a full search only when he user enters a new title
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "http://api.giantbomb.com/search/",
type: "get",
data: {api_key : "key here", query: "star trek", resources : "game", field_list : "name, resource_type, image", format : "jsonp", json_callback : "gamer" },
dataType: "jsonp"
});
});
function gamer(data) {
var table = '<table>';
$.each( data.results, function( key, value ) {
table += '<tr><td>' + value.image + '</td><td>' + value.name + '</td><td>' + value.resource_type + '</td></tr>';
});
table += '</table>';
$('#myelement').html(table);
}
</script>
</head>
<body>
<h1>Game Search</h1>
<input id="game" type="text" /><button id="search">Search</button>
<div id="myelement"></div>
</body>
</html>
Your working code as per standard of the giantbomb docs:
var apikey = "My key";
var baseUrl = "http://www.giantbomb.com/api";
// construct the uri with our apikey
var GamesSearchUrl = baseUrl + '/search/?api_key=' + apikey + '&format=json';
var query = "Batman";
$(document).ready(function() {
// send off the query
$.ajax({
url: GamesSearchUrl + '&query=' + encodeURI(query),
dataType: "json",
success: searchCallback
});
// callback for when we get back the results
function searchCallback(data) {
$('body').append('Found ' + data.total + ' results for ' + query);
var games = data.game;
$.each(games, function(index, game) {
$('body').append('<h1>' + game.name + '</h1>');
$('body').append('<p>' + game.description + '</p>');
$('body').append('<img src="' + game.posters.thumbnail + '" />');
});
}
});
http://jsfiddle.net/LGqD3/
GiantBomb Api example/explanation
First get your api key
Key: http://www.giantbomb.com/api/
Documentation: http://www.giantbomb.com/api/documentation
Your base url:
http://www.giantbomb.com/api/
Your url structure:
/RESOURCE?api_key=[YOUR_API_KEY]&format=json/FILTERS/FIELDS
/RESOURCE/ID example: /game/3030-38206/
The type of resource you which to return, in your case a search. Sometimes.. in case of a specific game you also want to pass in the ID under /ID (like in the example)
api_key
Your api key
You need this otherwise you cannot use the api :)
format
The format you which to output, in this case json.
FILTERS example: /search?limit=100
This manipulates the resourses output
See under the resources in the documentation for a what you can do.
FIELDS example: /search?field_list=description,
Which field to return, use this to "reduce the size of the response payload"
A game request for it's name & description would be:
http://www.giantbomb.com/api/game/3030-38206/?api_key=[YOUR-API-KEY]&format=json&field_list=name,description
A search request
Lets say we want to search for the game "Elder scroll online".
You would construct your url like this:
/search/?api_key=[YOUR-API-KEY]&format=json&query="elder scrolls online"&resources=game
To implement this in with $.ajax:
The ajax function
/*
* Send a get request to the Giant bomb api.
* #param string resource set the RESOURCE.
* #param object data specifiy any filters or fields.
* #param object callbacks specify any custom callbacks.
*/
function sendRequest(resource, data, callbacks) {
var baseURL = 'http://giantbomb.com/api';
var apiKey = '[YOUR-API-KEY]';
var format = 'json';
// make sure data is an empty object if its not defined.
data = data || {};
// Proccess the data, the ajax function escapes any characters like ,
// So we need to send the data with the "url:"
var str, tmpArray = [], filters;
$.each(data, function(key, value) {
str = key + '=' + value;
tmpArray.push(str);
});
// Create the filters if there were any, else it's an empty string.
filters = (tmpArray.length > 0) ? '&' + tmpArray.join('&') : '';
// Create the request url.
var requestURL = baseURL + resource + "?api_key=" + apiKey + "&format=" + format + filters;
// Set custom callbacks if there are any, otherwise use the default onces.
// Explanation: if callbacks.beforesend is passend in the argument callbacks, then use it.
// If not "||"" set an default function.
var callbacks = callbacks || {};
callbacks.beforeSend = callbacks.beforeSend || function(response) {};
callbacks.success = callbacks.success || function(response) {};
callbacks.error = callbacks.error || function(response) {};
callbacks.complete = callbacks.complete || function(response) {};
// the actual ajax request
$.ajax({
url: requestURL,
method: 'GET',
dataType: 'json',
// Callback methods,
beforeSend: function() {
callbacks.beforeSend()
},
success: function(response) {
callbacks.success(response);
},
error: function(response) {
callbacks.error(response);
},
complete: function() {
callbacks.complete();
}
});
}
search function
function search() {
// Get your text box input, something like:
// You might want to put a validate and sanitation function before sending this to the ajax function.
var searchString = $('.textox').val();
// Set the fields or filters
var data = {
query: searchString,
resources: 'game'
};
// Send the ajax request with to '/search' resource and with custom callbacks
sendRequest('/search', data, {
// Custom callbacks, define here what you want the search callbacks to do when fired.
beforeSend: function(data) {},
success: function(data) {},
error: function(data) {},
complete: function(data) {},
});
}
Example of a get game function
function getGame() {
// get game id from somewhere like a link.
var gameID = '3030-38206';
var resource = '/game/' + gameID;
// Set the fields or filters
var data = {
field_list: 'name,description'
};
// No custom callbacks defined here, just use the default onces.
sendRequest(resource, data);
}
EDIT: you could also make a mini api wrapper out of this, something like:
var apiWrapper = {};
apiWrapper.request = function(resource, data, callbacks) {
// The get function;
};
apiWrapper.search = function(data) {
// The search function
};
apiWrapper.getGame = function(id, data) {
// The game function
}
apiWrapper.init = function(config) {
var config = config || {};
this.apiKey = config.apiKey || false;
this.baseURL = config.baseURL || 'http://api.giantbomb.com';
}
apiWrapper.init({
apiKey: '[API-KEY]'
});
Have not tested the code, so there might be a bug in it, will clean it up tommorow :)
Edit: fixed a bug in $.ajax
Related
I'm trying to construct a generic Ajax function by passing the few properties required by a jQuery Ajax object as object parameters. I'm stuck on one piece of the puzzle, that is the proper way to pass the callback function within "done". The idea is to replace about 10 ajax functions in my .js file with just one ajax function.
Here's my code:
// The generic ajax function, which will be called by various functions
// and passing variable parameters, different controller urls, different
// GET or POST types, different POST data sets, and finally, different
// callback functions.
function generalAjax(params){
$.ajax({
url: params.url,
type: params.type,
data : params.formData,
dataType : 'json'
}).done(function( data ) {
params.callback; // <-- Trying to get this line to work.
}).fail(function(jqXHR, textStatus){
var string = "Ajax request failed : " + textStatus + " - " + jqXHR.responseText;
$("#diag").html(string);
});
}
// Create the prototype
function ajaxParams(url, type, data, callback) {
this.url = url;
this.type = type;
this.formData = data;
this.callback = callback;
}
// A button in my php file will call this function.
function nameSearch(){
var url = "/ajax/name_search/";
var type = "POST";
var formData = { 'q' : document.getElementsByName("searchname")[0].value };
var callback = nameSearchCallback; // Specific method for this event
var params = new ajaxParams(url, type, formData, callback);
generalAjax(params);
}
// One specific callback function for one specific event trigger.
function nameSearchCallback(e){
var string = "";
$.each(e,function(k,v){
string += k + " = " + v + "\n";
if(v instanceof Object == true){
string += "<ul>\n";
$.each(v,function(kk,vv){
string += "<li>" + kk + " = " + vv + "</li>\n";
});
string += "</ul>\n";
}
});
$("#form-panel").html(string);
}
15 lines down, you can see where I've substituted parameters.callback for a hard coded script or direct call to a specific function. What I want is for that line to call different functions or methods, depending on the needs of the instantiated object calling the genericAjax function.
Depending upon whether I try params.callback or params.callback(), at best, nothing happens, or at worst, the page refreshes and in my javascript console I get a TypeError : a is undefined in the jquery library file.
I have also tried var callback = nameSearchCallback; and var callback = nameSearchCallback(); I have also skipping the reference to the nameSearchCallback() function, and just writing the function into params.callback as
params.callback = function(){
var string = "";
$.each(e,function(k,v){
string += k + " = " + v + "\n";
if(v instanceof Object == true){
string += "<ul>\n";
$.each(v,function(kk,vv){
string += "<li>" + kk + " = " + vv + "</li>\n";
});
string += "</ul>\n";
}
});
$("#diag").html(string);
}
I have a working solution to my problem, but it isn't a specific answer to my question. Since nobody is answering the question, I guess I'll post the general solution.
I came across a question with an answer on how to make dynamic functions using arrays. I applied this answer to the above question.
I declare an array:
var dyn_functions = [];
Every time I want to define a callback function, I write something like this:
// Where data is an object and data['string'] is a property returned in jsson format from a php controller.
dyn_functions['nameSearchCallback'] = function (data){
var string = "<h3>Search results:</h3>\n";
string += "<blockquote>" + data['string'] + "</blockquote>";
$("#form-panel").html(string);
}
Every callback function will have its own name.
Your event trigger will call its own function, something like
var n = "Mark";
<button onClick='nameSearch(n);return false;'>Search</button>
In your script file, the event function nameSearch looks like this:
function nameSearch(n){
var url = "/ajax/name_search/"; //This is the name of a php file or a function in an MVC controller
var type = "POST"; //This can also be GET
var formData = { 'q' : n }; //If your type is "GET", then this should be empty, like "", and you could pass `n` as a url query string or a uri segment.
var callback = "nameSearchCallback"; //Remember the dynFunction callback above? This is the name of it.
var params = new ajaxParams(url, type, formData, callback);//Make a params object to pass our params to the generic ajax function.
generalAjax(params); //Calling the generic ajax function.
}
You need to prototype the params property constructor:
// The prototype constructor for the general Ajax parameters.
function ajaxParams(url, type, data, callback) {
this.url = url;
this.type = type;
this.formData = data;
this.callback = callback;
}
...and finally, we have one single ajax function that serves infinite n of calls:
// The general Ajax function.
function generalAjax(params){
$.ajax({
url: params.url,
type: params.type,
data : params.formData,
dataType : 'json'
}).done(function( data ) {
var callback = dyn_functions[params.callback](data);
}).fail(function(jqXHR, textStatus){
var string = "Ajax request failed : " + textStatus + " - " + jqXHR.responseText;
$("#diag").html(string);
});
}
So, the whole thing all together will look like this:
// The prototype constructor for the general Ajax parameters.
function ajaxParams(url, type, data, callback) {
this.url = url;
this.type = type;
this.formData = data;
this.callback = callback;
}
// The general Ajax function.
function generalAjax(params){
$.ajax({
url: params.url,
type: params.type,
data : params.formData,
dataType : 'json'
}).done(function( data ) {
var callback = dyn_functions[params.callback](data);
}).fail(function(jqXHR, textStatus){
var string = "Ajax request failed : " + textStatus + " - " + jqXHR.responseText;
$("#diag").html(string);
});
}
//The global dyn_functions object, to be used for all scripts.
var dyn_functions = [];
dyn_functions['nameSearchCallback'] = function (data){
var string = "<h3>Search results:</h3>\n";
string += "<blockquote>" + data['string'] + "</blockquote>";
$("#form-panel").html(string);
}
function nameSearch(n){
var url = "/ajax/name_search/";
var type = "POST";
var formData = { 'q' : n }; //If your type is "GET", then this should be empty, like "", and you could pass `n` as a url query string or a uri segment.
var callback = "nameSearchCallback";
var params = new ajaxParams(url, type, formData, callback);
generalAjax(params);
}
In my App, I get a list of Events from a Sharepoint Calendar List. That part works perfectly.
However after I get the collection of results, for each item I need to get the Display Form Url, which is another REST Call with the ListItem ID.
However I get the error below, but I still dont know what the problem might be
Uncaught ReferenceError: error is not defined App.js:87(anonymous function) App.js:87$.ajax.error App.js:40c jquery-1.9.1.min.js:22p.fireWith jquery-1.9.1.min.js:22k jquery-1.9.1.min.js:24send.r
I based my code on this answer:
https://sharepoint.stackexchange.com/questions/119236/how-to-get-the-display-form-url-using-rest
My adapted code is like this:
var SPHostUrl;
var SPAppWebUrl;
var ready = false;
// this function is executed when the page has finished loading. It performs two tasks:
// 1. It extracts the parameters from the url
// 2. It loads the request executor script from the host web
$(document).ready(function () {
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var param = params[i].split("=");
switch (param[0]) {
case "SPAppWebUrl":
SPAppWebUrl = decodeURIComponent(param[1]);
break;
case "SPHostUrl":
SPHostUrl = decodeURIComponent(param[1]);
break;
}
}
// load the executor script, once completed set the ready variable to true so that
// we can easily identify if the script has been loaded
$.getScript(SPHostUrl + "/_Layouts/15/SP.RequestExecutor.js", function (data) {
ready = true;
getItems();
});
});
function getListItemFormUrl(webUrl, listName, listItemId, formTypeId, complete, failure) {
$.ajax({
url: webUrl + "/_api/web/lists/GetByTitle('" + listName + "')/Forms?$select=ServerRelativeUrl&$filter=FormType eq " + formTypeId,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
var url = data.d.results[0].ServerRelativeUrl + '?ID=' + listItemId
complete(url);
},
error: function (data) {
failure(data);
}
});
}
// this function retrieves the items within a list which is contained within the parent web
function getItems() {
// only execute this function if the script has been loaded
if (ready) {
// the name of the list to interact with
var listName = "Events";
// the url to use for the REST call.
var url = SPAppWebUrl + "/_api/SP.AppContextSite(#target)" +
// this is the location of the item in the parent web. This is the line
// you would need to change to add filters, query the site etc
// "/web/lists/getbytitle('" + listName + "')/items?" +
"/web/lists/getbytitle('" + listName + "')/items?$select=Title,Category,EventDate,Description,EncodedAbsUrl,ID" +
"&#target='" + SPHostUrl + "'";
// create new executor passing it the url created previously
var executor = new SP.RequestExecutor(SPAppWebUrl);
// execute the request, this is similar although not the same as a standard AJAX request
executor.executeAsync(
{
url: url,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function (data) {
// parse the results into an object that you can use within javascript
var results = JSON.parse(data.body);
var events = [];
$.each(results.d.results, function (i, obj) {
//Usage
getListItemFormUrl(SPAppWebUrl, 'Calendar', obj.ID, 4,
function (url) {
console.log('Display from url for list item: ' + url);
},
function (sender, args) {
console.log(JSON.stringify(error));
})
//use obj.id and obj.name here, for example:
var event = {
date: Date.parse(obj.EventDate).toString(),
type: obj.Category,
title: obj.Title,
description: obj.Description,
url: obj.EncodedAbsUrl + 'DispForm.aspx?ID=' + obj.ID
}
events.push(event);
});
var myJsonString = JSON.stringify(events);
$("#eventCalendarInline").eventCalendar({
jsonData: events,
openEventInNewWindow: true,
showDescription: true,
txt_GoToEventUrl: "Go to event"
});
Communica.Part.init();
},
error: function (data) {
// an error occured, the details can be found in the data object.
alert("Ooops an error occured");
}
});
}
}
Under //Usage:
function (sender, args) {
console.log(JSON.stringify(error));
})
error does not seem to be defined
I'm looking for some tips on how I can create a discussion reply using the 2013 Sharepoint REST end point. I'm not using the built in SP javascript libraries, instead accessing the REST end point directly using jQuery ajax calls.
My issue when attempting to create a reply is that it is creating the article as a new thread instead of a reply. I've searched around the web and all I can come up with is something to do with the URL path.
If I use the "sharepointEndPoint/_api/web/lists/getByTitle('discussions')/Items" url, it will create article as a new thread.
I've tried appending the ID of the parent thread on the end of items in brackets "(1)" for example and also "/title of parent thread" but both throw an error.
I'm also setting the ParentItemID and the ParentFolderId against the article, but sharepoint still creates it as a new thread instead of a reply.
ParentItemID property could not be specified via message payload since it is a read only property, it means the following query for creating a message item fails:
Url /_api/web/lists/getbytitle('Discussions')/items
Method POST
Data {
'__metadata': { "type": "SP.Data.DiscussionsListItem" },
'Body': "Message text goes here",
'FileSystemObjectType': 0,
'ContentTypeId': '<MessageContentTypeId>',
'ParentItemID': <DiscussionItemId> //can't be set since it is read only
}
Solution
For creating a message under a discussion item (folder) you could consider following solution: once message item is created, it's getting moved under a discussion item (folder container)
Example
The following example demonstrates how to create a message (reply) in Discussion Board via SharePoint REST API:
var listTitle = "Discussions"; //Discussions Board title
var webUrl = _spPageContextInfo.webAbsoluteUrl;
var messagePayload = {
'__metadata': { "type": "SP.Data.DiscussionsListItem" }, //set DiscussionBoard entity type name
'Body': "Message text goes here", //message Body
'FileSystemObjectType': 0, //set to 0 to make sure Message Item is created
'ContentTypeId': '0x0107008822E9328717EB48B3B665EE2266388E', //set Message content type
'ParentItemID': 123 //set Discussion item (topic) Id
};
createNewDiscussionReply(webUrl,listTitle,messagePayload)
.done(function(item)
{
console.log('Message(reply) has been sent');
})
.fail(function(error){
console.log(JSON.stringify(error));
});
where
function executeJson(options)
{
var headers = options.headers || {};
var method = options.method || "GET";
headers["Accept"] = "application/json;odata=verbose";
if(options.method == "POST") {
headers["X-RequestDigest"] = $("#__REQUESTDIGEST").val();
}
var ajaxOptions =
{
url: options.url,
type: method,
contentType: "application/json;odata=verbose",
headers: headers
};
if("data" in options) {
ajaxOptions.data = JSON.stringify(options.data);
}
return $.ajax(ajaxOptions);
}
function createListItem(webUrl,listTitle,payload){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/items";
return executeJson({
"url" :url,
"method": 'POST',
"data": payload
});
}
function moveListItem(webUrl,listTitle,itemId,folderUrl){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")?$select=FileDirRef,FileRef";
return executeJson({
"url" :url
})
.then(function(result){
var fileUrl = result.d.FileRef;
var fileDirRef = result.d.FileDirRef;
var moveFileUrl = fileUrl.replace(fileDirRef,folderUrl);
var url = webUrl + "/_api/web/getfilebyserverrelativeurl('" + fileUrl + "')/moveto(newurl='" + moveFileUrl + "',flags=1)";
return executeJson({
"url" :url,
"method": 'POST'
});
});
}
function getParentTopic(webUrl,listTitle,itemId){
var url = webUrl + "/_api/web/lists/getbytitle('" + listTitle + "')/getItemById(" + itemId + ")/Folder";
return executeJson({
"url" :url,
});
}
function createNewDiscussionReply(webUrl,listTitle, messagePayload){
var topicUrl = null;
return getParentTopic(webUrl,listTitle,messagePayload.ParentItemID)
.then(function(result){
topicUrl = result.d.ServerRelativeUrl;
return createListItem(webUrl,listTitle,messagePayload);
})
.then(function(result){
var itemId = result.d.Id;
return moveListItem(webUrl,listTitle,itemId,topicUrl);
});
}
I have a small function that takes a dynamic list of textboxes with urls and sends it to the server. I am trying to load the urls into an array then pass them off in a JSON object. The problem is, when I get to that point in the code, I keep getting the error:
TypeError: url_data[this_url] is undefined
http://localhost/2011/admin/public/assets/js/tssol.ui.js
Line 196
Here is the block that returns that error:
$("#dialogEditor").dialog('option', 'buttons', {'Save' : function() {
/* Define variables */
var url_data = new Array();
var this_url = 0;
/* I've tried this with and without explicitly passing the vars... */
$("#website_editor input").each(function(url_data, this_url) {
var id =$(this).attr('name').match(/\d+/);
var url=$(this).val();
/* Test the varible each iteration */
console.log("this_url: " + this_url + " id: " + id + " url: " + url);
/* Line 196 */ url_data[this_url].id = id;
url_data[this_url].url = url;
this_url++;
});
data = JSON.stringify(url_data);
//data = url_data;
//console.log(data);
$.ajax({
url: 'ajax.websites.php',
dataType: 'json',
data: {
action: "update_resort",
ResortId: resort,
data: data
}
});
$(this).dialog("close");
},
'Cancel': function(){$(this).dialog("close");
}});
},
Sorry about the formatting
I would do this:
url_data[this_url] = {
id: id,
url: url
}
I am sending a request by post using jquery ajax, but some of the words i send have + to join words like: HTA+HIPERAQUITISM+DBLR, the php recieve HTA HIPERAQUITISM DBLR changing the + by blank spaces, i post the code below. help!
function getItemInfo(itemName, itemField, itemComparative, itemTable){
var result = "";
var nombreItem = itemName;
var campoItem = itemField;
var comparativeItem = itemComparative;
var tableItem = itemTable;
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+nombreItem+
'&campo='+campoItem+
'&comparador='+comparativeItem+
'&tabla='+tableItem,
success: function(data) {
result = data.toString();
},
failure: function() {
result = "";
}
});
return result;
}//end function
This is because in a URL + means space.
You'll need to URL encode the data first before adding it to the query string.
You can use the encodeURIComponent() function to encode your value before adding it to the query string.
Once your PHP code picks it up you can then decode the value with the urldecode function
So your code should update to something like this:
url: 'modules/medicos/controller.php?fun=consul_item&nombre_item=consul_item'+
'&nombre_item='+encodeURIComponent(nombreItem)+
'&campo='+encodeURIComponent(campoItem)+
'&comparador='+encodeURIComponent(comparativeItem)+
'&tabla='+encodeURIComponent(tableItem),
Your code seems to be correct. You are passing those variables one by one (nombreItem, campoItem, comparativeItem and tableItem). So I don't really understand what you say is not working.
A suggestion to make passing data easier:
$.ajax({
type: 'POST',
async: false,
url: 'modules/medicos/controller.php',
data : ({ fun : consul_item,
nombre_item : nombreItem,
campo : campoItem,
comparador : comparativeItem,
tabla : tableItem }),
success: function(data) {
result = data;
},
failure: function() {
result = "";
}
});
If you want to pass all your info as one textual string you should do:
...
data: ({ test : consul_item + '+' + nombreItem + '+' + campoItem + '+' + comparativeItem + '+' + tableItem }),
...