jQuery ajax params issue - javascript

This is my code:
$('body').on('click', '.update_contact_profile', function (){
var url = $("#ajaxUrl").val();
var ids = $(this).closest("div").nextAll(".contact-extra-info").find(".contact-ids").attr("id");
ids = ids.split("-")
var contactId = ids[0];
var customerId = ids[1];
var postDataUpdate = [];
$(this).closest("div").nextAll(".update_elements").find(".value :input").each(function(i, itemVal){
if ($(this).val()) {
postDataUpdate[''+$(this).attr('id')+''] = $(this).val();
}
});
var request = $.ajax({
url: url,
method: "POST",
data: {
id : contactId,
contact : postDataUpdate,
form_key : FORM_KEY,
customerId : customerId
}
});
request.success(function( text ) { // replace the ajax_wrapper with the new one
$(".ajax_wrapper").replaceWith(text);
$("#contact_form").find('select').selectize();
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
My problem is that this var postDataUpdate it didn't passed to ajax. On firebug the contact doesn't appear. If I do console.log(postDataUpdate) before my ajax request i got my array .
So any idea about this ?

postDataUpdate should be an object, instead of an array:
[..]
var postDataUpdate = {};
$(this).closest("div").nextAll(".update_elements").find(".value :input").each(function(i, itemVal){
if ($(this).val()) {
postDataUpdate[''+$(this).attr('id')+''] = $(this).val();
}
});
[..]
Check this snippet:
var asArray = [];
asArray[1] = "foo";
asArray["foo"] = "bar";
console.log("asArray:");
console.log(asArray);
var asObject = {};
asObject[1] = "foo";
asObject["foo"] = "bar";
console.log("asObject:");
console.log(asObject);

Related

I need to pass the value of the variable from javascript to php how can I do it?

This is the code and this is a variable price value parseFloat(preco).toFixed(4); that's refreshed every 2 seconds. I need to pass this to a PHP variable, how can I do it? I have tried various ways but it does not work for me. It must be something so simple and I'm overlooking it.
var preco;
var valor;
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "POST", aUrl, true );
anHttpRequest.send( null );
}
}
var HttpClient2 = function() {
this.get = function(aUrl, aCallback) {
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
var HttpClient3 = function() {
this.get = function(aUrl, aCallback) {
var anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
var client = new HttpClient();
var client2 = new HttpClient2();
var client3 = new HttpClient3();
let paragrafo = document.createElement("p");
paragrafo.setAttribute("id", 'dracoVlr');
let total = document.createElement("p");
total.setAttribute("id", 'dracodolares');
let totalr = document.createElement("p");
totalr.setAttribute("id", 'dracoreais');
let totale = document.createElement("p");
totale.setAttribute("id", 'dracoeuro');
let inputvlr = document.createElement("input");
inputvlr.setAttribute("id", 'dracoInput');
inputvlr.setAttribute("type", "number")
inputvlr.setAttribute("placeholder", "Cantidad de DRACOS")
inputvlr.setAttribute("value", localStorage.getItem('dracoVlr1'))
let texto = document.createTextNode("Precio DRACO" + ' - ' + parseFloat(preco).toFixed(4));
paragrafo.appendChild(texto);
let body = document.body;
body.appendChild(paragrafo);
body.appendChild(inputvlr);
body.appendChild(total);
body.appendChild(totalr);
body.appendChild(totale);
function display() {
client.get('https://api.mir4global.com/wallet/prices/draco/daily', function(response) {
var retorno = JSON.parse(response);
preco = retorno.Data[retorno.Data.length - 1].USDDracoRate
var input = document.querySelector('input');
valor = input.value;
localStorage.setItem('dracoVlr1', input.value);
document.title = 'Draco' + ' - $' + parseFloat(preco).toFixed(4);
document.getElementById('dracoVlr').innerHTML = "Preço do Draco" + ' - $' + parseFloat(preco).toFixed(4);
});
client2.get('https://api.binance.com/api/v3/ticker/price?symbol=BUSDBRL', function(response) {
var binance = JSON.parse(response);
console.log(binance.price)
document.getElementById('dracodolares').innerHTML = 'Total em Dólares: $' + (valor * preco).toFixed(4)
document.getElementById('dracoreais').innerHTML = 'Total em Reais: R$' + ((valor * preco)*binance.price).toFixed(4)
});
client3.get('https://api.binance.com/api/v3/ticker/price?symbol=EURBUSD', function(response) {
var binance3 = JSON.parse(response);
console.log(binance3.price)
document.getElementById('dracodolares').innerHTML = 'Total em Dólares: $' + (valor * preco).toFixed(4)
document.getElementById('dracoeuro').innerHTML = 'Total en Euros: EUR' + ((valor * preco)*binance3.price).toFixed(4)
});
}
var results= parseFloat(preco).toFixed(4);
<?php $results = "<script>document.write(results)</script>"?>
const createClock = setInterval(display, 2000);
I would be very grateful if you could help me please.
Ajax example for it in your PHP file request $result = $_POST['variable'];
let texto = document.createTextNode("Precio DRACO" + ' - ' + parseFloat(preco).toFixed(4));
$.ajax({
type: 'POST',
url: 'yourphpfile.php',
data: {
'variable': texto
},
});
$result = $_POST['variable'];
The problem is that you get the value asynchronously and try to use it before it's computed. Let me explain what seems to happen:
The two seconds passed
A request is sent to client1
A request is sent to client2
A request is sent to client3
clienti responds and its callback is executed
clientj responds and its callback is executed
clientk responds and its callback is executed
We know that i <> j <> k <> i. The problem is that you do not guarantee that i is 1. Yet, you intend to use the results of the callback of your request to client1 in the callbacks of the requests sent to client2 and client3.
You will need to have something like this:
function display() {
client.get('someurl', function(response) {
//compute your values
client2.get('someurl2', function(response2) {/* ... */});
client3.get('someurl2', function(response3) {/* ... */});
});
}
This way you guarantee that the requests to client2 and client3 are only sent once you have got a response to your request to client and you have computed your variable.
This is a simple example of how can pass Javascript variables to PHP you can understand how to pass variables to PHP. According to your script let texto = document.createTextNode("Precio DRACO" + ' - ' + parseFloat(preco).toFixed(4)); this is the Javascript variable and as example i pass this to like <?php echo "<script>window.alert(texto)</script>"; ?>

How to call in tag manager data after user OAUTH2 authorization is complete (JavaScript)?

I've been at this all day trying to figure out how to do an XMLHTTP request after authorization but just can't for the life of me figure it out.
So far I've got the code below which authorizes the user.
var OAUTHURL = 'https://accounts.google.com/o/oauth2/auth?';
var VALIDURL = 'https://www.googleapis.com/oauth2/v1/tokeninfo?
access_token=';
var SCOPE = 'https://www.googleapis.com/auth/userinfo.profile
https://www.googleapis.com/auth/userinfo.email';
var CLIENTID = 'NOT SHOWING FOR SECURITY REASONS';
var REDIRECT = 'NOT SHOWING FOR SECURITY REASONS'
var LOGOUT = 'http://accounts.google.com/Logout';
var TYPE = 'token';
var _url = OAUTHURL + 'scope=' + SCOPE + '&client_id=' + CLIENTID + '&redirect_uri=' + REDIRECT + '&response_type=' + TYPE;
var acToken;
var tokenType;
var expiresIn;
var user;
var loggedIn = false;
function login() {
var win = window.open(_url, "windowname1", 'width=800, height=600');
var pollTimer = window.setInterval(function() {
try {
console.log(win.document.URL);
if (win.document.URL.indexOf(REDIRECT) != -1) {
window.clearInterval(pollTimer);
var url = win.document.URL;
acToken = gup(url, 'access_token');
tokenType = gup(url, 'token_type');
expiresIn = gup(url, 'expires_in');
win.close();
validateToken(acToken);
}
} catch(e) {
}
}, 500);
}
function validateToken(token) {
$.ajax({
url: VALIDURL + token,
data: null,
success: function(responseText){
getUserInfo();
loggedIn = true;
$('#loginText').hide();
$('#logoutText').show();
},
dataType: "jsonp"
});
}
function getUserInfo() {
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + acToken,
data: null,
success: function(resp) {
user = resp;
console.log(user);
$('#uName').text('Welcome ' + user.name);
$('#imgHolder').attr('src', user.picture);
},
dataType: "jsonp"
});
}
//credits: http://www.netlobo.com/url_query_string_javascript.html
function gup(url, name) {
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\#&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( url );
if( results == null )
return "";
else
return results[1];
}
function startLogoutPolling() {
$('#loginText').show();
$('#logoutText').hide();
loggedIn = false;
$('#uName').text('Welcome ');
$('#imgHolder').attr('src', 'none.jpg');
}
The code works fine as far as the login goes. It's after logging in that I don't know what to do. I've tried multiple ideas and have gotten nowhere. Any ideas on how I can call tags from tag manager in "readonly" mode after this login?
Hi I just decided to try using the JavaScript web app method and was able to get this working. If you run into the same issue using the ajax version here is the documentation! Make sure to select the JavaScript tab or you can try the oAuth2.
https://developers.google.com/identity/protocols/OAuth2UserAgent

Save Multiple Rows from table to Backend SAPUI5

I'm having issues with saving multiple rows to the back-end. I don't know how to send all the rows in batch, so I was trying to send each row at a time but it hits after it has put the last row into the oEntry.
submitButtonPress: function() {
var oModel = this.getModel();
var hasChanges = oModel.hasPendingChanges();
if (hasChanges) {
var mcJson = {};
//get only rows with changes
var modelChanges = oModel.getPendingChanges();
mcJson = modelChanges;
var mcJsonLength = Object.keys(mcJson).length;
var mcJsonKey = Object.keys(mcJson);
var officeCode = this.byId("officeCombo").getValue();
var oEntry = {};
//for each row get data
for (var i = 0; i < mcJsonLength; i++) {
var item = mcJsonKey[i];
var obj = modelChanges[item];
var estDate = this.convertDate(obj.ESTIMATE_DATE);
oEntry.MRU_ID = obj.EST_MRU_ID.toString();
oEntry.ESTIMATE_PRCT = obj.ESTIMATE_PRCT;
oEntry.INSTALL_READ = obj.INSTALL_READ;
oEntry.PLAN_ESTIMATE = obj.EST_INSTALL;
oEntry.MRU_DATE = estDate;
oEntry.OFFICE_CODE = officeCode.toString();*/
oModel.create("/MRU_ESTSet", oEntry, {
success: function(oData, response) {
sap.m.MessageBox.alert("MRU: " + oEntry.MRU_ID + " EST DATE:" + oEntry.MRU_DATE + " SAVED!");},
error: function(oError) {
sap.m.MessageBox.alert("Error Saving Entries!!");
}
});
}
} else {
sap.m.MessageBox.alert("No Changes To Submit");
}
}
If you are using oDataModel V2 then what you could just simply do is:
oModel.submitChanges()
This would send all changes made to the model in a batch.
submitChanges method documentation
This is what ended up working for me.
Adding:
oModel.setUseBatch(true);
oModel.create("/MRU_ESTSet", oEntry, {
method: "POST",
success: function(oData) {
//sap.m.MessageBox.alert("success sent!");
},
error: function(oError) {
//sap.m.MessageBox.alert("Error Saving Entries!!");
}
});
}
oModel.submitChanges({
success: function(oData, response) {
sap.m.MessageBox.success("Success Saving Entries!");
},
error: function(oError) {
sap.m.MessageBox.error("Error Saving Entries!!");
}
});
So the function ends up like this and only sends one confirmation instead of many:
submitButtonPress: function() {
var oModel = this.getModel();
oModel.setUseBatch(true);
var hasChanges = oModel.hasPendingChanges();
if (hasChanges) {
var mcJson = {};
var modelChanges = oModel.getPendingChanges();
mcJson = modelChanges;
var mcJsonLength = Object.keys(mcJson).length;
var mcJsonKey = Object.keys(mcJson);
var officeCode = this.byId("officeCombo").getValue();
for (var i = 0; i < mcJsonLength; i++) {
var item = mcJsonKey[i];
var obj = modelChanges[item];
var estDate = this.convertDate(obj.ESTIMATE_DATE);
var oEntry = {
MRU_ID: obj.EST_MRU_ID,
ESTIMATE_PRCT: obj.ESTIMATE_PRCT,
INSTALL_READ: obj.INSTALL_READ,
PLAN_ESTIMATE: obj.EST_INSTALL,
MRU_DATE: estDate,
OFFICE_CODE: officeCode
};
oModel.create("/MRU_ESTSet", oEntry, {
method: "POST",
success: function(oData) {
//sap.m.MessageBox.alert("success sent!");
},
error: function(oError) {
//sap.m.MessageBox.alert("Error Saving Entries!!");
}
});
}
oModel.submitChanges({
success: function(oData, response) {
sap.m.MessageBox.success("Success Saving Entries!");
},
error: function(oError) {
sap.m.MessageBox.error("Error Saving Entries!!");
}
});
} else {
sap.m.MessageBox.alert("No Changes To Submit");
}
},

Retrieving and Updating a Record not Working in MS CRM

this is my scenario. As I am new to Microsoft Dynamics coding, need a solution for my code.
I have two entities named Acc and Con, where Acc is parent and Con is child entity of Acc.
I have created a lookup field of Acc in Con entity along with fields with similar datatype in the two entities.
So, whenever a change in parent record is made in the fields and saved, the changes should be done automatically in the corresponding fields of the child record.
The part I get the error is to update but am able to retrieve the code. So the record fails to update.
The error I get now is
ReferenceError: FetchRecordsCallBack is not defined at Object.GetRecs.jQuery.ajax.success
Your answers and suggestions are requested and welcome. :) Here below is my code.
function accupdate() {
debugger;
var PrvdLocData;
var name;
var age;
var sex;
var address;
var phonenumber;
var degree;
var sslcpercentage;
var hscpercentage;
var ugpercentage;
var PrvdLocData = new Array();
var EmpId = Xrm.Page.data.entity.getId();
//parent fields
if (Xrm.Page.getAttribute("new_name").getValue() != null) {
name = Xrm.Page.getAttribute("new_name").getValue();
}
if (Xrm.Page.getAttribute("new_age").getValue() != null) {
age = Xrm.Page.getAttribute("new_age").getValue();
}
if (Xrm.Page.getAttribute("new_sex").getValue() != null) {
sex = Xrm.Page.getAttribute("new_sex").getValue();
}
if (Xrm.Page.getAttribute("new_address").getValue() != null) {
address = Xrm.Page.getAttribute("new_address").getValue();
}
if (Xrm.Page.getAttribute("new_phonenumber").getValue() != null) {
phonenumber = Xrm.Page.getAttribute("new_phonenumber").getValue();
}
if (Xrm.Page.getAttribute("new_degree").getValue() != null) {
degree = Xrm.Page.getAttribute("new_degree").getValue();
}
if (Xrm.Page.getAttribute("new_sslcpercentage").getValue() != null) {
sslcpercentage = Xrm.Page.getAttribute("new_sslcpercentage").getValue();
}
if (Xrm.Page.getAttribute("new_hscpercentage").getValue() != null) {
hscpercentage = Xrm.Page.getAttribute("new_hscpercentage").getValue();
}
if (Xrm.Page.getAttribute("new_ugpercentage").getValue() != null) {
ugpercentage = Xrm.Page.getAttribute("new_ugpercentage").getValue();
}
var context = Xrm.Page.context;
var serverurl = context.getClientUrl();
var ODatapath = serverurl + "/XRMServices/2011/OrganizationData.svc";
var retrieveResult = new XMLHttpRequest();
var dtqeurl = ODatapath + "/new_conSet?$select=new_name,new_YourAge,new_YourSex,new_HomeAddress,new_Contact,new_DegreeType,new_SSLCPercent,new_HSCPercent,new_conId,new_UGPercent&$filter=new_AccName/Id eq guid'" + EmpId + "'";
GetRecs("PrvtLoc", dtqeurl);
function GetRecs(entity, url) {
jQuery.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: url,
async: false,
beforeSend: function XMLHttpRequest(XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null && data.d.results != null) {
AddRecordsToArray(data.d.results, entity);
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
// alert("Error : has occured during retrieval of the records ");
}
});
}
function AddRecordsToArray(result, entity) {
$.each(result, function () {
if (entity == "PrvtLoc")
PrvdLocData.push(this);
});
}
if (PrvdLocData.length > 0) {
for (i = 0; i < PrvdLocData.length; i++) {
//Object Assigning
var crmobject = new Object();
//Variable declaration for Child entity's primarykey (ID)
var childId = PrvdLocData[i].new_conId;
//Setting child entitiy's value with parent entity's variable
crmobject.new_name = name;
crmobject.new_YourAge = parseInt(age);
crmobject.new_YourSex = sex;
crmobject.new_HomeAddress = toString(address);
crmobject.new_Contact = parseInt(phonenumber);
crmobject.new_DegreeType = degree;
crmobject.new_SSLCPercent = sslcpercentage;
crmobject.new_HSCPercent = hscpercentage;
crmobject.new_UGPercent = ugpercentage;
// update starts...
var serverUrl = Xrm.Page.context.getClientUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var crmobject = new Object();
// Specify the ODATA entity collection
var ODATA_EntityCollection = "/new_conSet";
var jsonEntity = window.JSON.stringify(crmobject);
//Asynchronous AJAX function to Create a CRM record using OData
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection + "(guid'" + childId + "')",
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
XMLHttpRequest.setRequestHeader("Accept", "application/json");
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
success: function (data, textStatus, XmlHttpRequest) {
alert("updated");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("fail to update");
}
});
}
}
}
crmobject.new_name = name;
crmobject.new_YourAge = parseInt(age);
crmobject.new_YourSex = { Value: sex };
crmobject.new_HomeAddress = address;
crmobject.new_Contact = parseInt(phonenumber);
crmobject.new_DegreeType = { Value: degree };
crmobject.new_SSLCPercent = parseFloat(sslcpercentage).toFixed(2);
crmobject.new_HSCPercent = parseFloat(hscpercentage).toFixed(2);
crmobject.new_UGPercent = parseFloat(ugpercentage).toFixed(2);

Using parse.com is it possible to convert a string so that it saves as a pointer in the object browser?

Using parse.com and JavaScript.
Currently I have a BadgeSentTo which is a string taken from a html option box. I want to save this to parse, but ideally I want to save it into a pointer column "SentTo" so that it links back to the _User class.
It wont let me save as is, because its expecting a pointer. Is there a why to convert this to a pointer in the code?
$(document).ready(function () {
$("#send").click(function () {
var myBadge = new MyBadge();
var badgeselected = $('#badgeselect img').attr("src");
var BadgeSentTo = $('#SentToUser').val();
var uploadercomment = $('#UploaderComment').val();
myBadge.set("BadgeName", badgeselected);
myBadge.set("Comment", uploadercomment);
myBadge.set("uploadedBy", Parse.User.current());
myBadge.set("SentTo", BadgeSentTo).id;
myBadge.save(null, {
success: function (results) {
console.log("Done");
//location.reload();
},
error: function (contact, error) {
// The save failed.
alert("Error: " + error.code + " " + error.message);
}
});
return false;
});
});
The query capturing the data is
var currentUser = Parse.User.current();
var FriendRequest = Parse.Object.extend("FriendRequest");
var query = new Parse.Query(FriendRequest);
query.include('toUser');
query.include('SentTo');
query.include("myBadge");
query.equalTo("fromUser", currentUser);
query.equalTo("status", "Request sent");
query.find({
success: function (results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').id
});
var select = document.getElementById("selectNumber");
$.each(friends[0], function (i, v) {
//alert(i+" "+v);
var opt = v;
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
})
}
If BadgeSentTo contains the objectId of the User, you'll need to wrap that in a Parse Object. The SDK will convert it to a pointer to _User when it saves.
myBadge.set("SentTo", new Parse.User({id: BadgeSentTo}));

Categories