I have a web page that searches for an address using a web-service from a GIS server. I call this web-service in a JQuery AJAX method on the click of a button. Within the AJAX success function I map the address values to controls on the page. Before that, I do a check on the user role.
The check itself is not important. If the check fails, I alert() the user. The issue I'm having is that the alert() is repeated 6 times whenever the check fails. When debugging it looks like the AJAX call is not repeated multiple times.
function SelectAddress() {
var url = $.url.build({
protocol: 'https',
host: 'maps.site.co.za',
path: '/arcgis/rest/services/Search_Layers/SL_ADD/MapServer/find',
params: {
'searchText': SelectedAddressIsisKey,
'Contains': 'True',
'searchFields': 'ISIS Key',
'Layers': 0,
'returnCountOnly': 'false',
'returnZ': 'false',
'returnM': 'false',
'f': 'pjson'
}
});
$.ajax({
url: url,
type: 'GET',
cache: false,
dataType: 'jsonp',
success: function (data) {
// call autocomplete callback method with results
$.map(data.results[0].value, function (item) {
var _role = document.getElementById('txtRole').value;
var _addressNo = data.results[0].attributes['Addr No'];
var _suffix = data.results[0].attributes['Address No Suffix'];
var _streetName = data.results[0].attributes['Street Name'];
var _streetType = data.results[0].attributes['Street Name Type'];
var _suburb = data.results[0].attributes['Official Suburb Name'];
var _ward = data.results[0].attributes['Ward Name'];
var _subCouncil = data.results[0].attributes['Subcouncil Name'];
var _erfNo = data.results[0].attributes['Property Number'];
var _isisKey = data.results[0].attributes['ISIS Key'];
var _subCouncilNo = _subCouncil.substr(_subCouncil.length - 2, 2);
//Check Subcouncil of logged in user
if (_role == "Admin" || _role.substr(_role.length - 2, 2) == _subCouncilNo) {
document.getElementById('<%=TextBoxAddressNumber.ClientID%>').value = _addressNo;
document.getElementById('<%=ddlAddressSuffix.ClientID%>').value = _addressNo;
document.getElementById('<%=TextBoxRoad.ClientID%>').value = _streetName + " " + _streetType;
document.getElementById('<%=TextBoxSuburb.ClientID%>').value = _suburb;
document.getElementById('<%=ddlWard.ClientID%>').value = _ward;
document.getElementById('<%=ddlSubCouncil.ClientID%>').selectedIndex = _subCouncilNo;
document.getElementById('<%=txtErf.ClientID%>').value = _erfNo;
document.getElementById('<%=lblLISKey.ClientID%>').value = _isisKey;
jQuery('#Search-modal').dialog('close');
//return;
}
else {
alert("Error: This address is in Sub-Council " + _subCouncilNo);
//jQuery('#Search-modal').dialog('close');
}
//return;
});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error - ' + textStatus + errorThrown + XMLHttpRequest);
//console.log('error', textStatus, errorThrown);
}
});
}
I see.
jQuery.map()
Description: Translate all items in an array or object to new array of items.
So, what I need to do is this:
$.map(data.results[0].value[0], function (item) { ... }
Related
I have a form that submits through ajax. At first click it sends the request to php but doesnt send post variables and however when i submit form for second or third time it submits the form and gets the success response. The ajax request doesn't fail on first click it just doesnt send data to php.When i check the network tab request fields show up there on the first click and have correct values but doesnt reach php. Here is my code
jQuery("#bidding-form").on('submit', function(e) {
var request_english_level = jQuery('#request_english_level').val();
var job_title = jQuery('#job_title').val();
var request_type = jQuery('#request_type').val();
var estimated_hours = jQuery('#estimated_hours').val();
var designation = jQuery('#designation').val();
var service_type = jQuery('#service_type').val();
var budget = jQuery("#budget").val();
var user_id = jQuery('#user_id').val();
var locations = jQuery('#location').val();
var payment_terms = jQuery('#payment_terms').val();
var application_no = jQuery('#application_no').val();
var deadline_apply = jQuery('#deadline_apply').val();
var close_date = jQuery('#close_date').val();
var delivery_deadline = jQuery('#delivery_deadline').val();
var experience = jQuery('#consultant_experience').val();
var description = jQuery('#request_description').val();
var formdata = new FormData();
var length = jQuery(".attachment")[0].files.length;
for (i = 0; i < length; i++) {
formdata.append('file[]', jQuery(".attachment")[0].files[i]);
}
formdata.append('action', 'save_bid_info');
var checked_skills = []
jQuery("input[name='request_skills[]']:checked").each(function() {
//checked_skills.push(parseInt(jQuery(this).val()));
formdata.append('request_skills[]', parseInt(jQuery(this).val()));
});
var languages = []
jQuery("input[name='languages[]']:checked").each(function() {
//languages.push(parseInt(jQuery(this).val()));
formdata.append('languages[]', parseInt(jQuery(this).val()));
});
formdata.append('designation', designation);
// formdata.append('request_skills', checked_skills);
formdata.append('request_type', request_type);
formdata.append('estimated_hours', estimated_hours);
formdata.append('service_type', service_type);
formdata.append('delivery_deadline', delivery_deadline);
formdata.append('job_title', job_title);
formdata.append('locations', locations);
formdata.append('request_type', request_type);
formdata.append('payment_terms', payment_terms);
formdata.append('application_no', application_no);
formdata.append('deadline_apply', deadline_apply);
formdata.append('close_date', close_date);
formdata.append('experience', experience);
formdata.append('description', description);
formdata.append('budget', budget);
// formdata.append('languages', languages);
formdata.append('request_english_level', request_english_level);
e.preventDefault();
jQuery.ajax({
url: ajax_url,
type: 'post',
dataType: 'json',
contentType: false,
cache: false,
processData: false,
data: formdata,
beforeSend: function() {
jQuery(".loader").show();
},
complete: function(data) {
jQuery('.loader').hide();
}
})
.done(function(response, textStatus, jqXHR) {
if (response.success == true) {
jQuery(".ajax-processor").hide();
} else {
jQuery(".ajax-processor").find('p').html(response.msg);
}
})
.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
})
});
// PHP CODE
if(isset($_POST['budget']) && !empty($_POST['budget']))
{
// on second click this is executed
}
else
{
// on first click this is executed
}
My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
I have a ribon rule to either show or hide the Deactivate button for accounts.
It's pretty straightforward
if (typeof (XTC) == "undefined")
{ XTC= { __namespace: true }; }
XTC.RibbonRules = (function () {
AccountRules = {
//see if user has roles specified to have the Deactivate button enabled.
IsDeactivateEnabled: function () {
var orgName = Xrm.Page.context.getOrgUniqueName();
var validGuids;
var allowedRoles = [];
/*
put all roles needed to show Account Deactivate button here.
*/
allowedRoles.push('System Administrator');
allowedRoles.push('XTC Admin');
var userRoles = Xrm.Page.context.getUserRoles();
//user has no assigned roles...
if (userRoles.length < 1)
return false;
var matchingRoles = AccountRules.returnMatchingRoles(userRoles);
for (var x = 0; x < matchingRoles.length; x++) {
if ($.inArray(matchingRoles[x].Name, allowedRoles) != -1)
return true;
}
return false;
},
returnMatchingRoles: function (roles) {
var matches;
var serverUrl = location.protocol + '//' + location.host + '/' + Xrm.Page.context.getOrgUniqueName();
var queryUrl = serverUrl + '/XRMServices/2011/OrganizationData.svc/' + 'RoleSet?$filter=';
for (var x = 0; x < roles.length; x++) {
if (x == roles.length - 1) {
queryUrl += "RoleId eq guid'" + roles[x] + "'";
}
else {
queryUrl += "RoleId eq guid'" + roles[x] + "' or ";
}
}
$.ajax({
url: queryUrl,
type: "GET",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
matches = data.d;
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect);
}
});
return (matches.results.length > 0) ? matches.results : null;
}
};
return { AccountRules: AccountRules };
})();
So if the user doesn't have a role that's either of the two, the button is deactivated.
My issue is that this isn't running in the context of a form, so including web resources at form config is not working.
For some reason I can't figure out, from there, I have access to jQuery (2.1.1) but none of my other resources.
Is there a way to include web resources system wide so it may be available in this code, just like jQuery seems to be ?
You can include libraries by making your command look like this:
<CommandDefinition Id="new.incident.Home.ValidateAndResolve.Command">
<EnableRules>
<EnableRule Id="Mscrm.SelectionCountAtLeastOne" />
</EnableRules>
<DisplayRules />
<Actions>
<JavaScriptFunction FunctionName="isNaN" Library="$webresource:xyz_/Scripts/Common/helpers.js" />
<JavaScriptFunction FunctionName="incidentribbon.validateAndResolve" Library="$webresource:xyz_/Scripts/Ribbon/incident.js" />
</Actions>
</CommandDefinition>
Note the value of "isNaN" for FunctionName. isNaN is just a globally available JavaScript function that does nothing if you don't pass it any parameters. This is how you get the ribbon to load your library without actually making it call any functions in your library.
Also note that you can either manually edit the command or use a tool like the excellent Ribbon Workbench.
I have an ajax request, whereby I am installing a magento shop automatically, and when the process is done, it would redirect the user to the newly created shop. Here are my codes:
function postSuccessFormData() {
var targetUrl = '/index.php/install/wizard/successPost';
jQuery('.form-button').addClass('loading');
setInterval(installStatus(),4000);
jQuery.ajax({
url: targetUrl,
global: false,
type: 'POST',
data: ({
finish: 1,
password_key: jQuery('#password_key').val()
}),
async: true,
dataType: 'json',
error: function() {
alert("An error has occurred. Please try again.");
},
success: function(data) {
window.location.href = '/';
}
});
function installStatus() {
var installerUpdatesUrl = '/index.php/install/wizard/installerStatus';
//showProgressBar();
jQuery.ajax({
url: installerUpdatesUrl,
// global: false,
type: 'GET',
async: true,
dataType: 'json',
error: function (data) {
// alert(data.result);
},
success: function (data) {
handle data.result
var dataKeys = Object.keys(data);
var lastElementKey = dataKeys[dataKeys.length - 1];
var lastMessage = data[lastElementKey]['message'];
if(data[lastElementKey]['progress'] == '') {
updateProgressBar(data[dataKeys[dataKeys.length - 2]]['progress'],100);
}
setting message
jQuery("#message").html(lastMessage);
if (data[lastElementKey]['state'] == 'Failure') {
var stepStr = lastElementKey.split('_');
var stepString = stepStr[0].toUpperCase() + ' ' + stepStr[1] + ':';
alert(stepString + "\n" + data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
return false;
} else if (data[lastElementKey]['state'] == 'Finish') {
alert(data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
//window.location.href = '/';
} else {
// installStatus();
}
},
complete: function () {
installStatus();
jQuery('.form-button').removeClass('loading');
}
});
}
The way this is done:
After every 4 seconds the function installStatus is run, which will output the current progress in JSON format. My problem is, this function needs to be executed simultaneously with the function post().
This is not happening, the installStatus is only run after the first function has been completed.
What is wrong?
You are executing installStatus when you define it. So this:
setInterval(installStatus(),4000);
needs to be
setInterval(installStatus, 4000);
The new XMLHttpRequest has a nice progress event you can listen to show the user the upload progress.
Here's the spec with a nice demo: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
Initially you should call installStatus() only once and then inside the method inside ajax success you should update the procent in the progress bar and call it recursively the same method. On the server side you can save the current procent in a cookie and with every recursive call you can update the cookie and return the procent.
I Have added a Add New Lead button to the Homepage Main form of contacts
This calls a script to open a new form passing Crm Parameter FirstSelectedItemId
So when I have selected a contact I can click create new lead & pass the Id as a parameter to the function:
function openNewLead(SelectedID) {
parameters["customer"] = SelectedID;
Xrm.Utility.openEntityForm("lead", null, parameters);
}
"customer" is a lookup field
Now I can use this and it populates the lookup but im not passing the full name so doesn't work correctly. if I save and refresh its fine!
So I tried:
function openNewLead(SelectedID) {
if (SelectedID != null) {
var parameters = {};
var request = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/ContactSet?$select=FullName&$filter=ContactId eq guid'" + SelectedID + "'";
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: request,
async: false,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data.d.results.length > 0) {
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = SelectedID;
lookupValue[0].name = data.d.results[0].FullName;
lookupValue[0].entityType = "contact";
parameters["customer"] = lookupValue;
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
/*Error Occurred*/
}
});
Xrm.Utility.openEntityForm("lead", null, parameters);
}
else {
Xrm.Utility.openEntityForm("lead");
}
}
This doesn't work from the homepage/main screen as no reference can be added for Json
So the question is how do I reference json from here or is there a better way to write this?
Thank you
Try this change
success: function (data, textStatus, XmlHttpRequest) {
if (data.d.results.length > 0) {
parameters["customerid"] = SelectedID;
parameters["customeridname"] = data.d.results[0].FullName;
parameters["customeridtype"] = "contact";
}
}
Solution:
New lead Button on main/homepage This calls a script to open a new form passing CrmParameter FirstSelectedItemId
function openNewLead(SelectedID) {
if (SelectedID != null) {
var parameters = {};
var contact = {};
contact.Id = SelectedID;
var jsonContact = JSON.stringify(contact);
var PassContactReq = new XMLHttpRequest();
PassContactReq.open("GET", Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc/ContactSet?$select=ContactId, FullName&$filter=ContactId eq guid'" + SelectedID + "'");
PassContactReq.setRequestHeader("Accept", "application/json");
PassContactReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
PassContactReq.onreadystatechange = function () {
PassContact(this);
};
PassContactReq.send(jsonContact);
function PassContact(PassContactReq) {
if (PassContactReq.readyState == 4 /* complete */) {
PassContactReq.onreadystatechange = null; //avoids memory leaks
if (PassContactReq.status == 200) {
//Success
parameters["customer"] = JSON.parse(PassContactReq.responseText).d.results[0].ContactId;
parameters["customername"] = JSON.parse(PassContactReq.responseText).d.results[0].FullName;
Xrm.Utility.openEntityForm("lead", null, parameters);
}
else {
//Failure
Xrm.Utility.openEntityForm("lead");
}
}
};
} else {
Xrm.Utility.openEntityForm("lead");
}
}
Awesome :) thanks #Nicknow for comment!
As this was a custom lookup field the name differs for the parameters too: Ignore the "id" part of the string & no type to set.
Took too long to find this solution so hopefully it will help others :)
try add javascript actions with referenced webresources and some dummy function name. Like "isNaN".
Ribbon Xml will looks like:
<Actions>
<JavaScriptFunction FunctionName="isNaN" Library="new_json2"></JavaScriptFunction>
<JavaScriptFunction FunctionName="isNaN" Library="new_jquery"></JavaScriptFunction>
<JavaScriptFunction FunctionName="someFunctionUsingCoolExternalLibs" Library="new_referencinglibrary"></JavaScriptFunction>
</Actions>
Sorry for my english :)