I am new to AJAX and trying to build a dropdown-meny from a XML-file.
With my example I'm only getting "Akershus" to post in the menu.
Can anyone help me with this?
Best regards, a student from Norway.
Here is the XML:
<arrangement>
<fylke name="Akershus">
<fylke name="Buskerud">
<fylke name="Hordaland">
<fylke name="Nordland">
</arrangement>
Here is the script:
$(document).ready( function() {
arrangementer();
fetch();
});
/*function fetch() {
setTimeout( function() {
arrangementer();
fetch();
}, 100);
}*/
function arrangementer() {
$.ajax({
url: "arrangementer.xml",
dataType: "xml",
success: function(data) {
$('ul').children().remove();
$(data).find("arrangement").each( function() {
var info = ''+$(this).find("fylke").attr("name")+'';
$('ul').append(info);
});
},
error: function() { $('ul').children().remove();
$('ul').append("<li>There was an error!</li>"); }
});
}
Instead of
$(data).find("arrangement").each
use
$(data).find("arrangement fylke").each
And remove .find("fylke").
Or you could do this even more succinctly (and with proper escaping),
$(data).find('arrangement fylke').map(function() {
return $('').text($(this).attr('name'));
}).appendTo('ul');
Related
Good day, I am trying to manual ajax this
Add to cart
What this does is, It will add to the cart the one-time purchase option from the woocommerce subscription. I am trying to ajax it so it won't refresh the page when you click on it.
I found an idea how to manually ajax it by using these lines of codes. Reference here
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
$thisbutton.removeClass('added').addClass('loading');
},
complete: function(response) {
$thisbutton.addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);
The codes above work and it does ajax however, it displays the monthly subscription, not the one-time purchase. It should display the one-time purchase because of the &convert_to_sub_55337=0 which means the one-time subscription option is selected.
Also, I am getting an error after clicking the button on the console log
Uncaught TypeError: $button is undefined
I am a newbie to handling ajax so I am unsure about the issue
Thank you in advance!!
you can try this code i hope it will helped.
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
jQuery('.testing').removeClass('added').addClass('loading');
},
complete: function(response) {
jQuery('.testing').addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);
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 + '¬ificationId=' + notificationId,
type: 'DELETE',
success: function()
{
CreateNotificationTree(userId);
alert('Delete successful.');
},
failure: function()
{
alert('Delete failed.');
}
});
treeView.remove($(this).closest('.k-item'));
}
});
});
Hope that helps.
I have this code where I load an XML file through AJAX:
$("#list").on("click", "li", function (event) {
$.ajax({
url: 'test.xml',
type: "get",
context: this,
success: function (data) {
alert("success");
},
error: function () {
alert("failure");
}
});
})
The issue is that I have a long list of clickable elements that use this code which is not very efficient. Is there a way to call AJAX function once and then use the data produced for other items on the list?
Just save the return value somewhere
$("#list").on("click", "li", function (event) {
var data = $("#list").data('test');
if (data){
//use data
}
else{
$.ajax({
url: 'test.xml',
type: "get",
context: this,
success: function (data) {
$("#list").data('test', data);
// use data
alert("success");
},
error: function () {
alert("failure");
}
});
}
})
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
I cannot figure out how to merge the following separate pieces of code:
$(document).ready(function () {
$("#signupForm").validate();
});
and
$(document).ready(function () {
$("#btnSignup").click(function () {
$.ajax({
type: "POST",
dataType: 'json',
url: "/Newsletter/Signup",
data: $('#signupForm').serialize(),
success: function (response) {
if (response.success) {
$('#signupMessage').show(0);
}
else {
showValidationErrors(response.Data);
}
}
});
return false;
});
I need the first part to execute first, and if it validates the form successfully, then I need to exectute the second part.
I believe that you can use valid().
Pseudo code;
$(document).ready(function () {
$("#signupForm").validate();
$("#btnSignup").click(function () {
if ($("#signupForm").valid()) {
// ajax query
}
return false;
});
});
Does that work? I haven't checked it.
Here is a somewhat general way I use.
$('form').submit(function(e){
if (!$(e.target) && !$(e.target).valid()) {
return;
}
// Ajax call here.
$.ajax({ type: "POST",... });
});
Lastly, you could abstract the logic into an object for a more OOP approach
var formHandler = {
onSubmit: function(e){
if (!$(e.target) && !$(e.target).valid()) {
return;
}
// Ajax call here.
$.ajax({ type: "POST",... });
}
}
$('form').submit(formHandler.onSubmit);