How to fadIn with ajax request? - ajax

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.

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();
}
}
}
})
}

MVC partial view update from ajax success

On the main page in the view the user selects a project and that selection fills up a partial view (call it first partial) with data. In this partial view the user can also select an item which provides an editing partial view under below the previous one. Here a new item can be added, updated or deleted.
The question is: when a new item added the first partial view should be updated. The method how I am trying to achieve it is like this:
function addBottle() {
var code = $("#Code").val();
var desc = $("#Description").val();
var id = $("#ProjectId").val();
$.ajax({
url: "#Url.Action("AddBottleType", "Managers")",
data: { code: code, desc: desc, id: id },
type: "POST",
datatype: "text",
success: function (data) {
if (typeof data == "undefined") {
alert("Something went wrong. Sorry!");
}
if (data.Success) {
$.alert(data.Data, "Success!");
$.ajax({
url: "#Url.Action("BottleTypes", "Managers")",
data: { projectId: id },
type: "GET",
datatype: "text",
});
} else {
$.alert(data.Data, "Warning!");
}
}
});
};
This gives me the data in the controller, but the view is not updated. Probably this is not the best way, I am open the suggestions, solutions.
I've also done my part, google and stackoverflow is my friend, but none of the solutions worked.
You need to load it into your div. Something like this. Check for success in your controller action so you need not do Success() in the front end:
function addBottle() {
var code = $("#Code").val();
var desc = $("#Description").val();
var id = $("#ProjectId").val();
$.ajax({
url: "#Url.Action("AddBottleType", "Managers")",
data: { code: code, desc: desc, id: id },
type: "POST",
datatype: "text",
success: function (data) {
if (typeof data == "undefined") {
alert("Something went wrong. Sorry!");
}
if (data.Success) {
$.alert(data.Data, "Success!");
$("#bottleTypes").load("/Managers/BottleTypes", { projectId: id });
} else {
$.alert(data.Data, "Warning!");
}
}
});
};

Backbone - rest POST service is called more than once

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;
}
);

BreezeJs - How to make simultaneous AJAX calls?

I wrote two Ajax calls that request data from stored procedures (in SQL Server), sp_ahtreatmentselect and sp_inventoryselect. Here is how the functions look like in the Breeze controller.
[HttpPost]
[ActionName("getinventories")]
public object GetInventories(HttpRequestMessage request)
{
var data = request.Content.ReadAsFormDataAsync().Result;
var opId = data["operationid"];
string query = "sp_inventoryselect #operationId";
SqlParameter operationId = new SqlParameter("#operationId", opId);
return UnitOfWork.Context().ExecuteStoreQuery<GetInventories>(query, operationId);
}
[HttpPost]
[ActionName("gettreatments")]
public object GetTreatments(HttpRequestMessage request)
{
var data = request.Content.ReadAsFormDataAsync().Result;
var opId = data["operationid"];
string query = "sp_ahtreatmentselect #operationId";
SqlParameter operationId = new SqlParameter("#operationId", opId);
return UnitOfWork.Context().ExecuteStoreQuery<GetTreatments>(query, operationId);
}
Now, on client-side, the Ajax calls look like this:
var ajaxImpl = breeze.config.getAdapterInstance('ajax');
function treatments(id) {
return ajaxImpl.ajax({
type: 'POST',
url: serviceName + '/gettreatments',
data: { operationid: id },
success: function(data) {
console.log('Success!');
},
error: function(error) {
console.log('Error!');
}
});
}
function inventories(id) {
return ajaxImpl.ajax({
type: 'POST',
url: serviceName + '/getinventories',
data: { operationid: id },
success: function (data) {
console.log('Success!');
},
error: function(error) {
console.log('Error!');
}
});
}
return inventories(id).then(treatments(id))
.then(function() {
// Do something
})
.fail(function(error) {
// Display error
});
Both Ajax calls work fine, BUT problem is, // Do something is run BEFORE inventories(id) and treatments(id) are run. I would like it to work the other way around instead. I also tried $.when(inventories(id), treatments(id)).then(...) and $.when(ajaxImpl.ajax(...), ajaxImpl.ajax(...)).then(...), but same problem occurs. How do I solve this?
Thanks in advance.
I realized that the issue lay on synchronous calls, not Breeze. I used queue.js to make Ajax calls and // Do something and the calls are completed. Here is how.
var ajaxImpl = breeze.config.getAdapterInstance('ajax'),
serviceName = 'some/service',
id = 1; // Could be any number
return queue()
.defer(function(callback) {
ajaxImpl.ajax({
type: 'POST',
url: serviceName + '/getinventories',
data: { operationid: id },
success: function (data) {
console.log('Success!');
callback(null, data);
});
})
.defer(function(callback) {
ajaxImpl.ajax({
type: 'POST',
url: serviceName + '/gettreatments',
data: { operationid: id },
success: function (data) {
console.log('Success!');
callback(null, data);
});
})
.awaitAll(function(error, results) {
if (error) {
console.log('Error! ' + error);
} else {
// Do something, given that:
// results[0] are inventories, and
// results[1] are treatments
}
});
I don't know what this has to do with Breeze. Did you get your ajaxImpl from a Breeze ajax adapter? I've looked at both ajax adapters shipped with Breeze and neither of them returns anything from a call to the ajax method!
Accordingly, you're expression should have died immediately with a reference error when it got to the .then in return inventories(id).then(.... I don't see how it could have gotten to \\ do something at all.
Something isn't right with the way you've posed this question.
Once you get beyond this I still don't see how this involves Breeze. Breeze won't do anything with the results of your service requests.
I'm completely flummoxed by your question.

jQuery.ajax() inside a loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
Closed 6 years ago.
If I call jQuery.ajax() inside a loop, would it cause the call in current iteration overwrite the last call or a new XHR object is assigned for the new request?
I have a loop that do this, while from console log I can see requests done 200 ok but just the result data of the last request in the loop is stored by the request success callback as supposed .
the code:
var Ajax = {
pages: {},
current_request: null,
prefetch: function () {
currentPath = location.pathname.substr(1);
if(this.pages[currentPath])
{
var current = this.pages[currentPath];
delete this.pages[currentPath];
current['name']=currentPath;
current['title']=$("title").text().replace(' - '.SITE_NAME, '');
current['meta_description']=$("meta[name=description]").attr('content');
current['meta_keywords']=$("meta[name=keywords]").attr('content');
}
var _Ajax = this;
//the loop in question *****
for(var key in this.pages)
{
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+key,
success: function(data) {
_Ajax.pages[key] = data;
}
});
console.debug(this.pages);
}
if(current)
{
this.pages[currentPath] = current;
}
}
};//Ajax Obj
for(var i in pages)
{
Ajax.pages[pages[i]]={};
}
$(function() {
Ajax.prefetch();
});//doc ready
You'll need a closure for key:
for(var k in this.pages){
(function(key){
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+key,
success: function(data) {
_Ajax.pages[key] = data;
}
});
console.debug(this.pages);
})(k);
}
that way you make sure that key is always the correct on in each ajax success callback.
but other than that it should work
i made a small closure demonstration using timeout instead of ajax but the principle is the same:
http://jsfiddle.net/KS6q5/
You need to use async:false in you ajax request. It will send the ajax request synchronously waiting for the previous request to finish and then sending the next request.
$.ajax({
type: 'POST',
url: 'http://stackoverflow.com',
data: data,
async: false,
success: function(data) {
//do something
},
error: function(jqXHR) {
//do something
}
});
I believe what's happening here has to do with closure. In this loop:
for(var key in this.pages)
{
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+key,
success: function(data) {
_Ajax.pages[key] = data;
}
});
console.debug(this.pages);
}
The variable key is actually defined outside the for loop. So by the time you get to the callbacks, the value has probably changed. Try something like this instead:
http://jsfiddle.net/VHWvs/
var pages = ["a", "b", "c"];
for (var key in pages) {
console.log('before: ' + key);
(function (thisKey) {
setTimeout(function () {
console.log('after: ' + thisKey);
}, 1000);
})(key);
}
I was facing the same situation, I solved using the ajax call inside a new function then invoke the function into the loop.
It would looks like:
function a(){
for(var key in this.pages)
{
var paramsOut [] = ...
myAjaxCall(key,paramsOut);
.......
}
}
function myAjaxCall(paramsIn,paramsOut)
{
$.ajax({
method: 'get',
url:'http://'+location.hostname+'/'+paramsIn[0],
success: function(data) {
paramsOut[key] = data;
}
});
}
This is how I always do a ajax loop..
I use a recursive function that gets called after the xhr.readyState == 4
i = 0
process()
function process() {
if (i < 10) {
url = "http://some.." + i
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
alert(xhr.responseText)
i++
process()
}
}
xhr.send();
} else {
alert("done")
}
}

Resources