How to use alpine js in wordpress ajax request? - ajax

For a wordpress plugin using alpine js, I got an error to access of alpine data :
var data = {
'action' : 'myWPAjaxAction',
'data' : JSON.stringify(this.ui.data)
};
jQuery.post( wp_ajax_object.ajax_url, data, function(response) {
if (response.ok) {
this.ui.submit.state = true; //cannot be found !
this.ui.step = 5;
var iFrame = document.getElementsById("yousign-iframe");
iFrame.appendChild(response.view);
} else {
console.debug(response);
this.ui.submit.state = false;
this.ui.submit.errors = 'no_submit';
}
}).fail(function() {
this.ui.submit.state = false;
this.ui.submit.errors = 'no_submit';
});
With this code inside an alpine function, I got an error :
this.ui is undefined
How can I read/modify alpine data after ajax post request in Wordpress?

Use the arrow function syntax, so this will refer to Alpine.js data object instead of jQuery:
jQuery.post( wp_ajax_object.ajax_url, data, (response) => {
if (response.ok) {
this.ui.submit.state = true;
this.ui.step = 5;
var iFrame = document.getElementsById("yousign-iframe");
iFrame.appendChild(response.view);
} else {
console.debug(response);
this.ui.submit.state = false;
this.ui.submit.errors = 'no_submit';
}
}).fail(() => {
this.ui.submit.state = false;
this.ui.submit.errors = 'no_submit';
});

Related

Jasmine: Expected spy <function> to have been called error

In my angular application, I am trying to write a test case for following scenario but getting error 'Expected spy reinvite to have been called.'. Im testing on "jasmine-core: ^2.5.2 and "karma: ^1.3.0". I have written similar test cases and they passed without error.
In my controller file:
function reinvite() {
var emailsToReInvite = $j.map($scope.settingsData.userSettingsDetails, function(user) {
if(user.reInviteChecked){
return user.email;
}
});
if (emailsToReInvite.length >= 1) {
var invitation = { invitees: emailsToReInvite, listId: listId};
invitation = JSON.stringify(invitation);
inviteCollaboratorsModalDataService.reinvite(invitation).then(
function success(response) {
if(response.data.messages[0].code == 214){
$scope.showReinviteSuccess = true;
}
}else{
$scope.showReinviteSuccess = false;
}
}
);
}
}
And my spec file:
describe('settingsModalController', function() {
var controllerUnderTest = "settingsModalController";
var controllerResolver, rootScope, injector, $scope, inviteCollaboratorsModalDataService
beforeEach(function(){
angular.mock.module('sharedListApp');
inject(function($controller, $rootScope, $injector){
controllerResolver = $controller;
rootScope = $rootScope;
injector = $injector;
});
$scope = rootScope.$new();
inviteCollaboratorsModalDataService = injector.get('uiCommon.inviteCollaboratorsModalDataService');
});
it("should send re-invitation mail to selected users successfully", shouldReinviteSelectedUsers);
function shouldReinviteSelectedUsers() {
var $q = injector.get('$q');
$scope.settingsData = {
userSettingsDetails: [{email: 'abc#xyz.com'}]
};
var data = {
messages: [ { code: 214 }],
invite: {
invitation: $scope.settingsData
}
};
var response = { data: data };
var mockResult = new $q.defer();
mockResult.resolve(response);
spyOn(inviteCollaboratorsModalDataService, 'reinvite').and.returnValue(mockResult.promise);
controllerResolver(controllerUnderTest, { $scope: $scope });
$scope.reinvite();
$scope.showReinviteSuccess = true;
$scope.$apply();
expect(inviteCollaboratorsModalDataService.reinvite).toHaveBeenCalled();
expect($scope.showReinviteSuccess).toBe(true);
}
}
What am i doing wrong or what am i missing? Thanks in advance.
Ok, so i missed one variable to add in $scope.settingsData in my spec file which was why my spec code was not parsing into the first 'if' loop of the controller. Got it working by adding 'reInviteChecked: true' in:
$scope.settingsData = {
userSettingsDetails: [{email: 'abc#xyz.com', reInviteChecked: true}]
};

Ajax function gives Cannot read property 'length' of undefined

This function works fine as long im on the same page where the search div imagesearch is.
If im on another site on the website, ill get the error
Cannot read property 'length' of undefined.
The console point put row 27, that's where the if statement start if(q.length..
Cant really find out whats the problem. Any ideas ?
function reloadSearch() {
if (!isLoading) {
var q = $('#imagesearch').val();
if (q.length >= 2) {
isLoading = true;
$.ajax({
type: 'GET',
url: 'core/flickr.php',
data: 'search=' + q,
dataType: 'html',
beforeSend: function () {
$('#imageresult').html(
'<img src="img/loading45.gif" alt="loading..." />');
if (!q[0]) {
$('#imageresult').html(
'');
return false;
}
},
success: function (response) {
$('#imageresult').html(
response);
}
});
// enforce the delay
setTimeout(function () {
isLoading = false;
if (isDirty) {
isDirty = false;
reloadSearch();
}
}, delay);
}
}
};
var delay = 1000;
var isLoading = false;
var isDirty = false;
$(document).ready(function () {
reloadSearch();
$('#imagesearch').keyup(function () {
isDirty = true;
reloadSearch();
});
});
change:
if (q.length >= 2) {
to
if (q !== undefined && q.length >= 2) {
this will stop the can't read value from undefined...If you code in .Net this is similar to the null reference exception.

IE not reading GET success after POST

I cannot seem to find out why IE does not read my success on get after the post. I have tried cache: false, with no luck. This works in all other browsers, just not IE.
$.ajaxSetup({ cache: false });
num = $('#num').val();
phone = $('#phone').val();
$.post("post.php?"+$("#MYFORM").serialize(), {
}, function(response){
if(response==1 && codeVal == 1 && telVal == 1)
{
$("#after_submit").html('');
$("#Send").after('<label class="success" id="after_submit">Η αποστολή πραγματοποιήθηκε</label>');
change_captcha();
clear_form();
$.ajax({
type:'get',
cache: false,
url: "http://web.somesite/submit_code.php",
dataType: 'html',
data:{ user: "one", pass: "mtwo", source: "WEB", receipt: num, msisdn: phone},
success: function(data) {
var qsFull = "http://web.somesite.gr/submit_code.php?" + data;
var qs = URI(qsFull).query(true);
TINY.box.show({html:qs.message,animate:false,boxid:'error',top:5});
}
});
}
else
{
$("#after_submit").html('');
$("#Send").after('<label class="error" id="after_submit">Error! in CAPTCHA .</label>');
}
});
OK, I tried adding an error after the success and I see that I get my pop up as I should be, but the value of qs.message is 0. Why would I get error and not success, when it is successful in other browsers.
I found the answer, It has to do with IE not being flexible with cross domains and such, so I added a XDomainRequest like so
if (jQuery.browser.msie && window.XDomainRequest) {
var xdr = new XDomainRequest();
var my_request_data = { user: "M1web", pass: "m!", source: "WEB", receipt: num, msisdn: phone};
my_request_data = $.param(my_request_data);
if (xdr) {
xdr.onerror = function () {
alert('xdr onerror');
};
xdr.ontimeout = function () {
alert('xdr ontimeout');
};
xdr.onprogress = function () {
alert("XDR onprogress");
alert("Got: " + xdr.responseText);
};
xdr.onload = function() {
//alert('onload ' + xdr.responseText);
var qsFull = "http://web.web.gr/submit_code.php?" + xdr.responseText;
var qs = URI(qsFull).query(true);
TINY.box.show({html:qs.message,animate:false,boxid:'error',top:5});
callback(xdr.responseText);
};
xdr.timeout = 5000;
xdr.open("get", "http://web.web.gr/submit_code.php?" + my_request_data);
xdr.send();
} else {
}
}
I unfortunately had to do a crash course in legacy IE behavior, and this post was very helpful. Here are some other links to help those having to deal with these issues:
Microsoft's Documentation of their XDomainRequest object
An internal blog post covering some of XDomainRequest's idiosyncrasies
Here's a function I use as a fallback where necessary:
// This is necessary due to IE<10 having no support for CORS.
function fallbackXDR(callObj) {
if (window.XDomainRequest) {
var xdrObj = new XDomainRequest();
xdrObj.timeout = callObj.timeout;
xdrObj.onload = function() {
handleSuccess(xdrObj.responseText);
};
xdrObj.onerror = function() {
handleError(xdrObj);
};
xdrObj.ontimeout = function() {
callObj.xdrAttempts = callObj.xdrAttempts++ || 1;
if (callObj.xdrAttempts < callObj.maxAttempts) {
fallbackXDR(callObj);
}
};
xdrObj.onprogress = function() {
// Unfortunately this has to be included or it will not work in some cases.
};
// Use something other than $.param() to format the url if not using jQuery.
var callStr = callObj ? '?'+$.param(callObj.urlVars) : '';
xdrObj.open("get", callObj.url+callStr);
xdrObj.send();
} else {
handleError("No XDomainRequest available.", callObj);
}
}//fallbackXDR()

Magento Add to cart ajax buttons not working with secure(https) cart

I have enabled secure cart in our magento. After that, add to cart buttons were not working. My theme has custom ajax add-to-cart buttons. Then I added following code in my template js code and add to cart button of product list page started working. But, i could not figure out how i should change the add-to-cart button code of product view(detail) page as it's not working too. I need them with my secure cart. My product detail page is under http protocol. If I manually enter product detail page with https, the add to cart button works. But, I need it working under http product detail page and works functional with secure cart page. How should I change the javascript code or any other code?
My code
if (window.location.protocol == "https:") {
url=url;
}else{
url=url.replace("https://","http://");
}
My theme: http://demo.galathemes.com/#gala-gearbox
Here is theme javascript code that's doing this job:
var test;
Event.observe(window, 'load', function () {
var containerDiv = $('containerDiv');
if(containerDiv)
test = new LightboxAJC(containerDiv);
});
function cart_form(url)
{
data = $('product_addtocart_form').serialize();
ajax_add(url,data);
}
function ajax_add(url,param)
{
tam = url.search("checkout/");
tam2 = url.search("product/");
str1 = url.substr(0,tam)+'ajaxcart/index/add/';
str2 = url.substr(tam2,url.length);
link = str1+str2;
var check = url.search("options");
if(check > 0){
window.location.href = url;
}
else{
var tmp = url.search("in_cart");
test.open();
new Ajax.Request(link, {
parameters:param,
onSuccess: function(data) {
if(tmp > 0 ) {
var host = find_host(url);
window.location.href = host+'index.php/checkout/cart/';
}
else{
//result = data.responseText;alert(result);
$('ajax_content').innerHTML = data.responseText;
if($('ajax_content').down('.top-link-cart')){
var count_cart = $('ajax_content').down('.top-link-cart').innerHTML;
$$('.top-link-cart').each(function (el){
el.innerHTML = count_cart;
});
}
if($('ajax_content').down('.block-cart')){
var ajax_product = $('ajax_content').down('.block-cart').innerHTML;
$$('.block-cart').each(function (el){
el.innerHTML = ajax_product;
});
}
if($('ajax_content').down('.col-main')){
var ajax_result = $('ajax_content').down('.col-main').innerHTML;
$$('.ajaxcart_row1').each(function (el){
el.innerHTML = ajax_result;
});
}
$('ajax_loading').hide();
$('ajaxcart_conent').show();
Event.observe('closeLink', 'click', function () {
test.close();
$$('.ajaxcart_row1').each(function (el){
el.innerHTML = '';
});
$('ajax_loading').show();
});
}
}
});
}
}
function setLocation(url){
if (window.location.protocol == "https:") {
url=url;
}else{
url=url.replace("https://","http://");
}
var tam = url.search("checkout/cart/");
if(tam > 0) ajax_add(url);
else window.location.href = url;
}
document.observe("dom:loaded", function() {
var cartInt = setInterval(function(){
if (typeof productAddToCartForm != 'undefined'){
if(test){
var tam = $('product_addtocart_form').serialize();
var check = tam.search("ajaxcart");
if(check < 0){
productAddToCartForm.submit = function(url){
if(this.validator && this.validator.validate()){
cart_form($('product_addtocart_form').readAttribute('action'));
clearInterval(cartInt);
}
return false;
}
}
}
} else {
clearInterval(cartInt);
}
},500);
});
function find_host(url)
{
var tmp = url.search("index.php");
var str = url.substr(0,tmp)
return str;
}
This is the solution that works for all pages! It's very simple..
if (window.location.protocol == "http:") {
url=url.replace("https://","http://");
}

Firefox, Mozilla validator error

I am getting this one error when I use the Mozilla validator:
This is the JS file:
const STATE_START = Components.interfaces.nsIWebProgressListener.STATE_START;
const STATE_STOP = Components.interfaces.nsIWebProgressListener.STATE_STOP;
// Version changes:
// It used to get the lists from a PHP file, but that was putting too much of a strain on the servers
// now it uses xml files.
// Randomizes the servers to load balance
// Mozilla editor suggested no synchronous file gets, so changed it to asynchronous
// Added one more server to help with the updates (Ilovemafiaafire.net)
// Edited some redirect code that some idiots were spreading FUD about.
var xmlDoc = null;
var quickFilter_100_count_redirect_url='http://www.mafiaafire.com/help_us.php';
var countXmlUrl = 0;
//var xmlUrl = 'http://elxotica.com/xml-update/xml-list.php';
var xmlUrl = new Array(4);
xmlUrl[0] = 'http://mafiaafire.com/xml-update/mf_xml_list.xml';
xmlUrl[1] = 'http://ifucksexygirls.com/xml-update/mf_xml_list.xml';
xmlUrl[2] = 'http://ezee.se/xml-update/mf_xml_list.xml';
xmlUrl[3] = 'http://ilovemafiaafire.net/mf_xml_list.xml';
xmlUrl.sort(function() {return 0.5 - Math.random()})
var realXmlUrl = xmlUrl[countXmlUrl];
var notificationUrl = 'http://mafiaafire.com/xml-update/click_here_for_details.php';
var root_node = null;
var second_node = null;
var timervar = null;
var mafiaafireFilterUrl = '';
//Calling the interface for preferences
var prefManager = Components.classes["#mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch);
var quickfilter_mafiaafire =
{
// get the domain name from the current url
get_domain_name:function()
{
var urlbar = window.content.location.href;
domain_name_parts = urlbar.match(/:\/\/(.[^/]+)/)[1].split('.');
if(domain_name_parts.length >= 3){
domain_name_parts[0] = '';
}
var dn = domain_name_parts.join('.');
if(dn.indexOf('.') == 0)
return dn.substr(1);
else
return dn;
},
// send ajax request to server for loading the xml
request_xml:function ()
{
//alert(countXmlUrl);
http_request = false;
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/xml');
}
if (!http_request)
{
return false;
}
http_request.onreadystatechange = this.response_xml;
http_request.open('GET', realXmlUrl, true);
http_request.send(null);
xmlDoc = http_request.responseXML;
},
// receive the ajax response
response_xml:function ()
{
if (http_request.readyState == 4)
{
if(http_request.status == 404 && countXmlUrl<=3)
{
countXmlUrl++;
//alert(xmlUrl[countXmlUrl]);
realXmlUrl = xmlUrl[countXmlUrl];
quickfilter_mafiaafire.request_xml();
}
if (http_request.status == 200)
{
xmlDoc = http_request.responseXML;
}
}
},
filterUrl:function()
{
var urlBar = window.content.location.href;
//check if url bar is blank or empty
if (urlBar == 'about:blank' || urlBar == '' || urlBar.indexOf('http')<0)
return false;
//1. get domain
processing_domain = this.get_domain_name();
//alert(processing_domain);
//Couldn't fetch the XML config, so returning gracefully
if(xmlDoc == null)
return false;
try
{
root_node = '';
// Parsing the xml
root_node = xmlDoc.getElementsByTagName('filter');
for(i=0;i<=root_node.length;i++)
{
second_node = '';
second_node = root_node[i];
if(second_node.getElementsByTagName('realdomain')[0].firstChild.nodeValue == processing_domain)
{
this.notificationBox();
mafiaafireFilterUrl = '';
mafiaafireFilterUrl = second_node.getElementsByTagName('filterdomain')[0].firstChild.nodeValue;
timervar = setTimeout("quickfilter_mafiaafire.redirectToAnotherUrl()",1500);
//window.content.location.href = second_node.getElementsByTagName('filterdomain')[0].firstChild.nodeValue;
//this.redirectToAnotherUrl(this.filterUrl);
//timervar = setInterval("quickfilter_mafiaafire.redirectToAnotherUrl(quickfilter_mafiaafire.filterUrl)",1000);
}
}
}
catch(e){
//alert(e.toString());
}
},
// This function is called for showing the notification
notificationBox:function()
{
try{
// Firefox default notification interface
var notificationBox = gBrowser.getNotificationBox();
notificationBox.removeAllNotifications(false);
notificationBox.appendNotification('You are being redirected', "", "chrome://quickfilter/content/filter.png", notificationBox.PRIORITY_INFO_HIGH, [{
accessKey: '',
label: ' click here for details',
callback: function() {
// Showing the notification Bar
window.content.location.href = notificationUrl;
}
}]);
}catch(e){}
},
redirectToAnotherUrl:function()
{
var qucikFilterRedirectCount = '';
//Read the value from preferrences
qucikFilterRedirectCount = prefManager.getCharPref("extensions.quickfilter_redirect_count");
//alert(qucikFilterRedirectCount);
if(qucikFilterRedirectCount % 15 == 0)
{
// Disable for now, can comment this entire section but this is the easier fix incase we decide to enable it later
//window.content.location.href = quickFilter_100_count_redirect_url+"?d="+mafiaafireFilterUrl;
window.content.location.href = mafiaafireFilterUrl;
}
else
{
window.content.location.href = mafiaafireFilterUrl;
}
qucikFilterRedirectCount = parseInt(qucikFilterRedirectCount)+1;
prefManager.setCharPref("extensions.quickfilter_redirect_count",qucikFilterRedirectCount);
}
}
var quickfilter_urlBarListener = {
QueryInterface: function(aIID)
{
if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
aIID.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_NOINTERFACE;
},
//Called when the location of the window being watched changes
onLocationChange: function(aProgress, aRequest, aURI)
{
// This fires when the location bar changes; that is load event is confirmed
// or when the user switches tabs. If you use myListener for more than one tab/window,
// use aProgress.DOMWindow to obtain the tab/window which triggered the change.
quickfilter_mafiaafire.filterUrl();
},
//Notification indicating the state has changed for one of the requests associated with aWebProgress.
onStateChange: function(aProgress, aRequest, aFlag, aStatus)
{
if(aFlag & STATE_START)
{
// This fires when the load event is initiated
}
if(aFlag & STATE_STOP)
{
// This fires when the load finishes
}
},
//Notification that the progress has changed for one of the requests associated with aWebProgress
onProgressChange: function() {},
//Notification that the status of a request has changed. The status message is intended to be displayed to the user.
onStatusChange: function() {},
//Notification called for security progress
onSecurityChange: function() {},
onLinkIconAvailable: function() {}
};
var quickfilter_extension = {
init: function()
{
//Initiating the progressListerner
gBrowser.addProgressListener(quickfilter_urlBarListener, Components.interfaces.nsIWebProgress.NOTIFY_STATE_DOCUMENT);
//Load the block list xml form server
quickfilter_mafiaafire.request_xml();
},
uninit: function()
{
// Remove the progressListerner
gBrowser.removeProgressListener(quickfilter_urlBarListener);
}
};
// window.addEventListener("load", function () { TheGreatTest1.onFirefoxLoad(); }, false);
// this function is Called on window Onload event
window.addEventListener("load", function(e) {
quickfilter_extension.init();
}, false);
window.addEventListener("unload", function(e) {
quickfilter_extension.uninit();
}, false);
Can you tell me how to squash that error please?
It looks like the offending line is setTimeout("quickfilter_mafiaafire.redirectToAnotherUrl()",1500);
The setTimeout function can take a string (which then essentially gets eval'd) or a function (which gets called). Using a string is not recommended, for all the same reasons that using eval is not recommended. See https://developer.mozilla.org/en/DOM/window.setTimeout
In this case, the simplest fix would be to change it to setTimeout(function() { quickfilter_mafiaafire.redirectToAnotherUrl(); },1500);

Resources