I'm trying to fetch designations from database using ajax and php and store those values in a javascript variable designations.
I'm trying to set the availabletags option of tagit() from this designation variable.
var tagThis = $(".tagit");
tagThis.tagit({
tagSource: function(search, showChoices) {
$.ajax({
type : 'POST',
url: "/tags/search",
data: { queryString: inputString },
dataType: "json",
success: function(data) {
var assigned = tagThis.tagit("assignedTags");
var filtered = [];
for (var i = 0; i < data.length; i++) {
if ($.inArray(data[i], assigned) == -1) {
filtered.push(data[i]);
}
}
showChoices(filtered);
}
});
}
});
The drop down isn't getting produced when I change the type to POST.
Related
i'm really struggling to understand the asynchronous side of JavaScript. the code i have is meant to collate specific details of certain users and then put all the collated information into a global variable array which i intent to manipulate when all the users have been added to the array. i'm finding it difficult to iterate the array because when i do an array.length on the printurlonPage() function i get a 0 despite the fact that when i do a console log on the array itself i can see that there are items there. Does anyone know a technique that allows me to work on the global variable only after the asynchronous function has completed?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
var PeopleCompleteList = [];
function PersonConstructor(username,Title,Phone,Email,imageurl){
return {
name: username,
Title: Title,
phoneNumber: Phone,
Email: Email,
Picture: imageurl
}
}
var printurlonPage = function (){
for (var link in PeopleCompleteList) {
console.log(link['Picture']);
}
console.log(PeopleCompleteList);
}
var getIndividualPersonDetails = function(GetPictureUrl) {
listName = 'TeamInfo';
//var PeopleCompleteList = [];
// execute AJAX request
$.ajax({
url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getbytitle('"+listName+"')/items?$select=Name/Title,Name/Name,Name/Id,Name/EMail,Name/WorkPhone&$expand=Name/Id",
type: "GET",
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
for (i=0; i< data.d.results.length; i++) {
//check if the user exists if he does store the following properties name,title,workphone,email and picture url
if(data.d.results[i]['Name'] != null){
var personName = data.d.results[i]['Name'].Name.split('|')[2];
var userName = data.d.results[i]['Name']['Name'];
var UserTitle = data.d.results[i]['Name']['Title'];
var UserphoneNumber = data.d.results[i]['Name']['WorkPhone'];
var UserEmail = data.d.results[i]['Name']['EMail'];
var myuserPicture = GetPictureUrl(userName);
console.log(myuserPicture);
PeopleCompleteList.push(PersonConstructor(personName, UserTitle, UserphoneNumber,UserEmail,myuserPicture));
}
}
},
error: function () {
alert("Failed to get details");
}
});
}
function GetPictureUrl(user) {
var userPicture="";
var requestUri = _spPageContextInfo.webAbsoluteUrl +
"/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=#v)?#v='"+encodeURIComponent(user)+"'";
$.ajax({
url: requestUri,
type: "GET",
async:false,
headers: { "ACCEPT": "application/json;odata=verbose" },
success: function (data) {
console.log(data);
var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'c:\apps\noimageurl.jpg';
userPicture=PictureDetails;
}
});
return userPicture;
};
$(function () {
getIndividualPersonDetails(GetPictureUrl);
printurlonPage();
});
</script>
You're printurlonPage() is not asynchronous, so it's running before getIndividualPersonDetails responds. You can do two things, use promises or use async/await from es7. I prefer async/await, but you'll need to babelify.
Or, you can just put your printurlonPage invocation inside your success: handler.
success: function (data) {
for (i=0; i< data.d.results.length; i++) {
//check if the user exists if he does store the following properties name,title,workphone,email and picture url
if(data.d.results[i]['Name'] != null){
var personName = data.d.results[i]['Name'].Name.split('|')[2];
var userName = data.d.results[i]['Name']['Name'];
var UserTitle = data.d.results[i]['Name']['Title'];
var UserphoneNumber = data.d.results[i]['Name']['WorkPhone'];
var UserEmail = data.d.results[i]['Name']['EMail'];
var myuserPicture = GetPictureUrl(userName);
console.log(myuserPicture);
PeopleCompleteList.push(PersonConstructor(personName, UserTitle, UserphoneNumber,UserEmail,myuserPicture));
}
}
printurlonPage();
},
And then in document.ready:
$(function () {
getIndividualPersonDetails(GetPictureUrl);
});
So, getIndividualPersonDetails is invoked, and then when it receives the data, the callback is invoked with the data.
I have a javascript function
function TxEncrypt(event)
{ //perform encryption of token data, then submit the form like normal
//obtain public key and initial JSEncrypt object
var txPubKey = txJ$(".zwitch_encryptionkey").val();
var txEncrypter = new JSEncrypt();
txEncrypter.setPublicKey(txPubKey);
//get Data and encrypt it
var txData = '{}';
var txCryptData = '';
if(txJ$(".zwitch_data").length > 1)
{ //if there are more than one element with this class, convert it to json string
txData = txJ$(".zwitch_data").serializeObject();
txCryptData = txEncrypter.encrypt(JSON.stringify(txData));
}
else
{ //else, just encrypt the value
txData = txJ$(".zwitch_data").val();
txCryptData = txEncrypter.encrypt(txData);
}
dataString = txCryptData; // array?
$.ajax({
type: "POST",
url: "tokenize.php",
data: {data : dataString},
cache: false,
success: function(data) {
returnedvalue = data;
console.log(data); //alert isn't for debugging
}
});
alert(dataString);
}
I could get the value of dataString.But the ajax parrt is not working.I have added the jquery library.But doesnt seem to work
What's the error you are getting?
I think this should be:
$.ajax({
type: "POST",
url: "tokenize.php", //removed the dot
.....
In a button.click(function(){}); I have the following code:
var userId = $("#user-permission-edit").val();
var peId = $("#user-permission-entity-list").val();
var newParentPEId = $("#new-parent-pe").val();
var newPeName = $("#pe-name-add").val();
$.ajax({
type: "POST",
url: 'AddNewPE',
data: { 'targetUserId': userId, 'targetPEId': peId, 'newPeParentId': newParentPEId, 'newPeName': newPeName},
success: function (data) {
var dataObj = jQuery.parseJSON(data);
console.log(dataObj);
if (dataObj.status == "success") {
alert("Permissions have been updated.");
}
//update user PEs combo
}
});
However, I am concerned of a possible race condition of the variables not getting the values in time for the ajax call.
would something like this be safer?
var userId = $("#user-permission-edit").val();
var peId = $("#user-permission-entity-list").val();
var newParentPEId = $("#new-parent-pe").val();
var newPeName = $("#pe-name-add").val();
$.when(function() {
userId = $("#user-permission-edit").val();
peId = $("#user-permission-entity-list").val();
newParentPEId = $("#new-parent-pe").val();
newPeName = $("#pe-name-add").val();
}).done(function() {
$.ajax({
type: "POST",
url: 'AddNewPE',
data: { 'targetUserId': userId, 'targetPEId': peId, 'newPeParentId': newParentPEId, 'newPeName': newPeName},
success: function (data) {
var dataObj = jQuery.parseJSON(data);
console.log(dataObj);
if (dataObj.status == "success") {
alert("Permissions have been updated.");
}
//update user PEs combo
}
});
});
Is this even necessary?
The $('....').val() method is a synchronous call - your script execution won't continue past that line until you have received the value of that element.
I'm relatively new to javascript, and I have a restful api I'm connecting to that returns me a json string, which I can parse properly like so:
$.ajax({ url: './php/bandwidth.php',
data: { prop_id : "1" },
type: 'post',
success: function(output) {
var json = $.parseJSON(output);
for( var i = 0 ; i < json.response.length; i++ ){
times.push (json.response[i].time);
}
}
});
Inside of the success callback the variables in the array exist. I also have times array instantiated outside the ajax call function. But outside of the ajax call the array is empty. I'm sure it's a scoping issue. Can anyone give me a way to get the data from inside the array? Does the construct $.ajax({url:... , data:... , success: function(){}}); returns callback return value?
$.ajax({ url: './php/bandwidth.php',
data: { prop_id : "1" },
type: 'post',
dataType: 'json',
success: function(output) {
times = [];
for( var i = 0 ; i < output.response.length; i++ ){
times.push (output.response[i].time);
}
},
complete: function(){
if(times.length > 0){ console.log(times); } else { console.log("times empty"); }
}
});
I am trying to get the string to order by how it is displayed (red,blue,orange,black). For some reason, it will append the order randomly. For Example: it would output (blue,orange,red,black). Any help would be great. Thanks.
var tCookie = "red,blue,orange,black";
var Cookies = tCookie.split(',');
if (Cookies) {
for (var i = 1; i <= Cookies.length; i++) {
var dataString = "TabId="+Cookies[i]+"";
$.ajax({
type: "POST",
url: "includes/tab.php",
data: dataString,
cache: false,
success: function(html){
$("#Dynamic_Tab").append(html).children(':last').hide().fadeIn("fast");
}
});
}
}
You could have a list of requests and responses, and start appending when all are done, so that the order is always correct:
var deferreds = [],
results = [];
for (var i = 1; i <= Cookies.length; i++) {
(function(i) { // to freeze i
var dataString = "TabId="+Cookies[i]+"";
deferreds.push($.ajax({
type: "POST",
url: "includes/tab.php",
data: dataString,
cache: false,
success: function(html){
results[i] = html; // insert at the synchronous position
}
}));
})(i);
}
$.when.apply($, deferreds).then(function() {
$.each(results, function(i, html) {
$("#Dynamic_Tab").append(html).children(':last').hide().fadeIn("fast");
});
});
You can use deferred objects here to only append the HTML after all of the AJAX requests come back:
//create array to store XHR objects that will resolve when the AJAX requests return
//also create an object to store the AJAX responses
var jqXHRs = [],
responses = {};
//iterate through each of the cookie indexes
$.each(cookies, function (index, value) {
//create the dataString and cache the value of this index so it can be used in the success callback for the AJAX request associated with this index
var dataString = "TabId=" + value,
thisValue = value;
//store an empty string in the output variable for the current index, this keeps it's place in-line
responses[thisValue] = '';
//do the AJAX request and store it's XHR object in the array with the rest
jqXHRs[jqXHRs.length] = $.ajax({
type : "POST",
url : "includes/tab.php",
data : dataString,
cache : false,
success : function (html) {
//now that the AJAX request has returned successfully, add the returned HTML to the output variable for this index
responses[thisValue] = html;
}
});
});
//wait for all of the XHR objects to resolve then add all the HTML to the DOM
$.when(jqXHRs).then(function () {
//all of the AJAX requests have come back and you can now add stuff to the DOM
var $element = $("#Dynamic_Tab");
$.each(responses, function (index, value) {
$element.append(value).children(':last').hide().delay(index * 250).fadeIn(250);
}
});
The .delay() is so that each new row will fade in, in order.