Backbone - rest POST service is called more than once - ajax

I have a problem when I call a REST service by POST to updates tables in MySQL.
I'm working with BackboneJS and when click Save button, call the service and passed POST parameters
$.ajax({
type: 'POST',
url: rootURL,
data: dataJson, //data send to REST service by POST
cacheControl: "no-cache",
dataType: "json",
success: function(data){
console.log("OK");
},
error: function(data){
console.log(data.msg);
}
});
But the problem occurs when income and leave the editing screen. Assuming I made a change and it worked perfectly bringing me back a single "OK", when I go back into the editing screen and record again, I get twice the word "OK".
If I repeat this step to enter and exit the screen edition, duplicate responses are based on the number of times into the screen edition.
I don't know if it's a problem about I'm doing wrong with BackboneJS...?? I'm doing this:
editAdverts: function(){
var editAdvertsView = new EditAdvertsView ();
$('#container-page').append(editAdvertsView.render(idAdverts).el);
}
It can also be a topic of AJAX?
I hope someone can help me with this issue because I am not an expert in BackboneJS
Thanks a lot!
Diego

It's hard to tell without more code but I'm pretty sure it's because you are creating a model each time you are using editAdvert.
Instead of creating a model each time just create one at the init of your view then call the fetch/save function anytime you need an update. Creating the model once is enough.
edit: zombies views is a good thing to check too as brent noticed in comment, we can't tell without more code.

This is de code about route:
var Index = {
start: function() {
var list_view = new MainView();
}
};
var AppRouter = Backbone.Router.extend ({
routes: {
'goAdvert' : 'goAdvert'
},
goAdvert: function(){
var viewAdvertsView = new ViewAdvertsView();
$('#container-page').append(viewAdvertsView.render().el);
}
});
var MainView= Backbone.View.extend({
el: $('#contenedor-body'),
initialize: function() {
this.render();
},
render: function() {
// here is the code about main page. It's not important!
},
});
new AppRouter;
Index.start();
Backbone.history.start();
This is the viewAdvertsView.js
define([
'jquery',
'underscore',
'backbone',
'jqueryuniform',
'bootstrap',
'handlebars',
'jqueryDataTables',
'dtBootstrap',
'../../view/editAdvertsView',
], function($, _, Backbone, jqueryuniform, Bootstrap, Handlebars, JQueryDataTables, DtBootstrap, EditAdvertsView){
var viewAdverts = Backbone.View.extend({
events: {
'click #edit' : 'editAdvert'
}
editAdvert: function(){
$('#container-page').empty();
var idAdvert = $(event.target).data('id');
editAdvertView = new EditAdvertsView();
$('#container-page').append(editAdvertView.render(idAdvert).el);
},
render: function() {
// load viewAdverts
}
});
return viewAdverts;
}
);
And this is editAdvertsView.js
define([
'jquery',
'underscore',
'backbone',
'jqueryuniform',
'bootstrap',
'handlebars',
'jqueryDataTables',
'functions',
'sessionManage',
'slimscroll',
'jqueryCustomSlimscroll',
'slimscrollMin',
'jqueryblockui',
'text!../../html/editAdverts.html',
'maps',
'fancybox'
], function($, _, Backbone, jqueryuniform, Bootstrap, Handlebars, JQueryDataTables,
Functions, SessionManage, Slimscroll, JqueryCustomSlimscroll, SlimscrollMin,
Jqueryblockui, EditAdverts, Maps, Fancybox){
var Advert= Backbone.View.extend({
el: $('#container-page'),
events: {
'click #saveChanges' : 'doSaveChanges'
},
doSaveChanges: function(){
var data = null;
var rootURL = "http://localhost/php/slim/slim/advert/update" + "?date=" + $.now();
dataJson = {
id: $("#id").val(),
product: $("#product").val(),
price: $("#price").val(),
client: $("#client").val(),
country: $("#country").val(),
tel: $("#telephone").val(),
cel: $("#cellphone").val()
};
$.ajax({
type: 'POST',
url: rootURL,
data: dataJson,
cacheControl: "no-cache",
dataType: "json",
success: function(data){
console.log("OK");
error: function(data){
console.log(data.msg);
}
}
},
render: function(codInmueble) {
var self = this;
var editTemplate = Handlebars.compile(EditAdverts);
self.$el.html(editTemplate());
return this;
}
});
return Advert;
}
);

Related

XMLHTTPRequest dealing with event

I am performing an Ajax (JQuery) request on a php script which iterates. At each iteration I do an "echo" of the value of the loop counter, encoded in JSon. The goal is to manage the display of a progress bar.
By doing this I hoped to intercept and retrieve each of the counter values in a separate response thanks to the "progress" event.
Actually I only have one answer which contains all the counter values.
My research always leads me to information about downloading files, which is not my situation.
Maybe I should use the "onreadystatechange" event, but I don't see how to fit it into my code: $ Ajax parameter or separate function?
If anyone has an idea to solve my problem.
Here is my JS code
function DiffuseOffre(envoi, tab, paquet, dest) {
//$('#cover-spin').show(0);
$("#xhr-rep").css("display", "block");
var server = '/Admin/Offres/DiffuseOffre.php';
$.ajax({
url: server,
type: 'Post',
dataType: 'json',
data: {
envoi: envoi,
tab: tab,
paquet: paquet,
dest: dest
},
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var compteur = evt.text;
$("#xhr-rep").html(compteur);
}
}, false);
return xhr;
},
success: function(msg) {
//$('#cover-spin').css("display", "none");
$('#xhr-rep').css("display", "none");
if (msg.hasOwnProperty('erreur')) {
$("#dialog-erreur").html(msg.erreur);
$("#dialog-erreur").dialog("open");
$("#dialog-erreur").dialog({
width: '600px',
title: msg.title
})
} else {
$("#dialog-message").html(msg.message);
$("#dialog-message").dialog("open");
$("#dialog-message").dialog({
width: '600px',
title: msg.title
})
if (paquet == 1) {
$("#envoi_" + dest).remove();
$("#diffuser").remove();
}
if (msg.hasOwnProperty('encours')) {
$("#en_cours").html(msg.encours);
}
if (msg.hasOwnProperty('fieldset')) {
$("#" + msg.fieldset).remove();
}
}
}
})
}

ajax self invoked function to vue data

I'm trying to use a self invoked function to do an ajax call.
Later I want to use the response to populate a data property inside Vue, but for some reason I'm not able to do that.
Here is my code so far
//chiamata Ajax a servizio
var getData = (function(){
var req = $.ajax({
type:'get',
url:'https://api.myjson.com/bins/a8ohr',
dataType: 'json',
success: function(response)
{
result =JSON.parse(response);
}
});
return {
getResponse:function(){
return req.success;
}
}
}());
var modello = getData.getResponse();
My goal is to pass modello as data in Vue.
Here the VUE:
var Metromappa = new Vue({
el: '#metromappa',
data: {
modello:modello
},
methods:{
},
beforeMount(){
this.modello = modello;
}
})
What have I done wrong?
Instead you can perform the ajax call in the created() lifecycle hook and set the data property modello to the response there like this:
var Metromappa = new Vue({
el: '#metromappa',
data: {
modello:null
},
methods:{
},
created(){
var self = this;
$.ajax({
type:'get',
url:'https://api.myjson.com/bins/a8ohr',
dataType: 'json',
success: function(response){
self.modello = response;
}
});
},
})
Here is the jsFiddle
If you want to seperate the logic:
var getData = function(){
return $.ajax({
type:'get',
url:'https://api.myjson.com/bins/a8ohr',
dataType: 'json',
success: function(response){
console.log(response);
}
});
};
var Metromappa = new Vue({
el: '#metromappa',
data: {
modello:null
},
methods:{
},
beforeMount(){
var self = this;
getData().then(function(response){
self.modello = response;
}, function(error){});
}
})
here is the updated fiddle
thanks to Bert Evans for pointing out my mistake

Not seeing post data in node server

While making below ajax call, I am not seeing any post data in node server side.
$.ajax({
type: "POST",
url: window.location.origin + "/api/books",
data: {
title: "Javascript some good partd",
author: "Douglas crockford",
releaseDate: new Date(2013, 4, 2).getTime()
},
dataType: "json",
success: function(data) {
console.log(data);
}
});
After doing some search, I found out it could be because of body-parser configuration but unable to get it right. Please find below the node server configuration.
app.configure( function() {
app.use(bodyParser());
app.use(bodyParser.urlencoded());
app.use(bodyParser.json());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(application_root, 'site')));
app.use(express.errorHandler({dumpExceptions: true, showStack: true}));
});
And API call is:
app.post('/api/books', function (req, res) {
console.log(req.body);
var book = new BookModel({
title: req.body.title,
author: req.body.author,
releaseDate: req.body.releaseDate
});
return book.save(function (err, response) {
if (!err) {
return res.send(book);
} else {
console.log(err);
}
});
});
req.body is logged as undefined. Can anyone please help on debugging the issue?
Drop the app.configure function.
All the code inside of it can be left floating in that file.
My best guess would be that its not firing off that function.
I tend to use this code
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));

How to fadIn with ajax request?

I've this code, i'd like to replace the 'ul.hello-list' content with the answer datas. I'm trying
$.ajax({
type: "POST",
url: "home/hello.php",
data: {
"action": "hello_action"
},
success: function(datas) {
if (datas) {
$("ul.hello-list").fadeOut();
// It doesn't work
datas.fadeIn();
}
}
});
Thxs
So from your comment, I believe you can do:
success: function(datas) {
if (datas) {
var $newContent = $(datas).hide();
var $oldList = $("ul.hello-list");
var $container = $oldList.parent(); // Replace this with whatever your container is
$oldList.fadeOut();
$newContent.appendTo($container).fadeIn();
}
}
The issue is that datas is not inherently a jQuery object, so you cannot call jQuery functions on it. Furthermore, it needs to be attached to the DOM before it can be faded in.

Kendo UI reload treeview

I load a complex treeview with kendo ui via ajax because I need to load the tree with one request (works fine):
$(document).ready(function() {
buildTree();
});
function buildTree(){
$.getJSON("admin_get_treedata.php", function (data) {
$("#treeview").kendoTreeView({
select: function(item) { editTreeElement(item,'tree'); },
dataSource: data
});
})
}
If I try to reload the complete tree after changing some data via ajax the new build tree does not work correct and does not update the text.
$.ajax({
type: 'POST',
url: 'ajax/ajax_update_layer.php',
data: {
layerid:id,
...
},
success: function(data){
buildTree();
}
});
What can Ido?
Thanks
Sven
try this on ajax success callback
var data = $("#treeView").data('kendoTreeView');
data.dataSource.read();
I got mine to work.
This is what I did:
Function that creates the tree view:
function CreateNotificationTree(userId)
{
var data = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/notifications/byuserid/" + userId,
contentType: "application/json"
}
},
schema: {
model: {
children: "notifications"
}
}
});
$("#treeview").kendoTreeView({
dataSource: data,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["notificationType", "NotificationDesc"],
select: treeviewSelect
});
function treeviewSelect(e)
{
var $item = this.dataItem(e.node);
window.open($item.NotificationLink, "_self");
}
}
Modification & data source refresh:
$('#btnDelete').on('click', function()
{
var treeView = $("#treeview").data("kendoTreeView");
var userId = $('#user_id').val();
$('#treeview').find('input:checkbox:checked').each(function()
{
var li = $(this).closest(".k-item")[0];
var notificationId = treeView.dataSource.getByUid(li.getAttribute('data-uid')).ID;
if (notificationId == "undefined")
{
alert('No ID was found for one or more notifications selected. These notifications will not be deleted. Please contact IT about this issue.');
}
else
{
$.ajax(
{
url: '../api/notifications/deleteNotification?userId=' + userId + '&notificationId=' + notificationId,
type: 'DELETE',
success: function()
{
CreateNotificationTree(userId);
alert('Delete successful.');
},
failure: function()
{
alert('Delete failed.');
}
});
treeView.remove($(this).closest('.k-item'));
}
});
});
Hope that helps.

Resources