I am using the following java script code to retrieve contacts by account Id. I am set setting the alert message debugging. It does not enter in success call back message function.
Ending up with following error
Error while retrieval
"error" : { "lang":"en-US", "Value":"Syntax error'\ufffd' at position 20." }
I am using the following code.
function retrieveMultiple(odataSetName, select, filter, successCallback) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataUri = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "?";
alert("retrieveMultiple"+odataUri);
if (select) {
odataUri += "$select=" + select + "&";
alert("select error="+odataUri);
}
if (filter) {
odataUri += "$filter=" + filter;
alert("filter error="+odataUri);
}
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataUri,
beforeSend: function (XMLHttpRequest) {
//Specifying this header ensures that the results will be returned as JSON.
var x = XMLHttpRequest.setRequestHeader("Accept", "application/json");
alert(" in Ajax :beforeSend:" + x );
},
success: function (data, textStatus, XmlHttpRequest) {
alert("In success function outside success");
if (successCallback) {
alert("successCallback in if");
if (data && data.d && data.d.results) {
alert("data && data.d && data.d.results"+data + data.d + data.d.results);
successCallback(data.d.results, textStatus, XmlHttpRequest);
alert("data.d.results, textStatus, XmlHttpRequest" + data.d.results + textStatus + XmlHttpRequest);
}
else if (data && data.d) {
successCallback(data.d, textStatus, XmlHttpRequest);
}
else {
successCallback(data, textStatus, XmlHttpRequest);
}
}
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
alert(" In erro function");
if (XmlHttpRequest && XmlHttpRequest.responseText) {
alert(" In error function If");
alert("Error while retrieval ; Error – " + XmlHttpRequest.responseText);
}
}
});
}
function readRecordsOnSuccess(data, textStatus, XmlHttpRequest) {
// Loop through the retrieved records
for (var indx = 0; indx < data.length; indx++) {
alert("Name – " + data[indx].name);
}
}
function retrieveContactsByAccountId() {
// Pass ‘Contact’ set name since we are reading Contacts
var oDataSetName = "ContactSet";
// Column names of ‘Contact’ (Pass * to read all columns)
var columns = "FirstName";
// Read Account Guid
var accountId = Xrm.Page.data.entity.getId()
// Prepare filter
var filter = "AccountId/Id eq guid’" + accountId + "‘";
alert("retrieveContactsByAccountId"+filter);
retrieveMultiple(oDataSetName, columns, filter, readRecordsOnSuccess);
}
Looks like common mistype ;) Notice following string you are passing:
var filter = "AccountId/Id eq guid’" + accountId + "‘";
Your apostrophes are different from usual ones
You need to use regular '
var filter = "AccountId/Id eq guid'" + accountId + "'";
Related
I have two javascript functions madeAjaxCall() and getBookCall(bookId) to obtain book list and chapter list respectively.
I'm trying to call getBookCall(bookId) from within the function madeAjaxCall().
function madeAjaxCall(){
$.ajax({
type: "GET",
url: "http://localhost:8080/restApp/book/list",
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
delete_table();
if(data){
var len = data.length;
var txt = "";
txt += "<tr><th>"+"bookId"+"</th><th>"+"bookName"+"</th><th>"+"Chapter Details"+"</th></tr>";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].bookId != null && data[i].bookName != null){
/* txt += "<tr><td>"+data[i].bookId+"</td><td>"+data[i].bookName+"</td><td>"+"Chapter details"+"</td></tr>"; */
txt += "<tr><td>"+data[i].bookId+"</td><td>"+data[i].bookName+"</td><td>"+"Chapter details"+"</td></tr>";
}
}
if(txt != ""){
$("#table1").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;
}
And the other function
function getBookCall(bookId){
$.ajax({
type: "GET",
url: "http://localhost:8080/restApp/chapter/list/"+bookId,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
delete_table2();
if(data){
var len = data.length;
var txt = "";
txt += "<tr><th>"+"chapterId"+"</th><th>"+"chapterName"+"</th></tr>";
if(len > 0){
for(var i=0;i<len;i++){
if(data[i].chapterId != null && data[i].chapterName != null){
txt += "<tr><td>"+data[i].chapterId+"</td><td>"+data[i].chapterName+"</td></tr>";
}
}
if(txt != ""){
$("#table2").append(txt).removeClass("hidden");
}
}
}
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;
}
I am obtaining list of books as JSON from the function madeAjaxCall() and appending the list in a table. I want to call the function getBookCall(bookId) from within the function madeAjaxCall() with the help of a href. But i am unable to call the function getBookCall(bookId) using a href, from within the function madeAjaxCall().
This is the line from the function madeAjaxCall from where the function getBookCall(bookId) could not be called.
txt += "<tr><td>"+data[i].bookId+"</td><td>"+data[i].bookName+"</td><td>"+"Chapter details"+"</td></tr>";
Here In example I have use custom data-* attribute to store bookid, which can be fetched using .data(), create your anchor like:
txt += '<a class="myBookLink" href="#" data-bookid="' + data[i].bookId + '">Chapter details</a>";
Then use Event Delegation using .on() delegated-events approach to bind the click event handler of anchor.
$(document).on('click', function(){
getBookCall($(this).data('bookid'))
return false;
})
Important: In place of document you should always use closest static container.
For Immediate solution use quotes properly.
txt += "<tr><td>"
+ data[i].bookId
+ "</td><td>"
+ data[i].bookName
+'</td><td>Chapter details</td></tr>';
instead of
txt += "<tr><td>"+data[i].bookId+"</td><td>"+data[i].bookName+"</td><td>"+"Chapter details"+"</td></tr>";
I know this has been asked 1000 times before but I have hit a brick wall with this.^have created a web application that inserts user data and feedback for the user and the code below is basically part of the PhoneGap application. The strange thing is that the code works perfectly in a web browser but not in Phonegap (output iPad via Xcode).
Therefore would someone know why I am getting an undefined error for the following AJAX call, just after the success callback and the alert(data.ResultId). , any help is appreciated.
Thank you!
// POST: /Result/Create
[HttpPost]
public ActionResult Create(Result result)
{
if (ModelState.IsValid)
{
result.ResultDate = DateTime.Now;
repository.InsertResult(result);
repository.Save();
if (Request.IsAjaxRequest())
{
int ResultId = result.ResultId;
try
{ //valid database entry..send back new ResultId
return Json(new { Success = true, ResultId, JsonRequestBehavior.AllowGet });
}
catch
{ // no database entry
return Json(new { Success = false, Message = "Error", JsonRequestBehavior.AllowGet });
}
}
return RedirectToAction("Index");
}
return View(result);
}
Insert QnA
function InsertQnA() {
//hardcoded for testing
Q1 = 10;
Q2 = 10;
Q3 = 10;
Q4 = 10;
Q5 = 10;
Q6 = 10;
Q7 = 10;
Q8 = 10;
Q9 = 10;
Q10 = 10;
localStorage.setItem("Total",100);
localStorage.setItem("CaseStudy", 1);
localStorage.setItem("UserId",1);
Attempts = "1";
////////////////
$.ajax({
url: Domain + '/Result/Create',
cache: false,
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total") + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
// dataType : "json",
success: function (data) {
alert(data.ResultId);
if (data.Success==true) {
}
else if (data.Success==false) {
viewModel.UserId("Your entry has not been saved, please try again.");
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
}
The problem was that I was tying to use the same ActionResult to serve an MVC view as well as an htlm5 cordova iOS app. I got round this by copying the ActionResult but changing the return type to a string, note the code looks a bit different in the action, however the original worked fine too. Many thanks to all who posted
[HttpPost]
public string CreateResult(Result result)
{
result.ResultDate = DateTime.Now;
repository.InsertResult(result);
repository.Save();
if (result == null)
{
// User entity does not exist in db, return 0
return JsonConvert.SerializeObject(0);
}
else
{
// Success return user
return JsonConvert.SerializeObject(result, Formatting.Indented, new JsonSerializerSettings { PreserveReferencesHandling = PreserveReferencesHandling.Objects });
}
}
AJAX
$.ajax({
url: Domain + '/Result/CreateResult',
cache: false,
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: '{"Q1":"' + Q1 + '","Q2":"' + Q2 + '","Q3":"' + Q3 + '","Q4":"' + Q4 + '","Q5":"' + Q5 + '","Q6":"' + Q6 + '","Q7":"' + Q7 + '","Q8":"' + Q8 + '","Q9":"' + Q9 + '","Q10":"' + Q10 + '","Total":"' + localStorage.getItem("Total") + '","CaseStudy":"' + localStorage.getItem("CaseStudy") + '","UserId":"' + localStorage.getItem("UserId") + '","Attempts":"' + QnANumAttempts + '"}',
success: function (data) {
try {
if (data != 0) {
//result id used for feedback insertion > update result entity
localStorage.setItem("ResultId", data.ResultId);
viewModel.UserId("You have successfully completed case study " + localStorage.getItem("CaseStudy") + ", please fill out the <a href=evaluation.html target=_self>evaluation.<a/>");
//reset locals
ResetLocalStorage();
//count number of entities for User
CountUserEntitiesInResults();
}
else
{
viewModel.UserId("Your entry has not been saved, please try again.");
}
}catch(error) {
alert("This is the error which might be: "+error.message);
}
},
}).fail(
function (xhr, textStatus, err) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(err);
});
I want to retrieve multiple record. Here is my code;
function GetQuoteDetails(quoteId) {
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
var odataSetName = "QuoteDetailSet";
var odataSelect = serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "$filter=QuoteId/Id eq guid'" + quoteId + "'";
var jSonArray = new Array();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataSelect,
beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
success: function (data, textStatus, XmlHttpRequest) {
if (data && data.d != null) {
jSonArray.push(data.d);
}
},
});
return jSonArray;
}
It returns nothing. But there should be 4 records returned. Where is the problem?
Since this is Asynchronous call, you cannot return from function GetQuoteDetails. For verification either use Console.log or alert to check what is data.d value.
Right now I have username and password saved in cookies. My goal is to send that data to my server and then the server will send back response and I will display the response on my webpage. But before I do that I used alert() to see if it is working.
I think something is wrong with the JS:
$(document).ready(function () {
var messageType = "3";
var cookie_name = "username";
var cookie_name2 = "password";
var YouWrote = getName(cookie_name);
var YouWrote2 = getName2(cookie_name2);
var userName = YouWrote;
var password = YouWrote2;
auth(messageType, userName, password);
});
function auth(messageType, userName, password) {
$.ajax({
type: "POST",
//SEND TO SERVER URL
url: "######",
dataType: 'json',
async: false,
data: '{"messageType": "' + messageType + '", "userName": "' + userName + '", "password" : "' + password + '"}',
error: function (xhr, error) {
alert('Error!');
},
success: function (data, textStatus, jqXHR) {
alert(data.details + '\nHello ' + data.clientInfo.firstName + ' ' + data.clientInfo.lastName + '. \nBalance:' + data.clientInfo.balance);
}
})
}
These two functions will help me get the cookie data saved (this works, I have tested it):
function getName() {
if (document.cookie) {
index = document.cookie.indexOf(cookie_name);
if (index != -1) {
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {
nameend = document.cookie.length;
}
YouWrote = document.cookie.substring(namestart, nameend);
return YouWrote;
}
}
}
function getName2() {
if (document.cookie) {
index = document.cookie.indexOf(cookie_name2);
if (index != -1) {
namestart = (document.cookie.indexOf("=", index) + 1);
nameend = document.cookie.indexOf(";", index);
if (nameend == -1) {
nameend = document.cookie.length;
}
YouWrote2 = document.cookie.substring(namestart, nameend);
return YouWrote2;
}
}
}
I turned my server off on purpose because I want to see if it will show alert("Error!"). It doesn't which means the functions aren't running properly in the document.ready.
Is there an obvious issue that I'm missing? Any help will be much appreciated.
Your functions will need to have input argument specified:
function getName(cookie_name){ ... };
function getName2(cookie_name2){ ... };
I'm creating a custom button in the MS CRM ribbon that create a record in an entity, (i'm using odata), this button lunch a JavaScript function that use 'GetGlobalContext' method to get the context, im facing the below problem:
The value of the property 'GetGlobalContext' is null or undefined
here is my sample code :
//Parameters
var ODataPath;
var serverUrl;
//add the below script to the page DOM
var imported = document.createElement('script');
imported.src = 'ClientGlobalContext.js.aspx';
document.getElementsByTagName('head')[0].appendChild(imported);
//On COnvert to case click
function OnConvertClick(message) {
alert(Xrm.Page.getAttribute(message).getValue());
var data = {
subject: Xrm.Page.getAttribute(message).getValue()
};
CreateCaseOffer("incident", data);
}
//create case from an activity
function CreateCaseOffer(EntityName, data) {
var context = GetGlobalContext(); //GetGlobalContext function exists in ClientGlobalContext.js.aspx
serverUrl = location.protocol + "//" + location.hostname + ":" + location.port + "/" + context.getOrgUniqueName();
ODataPath = serverUrl + "/XRMServices/2011/OrganizationData.svc";
var jsonCaseOffers = window.JSON.stringify(data);
if (jsonCaseOffers != null) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: ODataPath + "/" + EntityName + "Set",
data: jsonCaseOffers,
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
success: function (data, textStatus, XmlHttpRequest) {
$.each(data, function (k, v) {
alert(k + " - " + v);
});
},
error: function (XmlHttpRequest, textStatus, errorThrown) {
}
});
}
}
any suggestions ??
it works fine now with var
var context = Xrm.Page.context;
instead of
var context = GetGlobalContext();