I'm trying to set up a model using backbone that loads from a remote url: https://api.github.com/legacy/repos/search/javascript. Here is what I have so far.
var Repo= Backbone.Model.extend({});
var RepoCollection = Backbone.Collection.extend({
url : "https://api.github.com/legacy/repos/search/javascript",
model : Repo
});
var repos = new RepoCollection();
repos.fetch({success: function(){
console.log(repos.models);
}});
This just gives me an empty array. Why does this not work? This url just contains a non-empty JSON array. I've also tried the parse function without any success.
parse : function(data) {
return data.results;
}
If the github api does not support this kind of call, does anyone have an example of a remote url where I can use backbone to fetch data?
Edit: I should add that I looked at the network console on Chrome and I am getting a 200 OK response with correct JSON response from github. I guess I'm just having trouble figuring out how to access that data and populate my RepoCollection with it.
Your data is wrapped in a repositories key, not in results and looks like this
{
"repositories": [
...
]
}
Try
var RepoCollection = Backbone.Collection.extend({
url : "https://api.github.com/legacy/repos/search/javascript",
model : Repo,
parse : function(data) {
return data.repositories;
}
});
and a demo http://jsfiddle.net/nikoshr/vHX7C/
You can try:
repos.fetch({success: function(data){
console.log(data);
}});
Related
my search params is
$params=Yii::$app->request->queryParams;
And my api call is like
function doInBackground(){
var params=<?=json_encode($params)?>;
$.get('car/get-map-data',
{
"params":params
},
function(data){
if(data)
{
console.log(data);
}
});
}
But i am getting an error like
PHP Notice – yii\base\ErrorException
Array to string conversion
on the line
var params=<?=json_encode($params)?>;
How to solve this.I want to pass the search params to another api.
you can use getQueryString()
function doInBackground(){
var params=<?=Yii::$app->request->getQueryString();?>;
$.get('car/get-map-data',
{
"params":params
},
function(data){
if(data)
{
console.log(data);
}
});
}
I think that handling the query params via URLSearchParams would be more non-hacky and clearer solution than obtaining them via PHP.
By URLSearchParams you can collect them into JS object and properly pass it as POST data to your AJAX request.
I am using a requirejs with backbone. The script runs without error but model.fetch() does not update the model. The two files for Backbone.js are:-
In main.js I have
'use strict';
require(['pageElements'],function(pageElements){
$( document ).ready(function() {
var country = new pageElements.country();
country.fetch({
success: function(e){
console.log(country.get('areaLevelZeroID')); // returns undefined
}
});
});
});
In pageElements.js I have
define(function() {
var country = Backbone.Model.extend({
url : 'resources/js/backBoneSandBox/countries.php',
parse: function(data){
newData = JSON.parse(data);
console.log(newData.areaLevelZeroID); // returns 1
return data;
}
});
return ( country );
});
Where the parse function is returning the correct value but not updating the model.
resources/js/backBoneSandBox/countries.php is tested and returns the jSON String
{"areaLevelZeroID":"1","areaLevelZeroName":"Afghanistan"}
I must be missing something really simple but I just can't see what. Thank you in advance for any advice you can offer.
In general flow is fetch - parse - set - success handler.
In your case you receive string response from the server, so you have to parse it to JSON, before calling set on the model. Thats why, you had to return newData;
I am using this tutorial to help me with rendering a tiled map. I want to try this example but CORS seems to be stopping me on the local side. It is not my main issue though, because i need to use dynamic JSON data, instead of directly including the json file. The relevant code is like this :
....
renderLayers: function(layers) {
layers = $.isArray(layers) ? layers : this.data.layers;
layers.forEach(this.renderLayer);
},
loadTileset: function(json) {
this.data = json;
this.tileset = $("<img />", { src: json.tilesets[0].image })[0]
this.tileset.onload = $.proxy(this.renderLayers, this);
},
load: function(name) {
return $.ajax({
url: "mountain.json",
type: "JSON"
}).done($.proxy(this.loadTileset, this));
}
};
scene.load("mountain");
Ideally, i would want to have a var that holds the whole json object and change the above method to support that. I tried a few things, but i lack jquery knowledge, so i think i kinda messed this.
Please notice that the sample gist is here :
https://gist.github.com/shaneriley/4078905
Could anyone help me with how i would go about directly using the json object instead of including the json file ? Thanks !
I am creating a basic piece of functionality to allow users to send their location to a server which then queries a database and returns locations near to them. I am using the below jQuery .ajax wrapper to POST data to the server. This takes the form of a latlon point which is then used as the basis for a geosearch in MongoDB using nodejs and express on the backend. The results of the search are then intended to be returned to the client and rendered by the createMapListings function.
The /find page is initially rendered through a GET request to the database via mongodb separate from the below code. However subsequent to initial rendering, I then want to return results dependent on the location provided.
The POST method works fine and the location is posted to the server, with the search results being returned as I can print contents out through the console log.
However, I then want to render the results on the client-side. As mentioned, the results of the search render in the console, but when I attempt to pass through to the client, I can render the data itself (in the form of an array of objects) in the #output div, but the createMapListings function does not seem to catch the data.
In fact, the below function appears to be called but prints out over a thousand rows with the data that should be caught described as 'undefined'. I have tried to use res.render and res.redirect, but in the first case, the view renders in the div (which I suppose is expected) and the redirect fails.
The createMapListings function works fine when a simple GET request is made to the server, for example, for all objects in a collection, using ejs template. However, I think the issue here may be a combination of a POST request and then wanting to pass the results back to the AJAX request using the complete callback.
I apologise if the below code is somewhat obtuse. I’m definitely what you would call a beginner. I appreciate the above functionality may not possible so if there is a better way, I would of course be open to it (res.direct perhaps).
Here is the relevant client side script:
$(document).ready(function(){
$("#geolocate").click(function(){
navigator.geolocation.getCurrentPosition(geolocate, function(){
});
});
});
function geolocate(pos){
var latlonpt = [];
var x = pos.coords.latitude;
var y = pos.coords.longitude;
latlonpt.push(x);
latlonpt.push(y);
var obj = {
userlocation: latitudelongitudept
};
$.ajax({
url: "/find",
type: "POST",
contentType: "application/json",
processData: false,
data: JSON.stringify(obj),
complete: function (data) {
$('#output').html(data.responseText);
$('#infooutput').children().remove();
createMapListings(data.responseText);
}
});
};
function createMapListings(maps) {
for (var i = 0; i < maps.length; i++) {
var url = maps[i]._id;
var fullurl = "<a href='/show?id=" + url + "'>Route</a></div>";
var title = "<div>" + maps[i].title + " - " + fullurl +"";
$('#infooutput').append(title);
};
};
</script>
Here is the relevant route used in a basic express app to handle the post request made by the above .ajax wrapper.
exports.findbylocation = function(req, res) {
console.log(req.body.userlocation);
var userlocation = req.body.userlocation;
Map.ensureIndexes;
Map.find({loc :{ $near : userlocation }}, function(err, maps) {
if (err) {
console.log(err)
}
else {
var jmaps = JSON.stringify(maps);
console.log(jmaps);
res.send(jmaps);
}
});
};
By convention, the data variable name in an $.ajax callback signature refers to the parsed HTTP response body. Since your callback is on complete, we're actually passed the XMLHttpRequest used, by convention called xhr. You rightly grab the responseText property, but this needs parsing to be useful. So long as we take care over our Content-Type's and don't explicitly disable processData, jQuery will do the encoding/unencoding for us - we just deal with objects. This is a good thing, since the transport format isn't usually of any particular importance to the application logic. If we use res.json(maps) in place of res.send(jmaps), we can write our call more simply:
$.ajax({
url: '/find',
type: 'POST',
data: obj,
success: function(data) {},
error: function(xhr, text, err) {}
});
Here data is a Javascript object already parsed and ready to use. We also use a default application/x-www-form-urlencoded request rather than explicitly setting a contentType. This is the same as far as express is concerned: it will just be parsed by urlencoded instead of json.
Assuming you solved your client-sie problem.
As you are using express there is no need for JSON.stringfy,
you can use res.json(maps).
I am using backbone for the first time and I am really struggling to get it to function correctly with a JSON data file.
I have a model Like so:
window.Test = Backbone.Model.extend({
defaults: {
id: null,
name: null,
},
url: function() {
return 'json/test.json/this.id';
},
initialize: function(){
}
});
When a test item is clicked I then try to bring up the details of the pacific model that was clicked by doing
testDetails: function (id) {
var test = new Test();
test.id = id;
test.fetch({ success: function(data) { alert(JSON.stringify(data))}});
},
However this does not work, I am unable to correctly say "get the JSON element with the passed ID"
Can anyone please show me how to correctly structure the models URL to pull the element with the ID.
Thanks
The problem here is that you're treating your JSON data file like a call to a server. That won't work and it's the reason you're getting a 404. If you're accessing a file locally, you have to load the file first. You can do this with jQuery using the .getJSON() method, or if the file's static, just load it into memory with a script block (though you'll probably need to assign a var in the file). Most likely, you'll use jQuery. An example of this can be found here:
Using Jquery to get JSON objects from local file.
If this is an array of JSON, you can load the array into a collection, and use the "at" method to access the particular element by id. If it's entirely JSON, you'll have to create a custom parser.
your url is incorrect for one. you are returning the literal string 'this.id'. you probably want to do something more along the lines of
url: function () {
return 'json/test.json/' + this.id;
}
I would start by fixing your url function:
url: function() {
return 'json/test.json/' + this.get('id');
}
The way you have it now, every fetch request, regardless of the model's id, is going to /json/test.json/test.id