JSON not match with model - json

im try render a html table via ajax with Backbone.js.
The Ajax request works fine, returns the JSON data, but appear the json not match with the model.
Im using, Symfony and Serialize Bundle.
This is my Backbone model and collection:
var Auditoria = Backbone.Model.extend({
defaults:{
id: 'undefined',
user_id: 'undefined',
user_str: 'undefined',
user_agent: 'undefined',
login_from: 'undefined',
login_date: 'undefined'
}
});
var AuditoriaList = Backbone.Collection.extend({
model: Auditoria,
url: $("#ajax-call").val()
});
var sesiones = new AuditoriaList();
sesiones.fetch({
async: false
});
The Ajax response (write on Symfony) do:
public function getSesionesAction(){
$em = $this->getDoctrine()->getManager();
$sesiones_registradas = $em->getRepository('AuditBundle:AuditSession')->findAll();
$serializer = $this->get('jms_serializer');
// Prepara la respuesta
$response = new Response();
$response->setContent($serializer->serialize($sesiones_registradas,'json'));
$response->headers->set('Content-Type', 'text/json');
// Retorna la respuesta
return $response;
}
The JSON data returned is:
[{"id":4,"user_id":1046,"user_str":"Meyra, Ariel
Germ\u00e1n","login_date":"2013-11-11
10:24:12","user_agent":"","login_from":""} ... ]
But in the table, print "undefined" in the cells.
Any ideas ?.
UPDATE
Thanks for replies. The HTML view is the next:
<table id="table-session" class="table table-bordered table-hover">
<thead>
<tr>
<th>#</th>
<th># Usuario</th>
<th>Usuario</th>
<th>Navegador</th>
<th>Desde</th>
<th>Fecha</th>
</tr>
</thead>
<tbody id="sessions">
</tbody> </table>
And the render Backnone is:
var AuditoriaView = Backbone.View.extend({
tagName: 'tr',
initialize: function(){
// Cada vez que el modelo cambie, vuelve a renderizar
this.listenTo(this.model, 'change', this.render);
},
render: function(){
this.$el.html("<td>" + this.model.get('id') + "</td>" + "<td>" + this.model.get('user_id') + "</td>"
+ "<td>" + this.model.get('user_str') + "</td>" + "<td>" + this.model.get('user_agent') + "</td>"
+ "<td>" + this.model.get('login_from') + "</td>" + "<td>" + this.model.get('login_date') + "</td>"
);
return this;
}
});
// The main view of the application
var App = Backbone.View.extend({
// Base the view on an existing element
el: $('#table-sessions'),
initialize: function(){
this.list = $('#sessions');
this.listenTo(sesiones, 'change', this.render);
sesiones.each(function(sesion){
var view = new AuditoriaView({ model: sesion });
this.list.append(view.render().el);
}, this);
},
render: function(){
return this;
}
});
new App();

I suspect that the problem is that you are trying to print the model's attributes before they are fetched from the server. Try this:
var App = Backbone.View.extend({
// Base the view on an existing element
el: $('#table-sessions'),
initialize: function(){
this.list = $('#sessions');
this.collection = new AuditoriaList
var that = this;
this.collection.fetch({
success: function(collection) {
collection.each(function(sesion) {
var view = new AuditoriaView({ model: sesion });
that.list.append(view.render().el);
});
}
});
this.listenTo(this.collection, 'change', this.render);
},
render: function(){
return this;
}
});

Related

Database mapping in Leaflet with (JSON, AJAX)

I get this JSON from DeviceNewController
public function index(Request $request)
{
$device_new = Device_new::with(['device']);
return Device_new::all()->toJson();
}
And when I wrote AJAX in view blade, it show me data from DB in console.
<script>
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
console.log(newdev.responseText);
};
newdev.send();
</script>
But I need to pass it in Leaflet script and write all data on map (coordinates, markers, device info)
When I set all in one script, there is no data in console, I can not fix it.
var newdev = new XMLHttpRequest();
newdev.open('GET', '/devices_new');
newdev.onload = function() {
var coordinates = newdev.responseText;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
};
};
newdev.send();
Did i make a mistake somewhere, is this correct???
You miss understood Ajax. Ajax is a function from JQuery, a JS library.
The ajax() method is used to perform an AJAX (asynchronous HTTP) request.
You have to add the JQuery library to your source, then you can create a Ajax call.
https://www.w3schools.com/jquery/ajax_ajax.asp
$.ajax({url: "/devices_new", success: function(result){
//result = JSON.parse(result); // If your result is not a json Object.
var coordinates = result;
for (var i=0; i < coordinates.length; i++) {
if(coordinates[i].x && coordinates[i].y){
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: "+coordinates[i].device_type+'<br>' + "Time: "+coordinates[i].datetime)
.addTo(map);
}
}
},
error: function(xhr){
alert("An error occured: " + xhr.status + " " + xhr.statusText);
}});
});
I make it on this way, and its working.
<script>
$(document).ready(function() {
$.ajax({
/* the route pointing to the post function */
url: '/device_new',
type: 'GET',
data: {
message: $(".getinfo").val()
},
dataType: 'json',
/* remind that 'data' is the response of the AjaxController */
success: function(data) {
var coordinates = data;
for (var i = 0; i < coordinates.length; i++) {
if (coordinates[i].x && coordinates[i].y) {
var marker = L.marker([coordinates[i].x, coordinates[i].y])
.bindPopup("Device: " + coordinates[i].device_type + '<br>' + "Time: " + coordinates[i].datetime)
.addTo(map);
}
}
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
</script>

Which method is best to pass data from view to controller codeigniter?

I am using codeigniter 3 and I am new for codeigniter. I want to ask that which method is more suitable to pass data from view to controller, using jquery or <form action="controller/method">
I am trying to pass data using jquery but it does not giving any response and no error will be shown. Jquery code is given:
function registration()
{
var txtemail = document.getElementById("email").value;
$.post("<?php echo site_url('Home/registration'); ?>", {checkEmail: txtemail, action: "registerUser"},
function(data) {
var result = data + "";
if (result.lastIndexOf("Success") > -1) {
} else {
var txtUser = document.getElementById("username").value;
var txtContact = document.getElementById("contact").value;
var txtEmail = document.getElementById("email").value;
var txtpincode = document.getElementById("pincode").value;
var txtCity = document.getElementById('city').value;
var txtState = document.getElementById('state').value;
var txtCountry = document.getElementById("country").value;
var txtPackage = document.getElementById("package").value;
var registerMstData = new Array();
registerMstData[0] = txtUser;
registerMstData[1] = txtContact;
registerMstData[2] = txtEmail;
registerMstData[3] = txtpincode;
registerMstData[4] = txtCity;
registerMstData[5] = txtState;
registerMstData[6] = txtCountry;
registerMstData[7] = txtPackage;
$.post("<?php echo site_url('Home/registration') ?>", {pageData: registerMstData, action: "save"},
function(data) {
var result = data + "";
window.alert(result);
})
.fail(function(req, status, err) {
console.error('Error : ' + err + " status : " + status + " request " + req.toString());
alert('Error : ' + err + " status : " + status + " request " + req.toString());
});
}
});
}
What I am doing wrong I don't understand? Please help.
I personally think that AJAX should be used for displays updates and form submissions should be done via a page reload.
a form submission is synchronous and it reloads the page.
an ajax call is asynchronous and it does not reload the page.
It all depends on how you want it to be
Update
For ajax, you can use
$.ajax({
url: 'your url',
data: {
format: 'json'
},
error: function(err) {
// handle error here
},
data: yourData
success: function(data) {
// handle success here
},
type: 'POST'
});

unable to call click event in template in angularjs directive

In have one common directive which will display in each and every page. Already visited page displaying as a done, So i want click event on already visited page. I added ng-click and wrote function in controller. Can anybody help why it's not working.
html
<div class="row">
<div class="col-sm-12">
<wizard-menu currentPage="searchOffering"></wizard-menu>
</div>
</div>
js
function generateMenuHtml(displayMenuItems, currentPage, businessType) {
var htmlOutput = '';
var indexOfCurrentPage = getIndexOf(displayMenuItems, currentPage, 'pageName');
if (businessType) {
htmlOutput += '<ol class="wizard wizard-5-steps">';
} else {
htmlOutput += '<ol class="wizard wizard-6-steps">';
}
angular.forEach(displayMenuItems, function (value, key) {
var htmlClass = '';
if (indexOfCurrentPage > key) {
htmlClass = 'class="done" ng-click="goToFirstPage()"';
} else if (key === indexOfCurrentPage) {
htmlClass = 'class="current"';
} else {
htmlClass = '';
}
if (key!==1){
htmlOutput += '<li ' + htmlClass + '><span translate="' + value.title + '">' + value.title + '</span></li>';
}
});
htmlOutput += '</ol>';
return htmlOutput;
}
.directive('wizardMenu',['store','WIZARD_MENU', 'sfSelect', function(store, WIZARD_MENU, Select) {
function assignPageTemplate(currentPageValue){
var storage = store.getNamespacedStore(WIZARD_MENU.LOCAL_STORAGE_NS);
var data=storage.get(WIZARD_MENU.LOCAL_STORAGE_MODEL);
var businessTypePath='offeringFilter.businessType.masterCode';
var businessTypeValue = Select(businessTypePath, data);
if(businessTypeValue!=='' && businessTypeValue==='Prepaid'){
template = generateMenuHtml(businessTypePrepaid, currentPageValue, true);
}
else{
template = generateMenuHtml(commonMenu, currentPageValue, true);
}
return template;
}
return {
require: '?ngModel',
restrict: 'E',
replace: true,
transclude: false,
scope: {
currentPage: '='
},
controller: ['$scope', '$state', '$stateParams', function($scope, $state, $stateParams) {
$scope.goToFirstPage = function() {
console.log('inside First Page');
};
}],
link: function(scope,element,attrs){
element.html(assignPageTemplate(attrs.currentpage));
},
template: template
};
}])
I'm unable to call goToFirstPage(). Can anybody tell what is wrong here.
Thanks in advance....
You need to compile the template. If you use Angular directive such as ng-click and you simply append them to the DOM, they won't work out of the box.
You need to do something like this in your link function:
link: function(scope,element,attrs){
element.append($compile(assignPageTemplate(attrs.currentpage))(scope));
},
And don't forget to include the $compile service in your directive.
Hope this helps, let me know!
Documentation on $compile: https://docs.angularjs.org/api/ng/service/$compile

Edit JSON Response in AngularJS and bind to the list

Hi I know how to read form json and bind the output to the view however I would like to add some logic into the output and bid converted data. How do I output my forEach to the array and than do ng-repeat based on it or combine my ajax data binding with my amendments?
At the moment if I change
$scope.fleet = newData; => $scope.fleet = data;
and view.html eg. {{item.name}} everything works but I would like to add some changes to the name before binding.
My code:
controler.js
function LoadFleetControler($scope){
$.ajax({
url: 'https://someapi/list',
type: 'GET',
dataType: 'json',
success: function (data) {
var newData = [];
angular.forEach(data, function(value, key){
/* ############################ Options ############################ */
var d = new Date();
var month = d.getMonth() + 1;
var thisDate = d.getDate() + '/' + padLeft(month,2) + '/' + d.getFullYear();
var thisCycle = dateToDays(thisDate, value.end_bill_date) + 1; // Include last 24H
/* ############################ Scope ############################ */
$scope.fleetUser = value.name;
$scope.fleetCycle = 'Cycle: ' + thisCycle + ' days left (' + value.end_bill_date + ')';
$scope.fleetPercentageUsed = value.percentage_used;
$scope.fleetCycleColor = highlighSwitch(value.percentage_used);
}, newData);
console.log(newData);
$scope.fleet = newData;
$scope.$apply();
},
error: function(data) {
$scope.error = true;
$scope.$apply();
}
});
}
view.html
<div ng-controller="LoadFleetControler">
<ons-list>
<ons-list-item ng-show="error">Server Connection Error</ons-list-item>
<ons-list-item class="topcoat-list__item__line-height" ng-repeat="item in fleet">
{{fleetUser}}
<small>{{fleetCycle}}</small>
</ons-list-item>
</ons-list>
</div>
Inside angular.forEach(), you are assigning items to the scope, when you probably meant to create new objects and add them to the newData array...
angular.forEach(data, function(value, key){
// ...
var newItem = {};
newItem.fleetUser = value.name;
newItem.fleetCycle = 'Cycle: ' + thisCycle + ' days left (' + value.end_bill_date + ')';
newItem.fleetPercentageUsed = value.percentage_used;
newItem.fleetCycleColor = highlighSwitch(value.percentage_used);
newData.push(newItem);
}
);

jQuery - google chrome won't get updated textarea value

I have a textarea with default text 'write comment...'. when a user updates the textarea and clicks 'add comment' Google chrome does not get the new text. heres my code;
function add_comment( token, loader ){
$('textarea.n-c-i').focus(function(){
if( $(this).html() == 'write a comment...' ) {
$(this).html('');
}
});
$('textarea.n-c-i').blur(function(){
if( $(this).html() == '' ) {
$(this).html('write a comment...');
}
});
$(".add-comment").bind("click", function() {
try{
var but = $(this);
var parent = but.parents('.n-w');
var ref = parent.attr("ref");
var comment_box = parent.find('textarea');
var comment = comment_box.val();
alert(comment);
var con_wrap = parent.find('ul.com-box');
var contents = con_wrap .html();
var outa_wrap = parent.find('.n-c-b');
var outa = outa_wrap.html();
var com_box = parent.find('ul.com-box');
var results = parent.find('p.com-result');
results.html(loader);
comment_box.attr("disabled", "disabled");
but.attr("disabled", "disabled");
$.ajax({
type: 'POST', url: './', data: 'add-comment=true&ref=' + encodeURIComponent(ref) + '&com=' + encodeURIComponent(comment) + '&token=' + token + '&aj=true', cache: false, timeout: 7000,
error: function(){ $.fancybox(internal_error, internal_error_fbs); results.html(''); comment_box.removeAttr("disabled"); but.removeAttr("disabled"); },
success: function(html){
auth(html);
if( html != '<span class="error-msg">Error, message could not be posted at this time</span>' ) {
if( con_wrap.length == 0 ) {
outa_wrap.html('<ul class="com-box">' + html + '</ul>' + outa);
outa_wrap.find('li:last').fadeIn();
add_comment( token, loader );
}else{
com_box.html(contents + html);
com_box.find('li:last').fadeIn();
}
}
results.html('');
comment_box.removeAttr("disabled");
but.removeAttr("disabled");
}
});
}catch(err){alert(err);}
return false;
});
}
any help much appreciated.
I believe you should be using val() and not html() on a textarea.
On a side note, for Chrome use the placeholder attribute on the textarea. You won't need a lot of this code.
<textarea placeholder="Write a comment"></textarea>