XMLHTTPRequest dealing with event - ajax

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

Related

jQuery.ajax request progress bar

Okay, this is the same post as my last post which got downvoted and marked as duplicate. Here's the post again but now with the explaination why the questions from What is the cleanest way to get the progress of JQuery ajax request? didn't work.
I have an AJAX request in where I insert stuff in the database and send 2
emails. I'd like to show the progress of the AJAX request.
Currently I tried:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.addEventListener('progress', function(e) {
if (e.lengthComputable) {
$('title').html((100 * e.loaded / e.total) + '%');
}
});
return xhr;
},
complete: function() { /*here some stuff*/ }
});
However, it doesn't change the title during the request, but after the request it sets it to 100%. Is there any way I can get what I want? So that when 50% in the AJAX file is executed it shows 50% and does the progress like that.
The next thing I tried is:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
chunking: true,
xhr: function() {
var xhr = new window.XMLHttpRequest();
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('title').html(percentComplete);
//Do something with upload progress here
}
}, false);
xhr.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
$('title').html(percentComplete);
//Do something with download progress
}
}, false);
return xhr;
},
complete: function (result){}});
However then I only get a 1 in the title, and immediately when I click my button and the AJAX gets called.
Last, I tried the second answer:
$.ajax({
type: 'POST',
url: '/ajax/submit_order_form.php',
data: form_data,
chunking: true,
complete: function (result) {}
}).progress(function(e, part) {
console.log(part);
}).progressUpload(function()
{
});
However this gives:
jq-ajax-progress.min.js:1 Uncaught TypeError: Cannot read property 'upload' of undefined
at Function.e.ajax (jq-ajax-progress.min.js:1)
at a.validator.submitOrderForm (checkout.js:108)
at d (jquery.validate.min.js:4)
at HTMLFormElement.<anonymous> (jquery.validate.min.js:4)
at HTMLFormElement.dispatch (jquery.min.js:3)
at HTMLFormElement.r.handle (jquery.min.js:3)
I tried a lot of things already but none seem to work.

Ext.Msg.show in ajax not append the page

I have a function for saving data. Before saving data there is dialog confirmation Yes or No. While I click option Yes the page behind this is back to the gridview (it's list). What i want is while click Yes the page behind is not change.
This is my function :
function SaveData(StatusSubmit) {
var d = ControlToData();
if (state == FormState.ADD) {
ShowLoading("sa-body", "Updating data .. Please Wait ...");
$.ajax({
url: root + "PF/Add?status=" + StatusSubmit,
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(d),
success: function (result, status, xhr) {
storePF.add(
{
PFID: result.PF.PFID
, Title: result.PF.Title
});
ChangeFormState(FormState.VIEW);
tabs.setActiveTab('pageGrid');
if (result.ErrorMail.length > 0) {
alert("Error while sending email !\nError description : " + result.ErrorMail + "\nPlease contact your System Administrator !");
}
if (result.Error.length > 0) {
var str = "<br/><br/><span style='color:red;font-weight:bold'>Success add new PF !</span>";
MsgBox2("Budget Validation", result.Error + str);
}
else
MsgBox("Success add new PF !");
},
complete: function () {
HideLoading();
}
});
}
}
I add new dialog confirmation like this, but it does not work (didn't append the page after click Yes button):
function SaveData(StatusSubmit) {
var d = ControlToData();
if (state == FormState.ADD) {
ShowLoading("sa-body", "Updating data .. Please Wait ...");
$.ajax({
url: root + "PF/Add?status=" + StatusSubmit,
type: 'POST',
dataType: "json",
contentType: 'application/json',
data: JSON.stringify(d),
success: function (result, status, xhr) {
storePF.add(
{
PFID: result.PF.PFID
, Title: result.PF.Title
});
ChangeFormState(FormState.VIEW);
tabs.setActiveTab('pageGrid');
if (result.ErrorMail.length > 0) {
alert("Error while sending email !\nError description : " + result.ErrorMail + "\nPlease contact your System Administrator !");
}
if (result.Error.length > 0) {
$.post(root + "PF/GetSetupName", function (datas) {
if (datas == "FILTER_BRAND") {
Ext.Msg.show({
title: 'Over Budget',
msg: 'Budget is over. Modify or Not ?',
fn: function (btn) {
if (btn == "yes") {
SaveData("none");
}
else {
CancelData();
}
},
buttons: Ext.Msg.YESNO,
icon: Ext.Msg.QUESTION
});
}
});
}
else
MsgBox("Success add new PF !");
},
complete: function () {
HideLoading();
}
});
}
}
I try also separate this Ext.Msg.show in another function. but it doesn't work. Is there any idea please ?
I've found that when I try to do a mask and an ajax request at the same time, Ext gets overwhelmed and will not properly display the mask.
To fix this, I delay doing my ajax request until Ext & the browser have had enough time to properly display the mask. It generally does not need much time. In the example below, it waits 50 ms before posting.
Ext.get(document.body).mask("Updating data .. Please Wait ...", 'x-mask-loading');
Ext.defer(function() {
Ext.Ajax.request({ ... });
}, 50);
This gives the browser enough time to render the masking before it has to do anything else.

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.

BlockUI Ajax loading wrong moment

I know there's other post about this. but there's no answer.
Situation, I have an ajax command. It take time because I have somes things to get.
I want to include a loading between the execution of the ajax.
I want to use jquery BlockUI because its simple and good looking.
But I dont know why the visual effect not working until ajax load the entire data(like when "success" begin).
I try multiple way but not working.
here's my last code :
function from http://www.codeproject.com/Articles/382390/An-Example-to-Use-jQuery-Global-AJAX-Event-Handler
var AjaxGlobalHandler = {
Initiate: function(options) {
$.ajaxSetup({ cache: false });
// Ajax events fire in following order
$(document).ajaxStart(function() {
$.blockUI({
message: options.AjaxWait.AjaxWaitMessage,
css: options.AjaxWait.AjaxWaitMessageCss
});
}).ajaxSend(function(e, xhr, opts) {
}).ajaxError(function(e, xhr, opts) {
if (options.SessionOut.StatusCode == xhr.status) {
document.location.replace(options.SessionOut.RedirectUrl);
return;
}
$.colorbox({ html: options.AjaxErrorMessage });
}).ajaxSuccess(function(e, xhr, opts) {
}).ajaxComplete(function(e, xhr, opts) {
}).ajaxStop(function() {
$.unblockUI();
});
}
};
call ready
var options = {
AjaxWait: {
AjaxWaitMessage: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>',
AjaxWaitMessageCss: { backgroundColor: '#ffffff' }
},
AjaxErrorMessage: "<h6>Erreur!/h6>"
};
AjaxGlobalHandler.Initiate(options);
call execution
$.ajax({
type: "POST",
url: location.href.split('/').pop() + "?action=" + actionName + "&recherche=" + recherche,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
FillDataGridOnSuccess(response, gridId, dataTypeName);
},
error: function(xhr, ajaxOptions, thrownError) {
alert("xhr.status : " + xhr.status);
alert("thrownError : " + thrownError);
}
});
I try also
var ajaxSettings = function(options) {
return $.extend(
{
beforeSubmit: function() {
//beforeSend: function() {
$.blockUI({ overlayCSS: { backgroundColor: '#ffffff' },
message: '<h1 class="ui-overlay-loading-content"><img class="ui-overlay-loading-image" src="_inc/img/loading3circle1.gif" />Chargement des données ...</h1>'
});
},
complete: function() {
$.unblockUI();
}
},
options
);
};
Every test that I did end with a loading who seems to only appear on ajaxSuccess.
I know there's sample on official blockUI site http://jquery.malsup.com/block/#demos
and they working there, but I cant on my own. did anybody see why?
tank you

JSON, jQueryUI Autocomplete, AJAX - Cannot get data when array is not local

I have searched stackoverflow, as well as the web for some insight into how to get the jQueryUI Autocomplete plugin working with my JSON data, and I'm at a loss. I had it working like a charm with a local data array. I was able to pull values and build html.
I ran into a problem when I had to pull JSON form this source:
/Search/AjaxFindPeopleProperties2
?txtSearch=ca pulls up the test data that I am trying to loop through, when I type in 'ca' to populate the autocomplete list. One of the problems is that ?term=ca is appended to the url instead of ?txtSearch=ca and I'm not sure how to change it.
This is an example of the data:
{
"MatchedProperties": [
{
"Id": 201,
"Name": "Carlyle Center",
"Description": "Comfort, convenience and style are just a few of the features you'll ...",
"ImageUrl": "/Photos/n/225/4989/PU__ThumbnailRS.jpg"
}
]
}
...and here is the ajax call I'm trying to implement:
$(document).ready(function () {
val = $("#txtSearch").val();
$.ajax({
type: "POST",
url: "/Search/AjaxFindPeopleProperties2",
dataType: "json",
data: "{}",
contentType: "application/json; charset=utf-8",
success: function (data) {
$('#txtSearch').autocomplete({
minLength: 0,
source: data.d, //not sure what this is or if it's correct
focus: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
$.widget("custom.catcomplete", $.ui.autocomplete, {
//customize menu item html here
_renderItem: function (ul, item) {
return $("<li class='suggested-search-item" + " " + currentCategory + "'></li>")
.data("item.autocomplete", item)
.append($("<a><img src='" + item.MatchedProperties.ImageUrl + "' /><span class='name'>" + item.MatchedProperties.Name + "</span><span class='location'>" + "item.location" + "</span><span class='description'>" + item.MatchedProperties.Description + "</span></a>"))
.appendTo(ul);
},
_renderMenu: function (ul, items) {
var self = this,
currentCategory = "Properties Static Test Category";
$.each(items, function (index, item) {
if (item.category != currentCategory) {
ul.append("<li class='suggested-search-category ui-autocomplete-category'>" + currentCategory + "</li>");
//currentCategory = item.category;
}
self._renderItem(ul, item);
});
}
}//END: widget
//return false;
},
select: function (event, ui) {
$('#txtSearch').val(ui.item.MatchedProperties.Name);
//$('#selectedValue').text("Selected value:" + ui.item.Abbreviation);
return false;
}
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
}); //END ajax
}); //END: doc ready
and I'm initializing here:
<script type="text/javascript">
//initialize autocomplete
$("#txtSearch").autocomplete({ //autocomplete with category support
/*basic settings*/
delay: 0,
source: "/Search/AjaxFindPeopleProperties2",
autoFocus: true,
minLength: 2 //can adjust this to determine how many characters need to be entered before autocomplete will kick in
});
//set auto fucus
$("#txtSearch").autocomplete("option", "autoFocus", true);
</script>
any help would be great...
Thanks!

Resources