Here is what I have so far:
var Item = Backbone.Model.extend({
defaults: {
id: 0,
pid: 0,
t: null,
c: null
},
idAttribute: 'RootNode_', // what should this be ???
url: 'page.php'
});
var ItemList = Backbone.Collection.extend({
model: Item,
url: 'page.php',
parse: function(data) {
alert(JSON.stringify(data)); // returns a list of json objects, but does nothing with them ???
}
});
var ItemView = Backbone.View.extend({
initialize: function() {
this.list = new ItemList();
this.list.bind('all', this.render, this);
this.list.fetch();
},
render: function() {
// access this.list ???
}
});
var view = new ItemView();
Current (expected) json response:
{
"RootElem_0":{"Id":1,"Pid":1,"T":"Test","C":"Blue"},
"RootElem_1":{"Id":2,"Pid":1,"T":"Test","C":"Red"},
"RootElem_2":{"Id":3,"Pid":1,"T":"Test2","C":"Money"}
}
This successfully polls page.php and the backend acts on $_SERVER['REQUEST_METHOD'] and returns the required information, however I don't know why the collection is not filled.
In the parse function of ItemList it properly shows me all the output, but it does nothing with it.
I left some comments in the code for some more precise questions, but the main question is why doesn't the collection populate with the obviously received data?
Modify your parse method to:
parse: function(response){
var parsed = [];
for(var key in response){
parsed.push(response[key]);
}
return parsed;
}
To follow conventions, change list inside ItemView to model. Also in render():
render: function() {
var template = _.template("<div>some template</div>");
this.model.each(function(item){
this.$el.append(template(item.toJSON()));
}, this);
return this;
}
The parse method you're supposed to be returning the data after doing whatever necessary parsing is required for it.
The common use case for parse would be if you're sending back an object of a form like:
{ "id" : "NaN", "tasks": [ *all your models in a list here *] }
then you'd use parse like so:
parse: function (data) {
return data.tasks
}
Backbone then handles the rest.
Is there a particular reason why you're sending the data back in that dictionary format? It's not exactly clear how you intend to map that to each model of the collection. Is the key irrelevant? if so, you should be passing back a list of the objects in the values.(Although see note at bottom). If not, and you want to attach it to the models, it should be moved to the object you're using as a value and send back a list.
* Note: Don't actually send back a JSON list bare. There is an exploit for GET requests that relies on lists being valid javascript on their own, where a malicious site can use the Array object and override it to use a script tag to your API to use the users credentials to pull down whatever information is available in that call. Instead, when wanting to send back a list you should use something like this:
{ result: [*list here*] }
Then you just use the parse method above to extract the list.
Related
I am new to Laravel. I do not know the right way to construct and accept GET requests.
I need to send the following request (en and es are language codes):
translation/next-word/en/es
and in Controller I have
public function getNextWord($langfrom, $langto) {
However, now new requirement came and I also have to send a list of IDs (on my client side it is an array (for instance, [1,5,12,15]), but it could be long list (about 100 IDs). Thus I am not sure how to send this ID array to controller and also accept it in controller method.
My old client side request (without categories):
// var categories = [1,2,5,6,17,20];
var url = "translation/next-word/en/es";
$.ajax({
url: url,
method: "GET"
}).success(function(data){
...
});
For get, change your controller like this,
public function getNextWord() {
$langfrom = $_GET['langfrom'];
$langto = $_GET['langto'];
}
In ajax send the data like this,
$.ajax({
url: url,
method: "GET" ,
data: {langfrom:langfrom,langto:langto} <----- passing from GET
}).success(function(data){
...
});
If you wan to get in parameters like this,
public function getNextWord($langfrom, $langto) {
Then ajax should look like this,
$.ajax({
url: url +"/" + langfrom + "/" langto, <----- passing as parameter
method: "GET" ,
}).success(function(data){
...
});
In Laravel, you handle GET requests by making a route in your routes.php file and then a corresponding method in a controller class to actually handle the request. In your case, because you want to also pass in an unknown number of IDs, I would suggest making that into a query parameter. You can format that however you want, although I would suggest using something like commas to divide the data in your URL. So in the end, your URL would look something like this:
example.com/translation/next-word/en/es?categories=1,2,5,6,17,20
routes
Route::get('translation/{nextWord}/{from}/{to}', 'TranslationController#translate');
TranslationController
public method translate($nextWord, $from, $to, Request $request)
{
//get the categories passed in as a query parameter
$input = $request->all();
$categories = $input['categories'];
$categories = explode(',',$categories); //turn string into array
//actually translate the words here (or whatever you need to do)
$translated = magicTranslateFunction($nextWord, $from, $to);
//also you can now use the categories however you need to
//once you're done doing everything return data
return $translated;
}
Inside your javascript, you'll just want to turn your array of categories into a comma delimited string and pass that to make the URL I started the post with.
var categories = [1,2,5,6,17,20];
var categoriesString = categories.join();
var url = "translation/next-word/en/es?categories="+categoriesString;
$.ajax({
url: url,
method: "GET",
success: function(data) {
...
}
});
Edit - using $.ajax 'data' setting
Instead of appending the categories as a string to the URL, you can just pass in the array directly as part of the 'data' setting of your ajax call.
var categories = [1,2,5,6,17,20];
var url = "translation/next-word/en/es";
$.ajax({
url: url,
method: "GET",
data: {
"categories": categories
},
success: function(data) {
...
}
});
Laravel will actually convert this correctly to a PHP array, so you don't need to do any special parsing in your controller. Just take it in like normal and use it:
TranslationController
public method translate($nextWord, $from, $to, Request $request)
{
//get the categories passed in as a query parameter
$input = $request->all();
$categories = $input['categories']; //already a PHP array
//actually translate the words here (or whatever you need to do)
$translated = magicTranslateFunction($nextWord, $from, $to);
//also you can now use the categories however you need to
//once you're done doing everything return data
return $translated;
}
Excuse me. I'm still learning the amazing JQuery language. I've faced a problem, read a lot, and still in a mess. Hope you can guide me through the solution.
I have three functions which perform three post calls. They return a text var which I lately parse as a JSON if available.
<script>
$(document).ready(function() {
...
afterAction:
a(param1,param2);
...
param1: [other value];
...
b(param1);
select:
a(param1,param2);
b(param1);
...
});
function a (param1,param2) {
// get data from DOM objects, val, texts, whatever
$.post ( "a.php", {
param1: param1,
param2: param2,
stuff1: [data from DOM objects...]
},function(data){
console.log(data)
// do something (change dom objects properties, append..)
}
});
function b (param1) {
// get data from DOM objects, val, texts, whatever
$.post ( "b.php", {
param1: param1,
stuff1: [data from DOM objects...]
},function(data){
console.log(data)
// do something (change dom objects properties, append..)
}
});
function c (param1) {
// get data from DOM objects, val, texts, whatever
$.post ( "c.php", {
param1: param1,
stuff1: [data from DOM objects...]
},function(data){
console.log(data)
// do something (change dom objects properties, append..)
}
});
</script>
The thing is that all these funtions work well... But they are asyncronous, of course. And I need to:
Execute in order, as if they were syncronous
Besides of it, (and this is one of my challenges) function a receives a param1, but after being executed code will change param1 to another value which will be used to function b.
And, whats more, this happens if trigerred certain DOM event (afterAction Owl Carrousel). If trigerred a different DOM event (selectmenu select), function a will be executed, param1 will keep its value, and function b will be called.
Things that I've tried and didn't worked:
Use $.ajax request (post method and type="text");
var posting = $.post () and posting.done ();
Nest functions in a $.when().then(),
$.when(a()).then(function(){
...
...
$.when(b()).then ({ .... });
});
AjaxQ plugin ($.postq) . But it seems to be very slow, and I dont' know why, it doesn't retrieve data.
What the calls do?
function a inserts data , updates it or deletes it using php and mysqli . It works fine for sure.
function b retrieves data from the same table.
function c retrieves a list of dates and changes the before selectmenu html.
Thanks a lot if you can help me...
ADDED 17/03/2015
A partial solution? Working on it! Change $.post by $.ajax ({... type: 'POST' }) and retrieve data using "return $.ajax" and success callback. Later I need a $.when(a(param1,param2), b(param1*), c(param1)).done(function(data1,data2,data3)){ ... }); statement which I can deal with separate data set. The thing is, when param1 is a different value for a and b functions, to be calculated previously,
A quick way is to chain them is to call each one of them in the callback function of the one you want to be executed previous to that.
For example, since a is your first function, call it, then in its callback manipulate the variables as you need and call b, and do the same in it to call c.
A rough example based on your code:
$(document).ready(function() {
//call function a first
a(param1,param2);
});
function a (param1,param2) {
// get data from DOM objects, val, texts, whatever
$.post ( "a.php", {
param1: param1,
param2: param2,
stuff1: [data from DOM objects...]
},function(data){
console.log(data)
// do something (change dom objects properties, append..)
//change the state of param1 to whatever is required and then call function b
b(param1);
}
});
function b (param1) {
// get data from DOM objects, val, texts, whatever
$.post ( "b.php", {
param1: param1,
stuff1: [data from DOM objects...]
},function(data){
console.log(data)
// do something (change dom objects properties, append..)
//change the state of param1 to whatever is required and then call function c
c(param1);
}
});
function c (param1) {
// get data from DOM objects, val, texts, whatever
$.post ( "c.php", {
param1: param1,
stuff1: [data from DOM objects...]
},function(data){
console.log(data)
// do something (change dom objects properties, append..)
}
});
i am working in extjs4 MVC where I have been working on task to create question answer page functionality.There are 4 questions to be displayed with there options.I have getting all the selected questions and answers in controller.But I didnot know how to send to srver side using models method.I am getting stuck at this point.
Here is my some controller code
1)
check:function()
{
console.log("Inside check function.");
//creating objects in javascript
var obj=new Object();
for(var i=0;i<=5;i++)
{
var inputs = document.getElementsByName(i);
var radio = "";
for (var j = 0; j < inputs.length; j++) {
if (inputs[j].checked) {
name = inputs[j].name;
value = inputs[j].value;
//obj[i].name1=name;
obj[i]={'questionId':name,'option':value};
console.log("questionId="+name +" value="+ value);
console.log("object name="+ obj[i].questionId+" Object value="+obj[i].option);
}// End of if statment
}// End of inner for loop
}//End of outer for loop
}// End of check function
2)here is I have getting some output in firebug
questionId=1 value=Aus QbqnsController.js:39
questionId=2 value=india QbqnsController.js:39
questionId=3 value=England QbqnsController.js:39
questionId=4 value=Srilanka
Actually i want to use model class methods save() . but how can I use it.
please give me some suggestions.
3)here is my model classs
Ext.define('Balaee.model.qb.QbqnsModel',{
extend: 'Ext.data.Model',
idproperty:'questionId',//fields property first position pk.
fields: ['questionId','question','languageId','userId','creationTime','questionStatusId','keyword'],
hasMany:{
model:'Balaee.model.qb.QbqnsoptionModel',
foreignKey:'questionId',
name:'options',
},
proxy:
{
type:'ajax',
api:
{
read:'http://localhost/balaee/balaee/index.php?r=QuestionBank/qbpaper/setuseranswer',
create:'http://localhost/balaee/balaee/index.php?r=QuestionBank/qbpaper/setuseranswer',
},//end of api
reader:
{
type:'json',
},//end of reader
writer:
{
type:'json',
root:'records',
},//End of writer
}
});
If you're using Ext MVC and you're questions are model instances stored inside a store, you can use store.sync() which will batch the data in different states (add, edit, deletes etc) and sync them with the relevant store or model proxy url, or the api urls specified.
This has the benefit of sending arrays of objects back in a single request, but then of course you need to separate them on the server side before processing.
Inside your function you can send them using Ext.Ajax.request
Ext.Ajax.request({
url: 'your_server_page.php ',
params: {
Your_Object_Name : JSON.stringify(Your_Object_Array)
}
});
I'm using jQuery ui's sortable. A list of objects is retrieved from the db an dynamically put into a list, the user drag and drops the list objects and the new order of the list should get saved.
Below is the jQuery code for sortable, which include creating an array of the new list order. However, next step is to do something so that I'm able to use this array in my php code.
The thing is that the user, apart from sorting the list objects also should be able to add some comments and do some other stuff and then submit it all. That is, I'm using a form for this. By that reason I must be able to put in the array with the list order into the form in some way, and here's where I need some help.
What method should I use? Ajax? Local storage? How could this be accomplished?
$('#listElements').sortable({
update: function(event, ui) {
var order = [];
$('.listObject li').each( function(e) {
order.push($(this).attr('id'));
});
}
});
You'll want to use AJAX to send the order array to PHP like so:
$('#listElements').sortable({
update: function (event, ui) {
var order = [];
$('.listObject li').each(function (e) {
order.push($(this).attr('id'));
});
$.ajax({
url: "/save_order_to_db",
type: "post",
data: {
order_data: order
}
}).success(function (data) {
console.log(data);
});
}
});
I'm trying to get geolocation from tweets.
For my tests, I posted new tweets geo-referenced but when I got the json of them, the element 'geo' is null. Why? What's wrong with them?
I don't want to search by range and geolocation: I want to search some tweets indexed by a particular hashtag and then retrieve 'geo' json element.
I tried to search other tweets (not mine) and sometimes I got 'geo' element as a full object, with coordinates array.
So, what can I do to have 'geo' element not null?
I did 4 posts geo-referenced: my tweets
The location is: 44.694704,10.528611
Edit: Added geocode param
This is what I've done server-side (pure php):
$conn = new OAuth (CONSUMER_KEY, CONSUMER_SECRET);
$conn->setToken (ACCESS_TOKEN, ACCESS_TOKEN_SECRET);
$conn->fetch (API_URL, array ('q' => '#testhashtagandgeo', 'geocode' => '44.694704,10.528611,4km'));
echo $conn->getLastResponse ();
I used PHP OAuth base and each constant is defined correctly, so it works good.
Client-side (ExtJS):
Ext.onReady (function () {
Ext.Ajax.request ({
url: 'proxy.php' ,
disableCaching: false ,
success: function (xhr) {
var js = Ext.JSON.decode (xhr.responseText);
Ext.each (js.results, function (tweet) {
if (tweet.geo !== null) {
console.log ('lat = ' + tweet.geo.coordinates[0] + ' - lng = ' + tweet.geo.coordinates[1]);
}
});
console.log (js);
} ,
failure: function (xhr) {
console.log ('something\'s wrong!');
}
});
});
Thanks in advance.
Wilk
You need to read the documentation
Location data is only included if the query includes the geocode parameter, and the user Tweeted with Geo information.
So, you need to add something like this to your query
&geocode=37.781157,-122.398720,25mi
Or whichever location you want.