StackOverflow API - Trouble Displaying Results - javascript

I am kind of new to API's and I have the hang of some of it, but not quite all of it yet. When I type in a tag, such as "HTML" or "JavaScript", I am trying to write a program that will give me the top answerers for that tag. When I type in my result, it says "20 results for undefined," so for some reason, I don't think my code is "communicating" propertly.
I think it has to do with my "Tagged: answered" part, but I'm not sure. What do you guys think?
HTML:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Stack Overflow AJAX Demo</title>
<link rel="stylesheet" href="css/main.css">
</head>
<body>
<div class="container">
<div class="intro">
<div class="left stack-image"></div>
<div class="explanation">
<h1>StackOverflow Reputation Builder</h1>
<p>This app lets you search by topic for unanswered questions on Stack Overflow to help you build your reputation. Find unanswered questions for a topic you know about, write quality answers, and watch your reputation go up.</p>
<p>Sometimes, you also need some inspiration. This page also lets you search for the top answerers for a tag. If you want to rise to the top ranks for a topic, see how many reputation points you'll need to aim for!</p>
</div>
</div>
<hr>
<div class="stack">
<h3>Get Unanswered Questions</h3>
<p>Find unanswered questions by tag. For multiple tags, use a semi-colon to separate.</p>
<form class="unanswered-getter" onsubmit="return false;">
<input type="text" placeholder='e.g., "HTML" or "HTML;CSS"' name="tags" size="30" autofocus required>
<input type="submit" value="Submit">
</form>
<h3>View the Top Answerers for a Tag</h3>
<form class="inspiration-getter" onsubmit="return false;">
<input type="text" placeholder="e.g., jQuery" name="answerers" size="30" required>
<input type="submit" value="Submit">
</form>
</div>
<div class="results-container">
<div class="search-results"></div>
<div class="results"></div>
</div>
</div>
<div class="templates hidden">
<dl class="result question">
<dt>Question</dt>
<dd class="question-text"></dd>
<dt>Asked</dt>
<dd class="asked-date"></dd>
<dt>Viewed</dt>
<dd class="viewed"></dd>
<dt>Asker</dt>
<dd class="asker"></dd>
</dl>
<dl class="resultAnswerer">
<dt>Name of Answerer:</dt>
<dd class="answererName"></dd>
<dt>Score:</dt>
<dd class="scoreAmount"></dd>
<dt>Reputation:</dt>
<dd class="reputationAmount"></dd>
</dl>
<div class="error">
<p>Uh-oh! Something went wrong with your request. Here's what we know:</p>
</div>
</div>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/app.js"></script>
</body>
</html>
Javascript:
var showQuestion = function(question) {
var result = $('.templates .question').clone();
var questionElem = result.find('.question-text a');
questionElem.attr('href', question.link);
questionElem.text(question.title);
var asked = result.find('.asked-date');
var date = new Date(1000*question.creation_date);
asked.text(date.toString());
var viewed = result.find('.viewed');
viewed.text(question.view_count);
var asker = result.find('.asker');
asker.html('<p>Name: <a target="_blank" '+
'href=http://stackoverflow.com/users/' + question.owner.user_id + ' >' +
question.owner.display_name +
'</a>' +
'</p>' +
'<p>Reputation: ' + question.owner.reputation + '</p>'
);
return result;
};
var topScorers = function(score){
var result = $('.templates .resultAnswerer').clone();
var answererDisplayName = result.find('answererName');
answererDisplayName.text(score.display_name);;
var answererScore = result.find('scoreAmount');
answererScore.text(score.score);
var answererReputation = result.find('reputationAmount');
answererReputation.text(score.reputation);
return result;
}
var showSearchResults = function(query, resultNum) {
var results = resultNum + ' results for <strong>' + query + '</strong>';
return results;
};
var showError = function(error){
var errorElem = $('.templates .error').clone();
var errorText = '<p>' + error + '</p>';
errorElem.append(errorText);
};
var getUnanswered = function(tags) {
var request = { tagged: tags,
site: 'stackoverflow',
order: 'desc',
sort: 'creation'};
$.ajax({
url: "http://api.stackexchange.com/2.2/questions/unanswered",
data: request,
dataType: "jsonp",//use jsonp to avoid cross origin issues
type: "GET",
})
.done(function(result){ //this waits for the ajax to return with a succesful promise object
var searchResults = showSearchResults(request.tagged, result.items.length);
$('.search-results').html(searchResults);
$.each(result.items, function(i, item) {
var question = showQuestion(item);
$('.results').append(question);
});
})
.fail(function(jqXHR, error){
var errorElem = showError(error);
$('.search-results').append(errorElem);
});
};
var getAnswerers = function(answered){
var request = {
tagged: answered,
site: 'stackoverflow',
order: 'desc',
sort: 'score',
};
$.ajax({
url: "http://api.stackexchange.com/2.2/tags/" + answered + "/top-answerers/all_time",
data: request,
dataType: "jsonp",
type: "GET",
})
.done(function(result){
var searchResults = showSearchResults(request.tagged, result.items.length);
$('.search-results').html(searchResults);
$.each(result.items, function(i,item){
var score = topScorers(item);
$('.results').append(score);
});
})
.fail(function(jqXHR, error){
var errorElem = showError(error);
$('.search-results').append(errorElem);
});
}
$(document).ready( function() {
$('.unanswered-getter').submit(function(){
$('.results').html('');
var tags = $(this).find("input[name='tags']").val();
getUnanswered(tags);
});
$('.inspiration-getter').submit(function(){
$('.results').html('');
var answered = $(this).find("input[name='tags']").val();
getAnswerers(answered);
});
});

You're probably calling the getAnswer on submit of a form. Form submission will destroy the Javascript context. To make it work correctly, you should use simple click instead of submit.
Check code below:
<html>
<head>
<script src="jquery-1.10.2.min.js"></script>
<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<style>
img {
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<input class="tag"/><button class="search">Search</button>
<div class="search-results"></div>
<script>
var topScorers = function(score){
//Clone result template ode
var result = $('.templates .resultAnswerer').clone();
//set the display name in result
var answererDisplayName = result.find('answererName');
answererDisplayName.text(score.display_name);;
//set the user score amount in result
var answererScore = result.find('scoreAmount');
answererScore.text(score.score);
//set the user reputation amount in result
var answererReputation = result.find('reputationAmount');
answererReputation.text(score.reputation);
return result;
}
var getAnswerers = function(answered){
//the parameters I need to pass in our request to StackOverflow's API
var request = {
tagged: answered,
site: 'stackoverflow',
order: 'desc',
sort: 'score',
};
$.ajax({
//the parameters I need to pass in our request to stackOverFlow's API
//this is the endpoint that I want to use
url: "http://api.stackexchange.com/2.2/tags/" + answered + "/top-answerers/all_time",
data: request,
dataType: "jsonp",
type: "GET",
})
//what the function should do if successful
.done(function(result){
//this gives you the search result description
//var searchResults = showSearchResults(request.tagged, result.items.length);
showResults(result.items);
})
//what the function should do if it fails
.fail(function(jqXHR, error){
$('.search-results').text(JSON.stringify(error));
});
}
function showResults (result) {
var tbody = "";
var thead = "";
var firstEl = result[0];
var propArr = [];
for(var prop in firstEl) {
if(typeof firstEl[prop] !== "object") {
thead += "<th>" + prop + "</th>";
propArr.push(prop);
} else {
var obj = firstEl[prop]
for(var propdeep in obj) {
thead += "<th>" + propdeep + "</th>";
propArr.push(propdeep);
}
}
}
result.forEach(function (rowEl) {
var row = "<tr>";
var currentEl = null;
for(var i = 0; i < propArr.length; i++) {
currentEl = rowEl[propArr[i]];
if(currentEl === undefined) {
currentEl = rowEl["user"][propArr[i]]
}
if(propArr[i] !== "profile_image") {
row += "<td>"+ currentEl + "</td>";
} else {
row += "<td><img src='"+ currentEl + "'></img></td>";
}
}
row += "</tr>";
tbody += row;
});
var table = "<table><thead>" + thead + "</thead><tbody>" + tbody + "</tbody></table>";
$('.search-results').html(table);
}
$('.search').click(function(){
//zero out results if previous search has run
$('.search-results').html('');
//separate line of code
var answered = $(".tag").val();
getAnswerers(answered);
});
</script>
</body>
</html>
*Edit***********************
Since you're using "return false;" in submit of the forms, it's not submitting. That's actually clever as it saves us from having to attach both mouse and key events
There were 3 bugs in the code you posted last.
1> Input text field name is "answerers" but in the submit() function it's used as "tags".
var answered = $(this).find("input[name='tags']").val();
// should be
var answered = $(this).find("input[name='answerers']").val();
2> Data returned from the inspiration-getter form call has different structure than used. Actual structure of each item is as below.
{
post_count: 0,
score: 0,
user: {
display_name: "",
link: "",
profile_image: "",
reputation: 0,
user_id: 0,
user_type: ""
}
}
3> There should be a . (dot) before the selectors used in the topScorers() function.
var answererDisplayName = result.find('answererName'); //should be '.answererName'
answererDisplayName.text(score.display_name);;
var answererScore = result.find('scoreAmount'); //should be '.scoreAmount'
answererScore.text(score.score);
var answererReputation = result.find('reputationAmount'); //should be '.reputationAmount'
That's it,
Here is the working code after corrections,
app.js
var showQuestion = function(question) {
var result = $('.templates .question').clone();
var questionElem = result.find('.question-text a');
questionElem.attr('href', question.link);
questionElem.text(question.title);
var asked = result.find('.asked-date');
var date = new Date(1000*question.creation_date);
asked.text(date.toString());
var viewed = result.find('.viewed');
viewed.text(question.view_count);
var asker = result.find('.asker');
asker.html('<p>Name: <a target="_blank" '+
'href=http://stackoverflow.com/users/' + question.owner.user_id + ' >' +
question.owner.display_name +
'</a>' +
'</p>' +
'<p>Reputation: ' + question.owner.reputation + '</p>'
);
return result;
};
var topScorers = function(item){
var user = item.user;
var result = $('.templates .resultAnswerer').clone();
var answererDisplayName = result.find('.answererName');
answererDisplayName.text(user.display_name);;
var answererScore = result.find('.scoreAmount');
answererScore.text(item.score);
var answererReputation = result.find('.reputationAmount');
answererReputation.text(user.reputation);
return result;
}
var showSearchResults = function(query, resultNum) {
var results = resultNum + ' results for <strong>' + query + '</strong>';
return results;
};
var showError = function(error){
var errorElem = $('.templates .error').clone();
var errorText = '<p>' + error + '</p>';
errorElem.append(errorText);
};
var getUnanswered = function(tags) {
var request = { tagged: tags,
site: 'stackoverflow',
order: 'desc',
sort: 'creation'};
$.ajax({
url: "http://api.stackexchange.com/2.2/questions/unanswered",
data: request,
dataType: "jsonp",//use jsonp to avoid cross origin issues
type: "GET",
})
.done(function(result){ //this waits for the ajax to return with a succesful promise object
var searchResults = showSearchResults(request.tagged, result.items.length);
$('.search-results').html(searchResults);
$.each(result.items, function(i, item) {
var question = showQuestion(item);
$('.results').append(question);
});
})
.fail(function(jqXHR, error){
var errorElem = showError(error);
$('.search-results').append(errorElem);
});
};
var getAnswerers = function(answered){
var request = {
tagged: answered,
site: 'stackoverflow',
order: 'desc',
sort: 'score',
};
$.ajax({
url: "http://api.stackexchange.com/2.2/tags/" + answered + "/top-answerers/all_time",
data: request,
dataType: "jsonp",
type: "GET",
})
.done(function(result){
var searchResults = showSearchResults(request.tagged, result.items.length);
$('.search-results').html(searchResults);
$.each(result.items, function(i,item){
var score = topScorers(item);
$('.results').append(score);
});
})
.fail(function(jqXHR, error){
var errorElem = showError(error);
$('.search-results').append(errorElem);
});
}
$(document).ready( function() {
$('.unanswered-getter').submit(function(){
$('.results').html('');
var tags = $(this).find("input[name='tags']").val();
if(!tags || $.trim(tags) === "") {
alert("input is empty");
} else {
getUnanswered(tags);
}
});
$('.inspiration-getter').submit(function(){
$('.results').html('');
var answered = $(this).find("input[name='answerers']").val();
if(!answered || $.trim(answered) === "") {
alert("input is empty");
} else {
getAnswerers(answered);
}
});
});

I figured out part of what I did wrong.
I had name 'tags" instead of name 'answerers', so part of my problem is fixed.
Now if I get results, it will say "20 results of HTML" or "20 results of CSS" or whatever tag I use.
Now I just need to figure out why all of my results are blank. For some reason, it works for one button, but not the other.
JavaScript:
$('.inspiration-getter').submit(function(){
$('.results').html('');
var answered = $(this).find("input[name='tags']").val();
getAnswerers(answered);
});
HTML:
<form class="inspiration-getter" onsubmit="return false;">
<input type="text" placeholder="e.g., jQuery" name="answerers" size="30" required>
<input type="submit" value="Submit">
</form>

Related

How to append a div into a div with variables Javascript

I have this div here:
<div id='suggested_students'>
</div>
I am trying to write some javascript which will append this with the correct values:
<div id='STUDENT NAME' onClick='moveProfile("STUDENT NAME", "STUDENT ID")'>
STUDENT NAME<br>
STUDENT ID<br>
</div>
This is the javascript/ajax I have:
$('#search_bar').keyup(function () {
var keyword = $('#search_bar').val();
if(keyword.length > 2){
console.log('hey')
var url = window.location.pathname;
$.ajax({
method: 'GET',
url: url,
data: {
'keyword': keyword,
},
dataType: 'json',
success: function (data) {
var suggestions = data.students;
for(i = 0; i< suggestions.length; i++){
var current_student = suggestions[i];
console.log(current_student[0])
console.log(current_student[1])
}
}
});
}
})
and each iteration of the for loops produces something like:
[STUDENT NAME, STUDENT ID
How do I go about filling in these place holders and then appending the html to the main div for each student.
This will add the student information into the container div for you...
success: function (data) {
// get a reference to the container div
var $container = $("#suggested_students");
// remove any existing student information
$container.empty();
var suggestions = data.students;
for(i = 0; i< suggestions.length; i++){
var current_student = suggestions[i];
// create a new div to add to the container element
var $div = $("<div/>");
$div.data("name", current_student[0]);
$div.data("id", current_student[1]);
$div.html(current_student[0] + "<br/>" + current_student[1]);
$div.on("click", moveProfile);
$container.append($div);
}
}
There's a couple of things worth noting here. Firstly, I didn't give each new div the ID of the student name. There are several reasons for this, but the main one is that it's not a very friendly ID. Names have spaces and can also have other punctuation marks. Also, you can have multiple students with the same name, but you can't have multiple elements with the same ID.
Secondly, I set data attributes for each student div, rather than pass the values in an inline event handler. To handle the click event you'd need this extra function, already referenced above...
function moveProfile() {
var $this = $(this);
var studentId = $this.data("id");
var studentName = $this.data("name");
// do whatever you need with the student info here
}
Try this:
$('#search_bar').keyup(function () {
var keyword = $(this).val(), $suggested_students;
$suggested_students = $('#suggested_students');
if (keyword.length > 2) {
var url = window.location.pathname;
$.ajax({
method: 'GET',
url: url,
data: {
'keyword': keyword
},
dataType: 'json',
success: function (data) {
var i, suggestions, s_name, s_id, current_student;
suggestions = data.students;
// empty before
$suggested_students.empty();
for(i = 0; i< suggestions.length; i++){
current_student = suggestions[i];
s_id = current_student[0];
s_name = current_student[1]
$suggested_students.append(
"<div id='" + s_id + "' onClick='moveProfile(\"" + s_name + "\", \"" + s_id +"\")'>" +
s_id + " <br>" +
s_name + " <br>" +
"</div>"
);
}
}
});
}
});
I suggest, however, to abort the $.ajax call in case a new string is written or wait a few moments before executing a new one and avoid using onClick in this way: just add a class or a selector like #suggested_students > div and add a click event listener to each div inside the container.
for(i = 0; i< suggestions.length; i++){
var current_student = suggestions[i];
console.log(current_student[0])
console.log(current_student[1])
var div = "<div id='"+current_student[0]+"' onClick='moveProfile(\""+current_student[0]+"\", "+current_student[1]+")'>"+current_student[0]+"<br>"+current_student[1]+"<br></div>";
$('#suggested_students').append(div);
}

Image source shows up as undefined in IE but works in Chrome

I am trying to display several images(PrinurlonPage) that are contained in an array and also position them on the page randomly. I have two issues,
The first and most important is that I cant get the images to display on IE when I look the source attribute on developer tools I just see undefined whereas in chrome I get the full URL that was passed. I was wondering if there was something wrong with the order in which the script was being run that was causing the problem.
The second question is about positioning the images randomly on the page and also prevent overlapping, I would like to know how can I achieve this, what I have implemented at the moment in some iterations the pictures overlap.
I would appreciate any suggestion on this
var getIndividualPersonDetails = function(GetPictureUrl, printurlonPage, getRandom) {
listName = 'TeamInfo';
var PeopleCompleteList = [];
var personName, userName, UserTitle, UserphoneNumber, UserEmail, Id, myuserPicture;
// 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) {
personName = data.d.results[i]['Name'].Name.split('|')[2];
userName = data.d.results[i]['Name']['Name'];
UserTitle = data.d.results[i]['Name']['Title'];
UserphoneNumber = data.d.results[i]['Name']['WorkPhone'];
UserEmail = data.d.results[i]['Name']['EMail'];
Id = data.d.results[i]['Name']['Id'];
myuserPicture = GetPictureUrl(userName);
PeopleCompleteList.push(PersonConstructor(personName, UserTitle, UserphoneNumber, UserEmail, myuserPicture, Id));
}
}
PeopleObject = PeopleCompleteList;
PrinturlonPage(PeopleCompleteList, getRandom);
},
error: function() {
alert("Failed to get details");
}
});
}
//print all the image links in the peopleCompleteList array and then position them randomly on the page
var PrinturlonPage = function(PeopleCompleteList, getRandom) {
var imageList = [];
for (i = 0; i < PeopleCompleteList.length; i++) {
var top = getRandom(0, 400);
var left = getRandom(0, 400);
var right = getRandom(0, 400);
imageList.push('<img style="top:' + top + ';right:' + right + '" id="image' + PeopleCompleteList[i]['UserId'] + '" alt="' + PeopleCompleteList[i]['Title'] + '"class="imgCircle" src="' + PeopleCompleteList[i]['Picture'] + '"/>');
//imageList +='<img class="img-circle" src="'+PeopleCompleteList[i]['Picture']+ '"/>'
}
var imagesString = imageList.join().replace(/,/g, "");
$('#imageList').append(imagesString);
}
//funtion retrieves the picture
function GetPictureUrl(user) {
var userPicture="";
var imageurls="";
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 loginName = data.d.AccountName.split('|')[2];
console.log(loginName);
var PictureDetails = data.d.PictureUrl != null ? data.d.PictureUrl : 'https://xxxcompany/User%20Photos/Profile%20Pictures/zac_MThumb.jpg?t=63591736810';
imageurls = data.d.PersonalSiteHostUrl+'_layouts/15/userphoto.aspx?accountname='+ loginName+ '&size=M&url=' + data.d.PictureUrl;
userPicture1=imageurls;
}
});
return userPicture1;
}
var getRandom = function(x, y) {
return Math.floor(Math.random() * (y - x)) + x + 'px';
};
$(function() {
getIndividualPersonDetails(GetPictureUrl, PrinturlonPage, getRandom);
$(document).on('click', '.imgCircle', function() {
var theName = jQuery(this).attr('Id');
pullUserObject(theName);
//console.log(theId);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="imageList"></div>

ajax call returning null

I have this small script (fiddle) in charged for reading some blog XML. The problem is that it simply stopped working a few days ago. It seems the Ajax function is always returning null, even though there is data in the specified URL.
<script>
var toType = function(obj) {
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
var buildRSS = function (container_id){
$.ajax({
type: "GET",
url: "http://bloginstructions.blogspot.dk/rss.xml",
dataType: "xml",
success: function(result){
var values = getEntries(result)
console.log(result)
for (var i = 0; i < 10; i++) {
var entry = values[i],
info = entry.__text.split("\n"),
title = info[0],
link = info[1],
date = entry.pubdate.match(/(.*) \d/)[1],
snippet = entry.description.replace(/<\/?[^>]+(>|$)/g, "").substring(0,350)+'...';
var html = '<div><h4>' + title + '</h4><p>' + date + '</p><p>' + snippet + '</p></div>'
$('#' + container_id).append(html)
}
}
})
}
function getEntries(rawXML){
var x2js = new X2JS();
console.log(rawXML);
var xml = rawXML.responseText;
match = xml.match(/<item>(.*)<\/item>/);
xml = match[0] || '';
var json = x2js.xml_str2json(xml);
json = json.rss.channel.item;
return json
}
</script>
<div id="rssfeed">
</div>
<div id="rss">
</div>
<script>
$(document).ready(function() {
buildRSS('rssfeed')
});
</script>

How do I scroll down a chatbox (div) automatically?

I've been working on a chat application and now I need to scroll automatically when a message appears.
I've tried different things but they do not work unfortunately.
So this is my main.js code:
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "/refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
var message = $('#view_ajax');
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div>(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
message.html(data);
message.scrollTop(message[0].scrollHeight);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "/submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
I've used
var message = $('#view_ajax');
message.html(data);
message.scrollTop(message[0].scrollHeight);
I really have no clue how jQuery works. I've tried a couple of things before this but it didn't work also.
Do you have any suggestion? Any advice?
Do you need any more information? Feel free to ask!
Give each message an ID, as follows:
<div id="msg-1234">
Then you can scroll to this element using this jQuery:
$('html, body').animate({ scrollTop: $('#msg-1234').offset().top }, 'slow');
Alternatively, put a div at the bottom of your chat:
<div id="chat-end"></div>
And scroll to this ID instead.
JSFiddle Demo

Embedding Advanced Find View in Entity Form (Crm 2011)

We making a system so work on a list of records based on 'Fetch XML' the user specify. (Simple FetchXml field)
To make it easy we want to do a nice UI to edit the 'Fetch XML'.
We saw this solution - but it is for CRM 4.
Is there anything similar for CRM 2011?
// JavaScript source code
function SearchCustomers() {
var params = '';
var fullname = Xrm.Page.getAttribute("fullname").getValue();
if (fullname != null) {
params += "fullname" + GetParam(fullname);
}
var IFrame = Xrm.Page.ui.controls.get("IFRAME_advancedfind");
var url = getServerUrl() + "/WebResources/new_advancedfind.htm?Data=" + params;
IFrame.setSrc(url);
}
function GetParam(data) {
return "%3D" + encodeURIComponent(data) + "%26";
}
function getServerUrl() {
//var context = GetGlobalContext();
//var serverUrl = context.getClientUrl();
var serverUrl = window.location.protocol + "//" + window.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}
return serverUrl;
}
// new_advancedfind.htm Webresource
<HTML><HEAD><TITLE></TITLE>
<SCRIPT type=text/javascript src="ClientGlobalContext.js.aspx"></SCRIPT>
<SCRIPT type=text/javascript>
function submitForm() {
var fullname = "";
var vals = getDataParam();
fullname = GetParam(vals, 'fullname');
var filter = '<filter type="and"> <condition attribute="fullname" value="%' + fullname + '%" operator="like"/> <condition attribute="statecode" value="0" operator="eq"/> </filter>';
var fetch = '<fetch version="1.0" output-format="xml-platform" mapping="logical" distinct="false"><entity name="contact"><attribute name="fullname"/><attribute name="telephone1"/><attribute name="contactid"/><order attribute="fullname" descending="false"/>' + filter + '</entity></fetch>';
var form = document.getElementById("AdvancedFind");
form.action = getServerUrl() + '/AdvancedFind/fetchData.aspx';
form.LayoutXml.value = '<grid name="resultset" object="2" jump="lastname" select="1" icon="1" preview="1"><row name="result" id="contactid"><cell name="fullname" width="300" /><cell name="telephone1" width="125" /></row></grid>';
form.FetchXml.value = fetch;
form.submit();
}
function getServerUrl() {
//var context = GetGlobalContext();
//var serverUrl = context.getClientUrl();
var serverUrl = window.location.protocol + "//" + window.location.host + "/" + Xrm.Page.context.getOrgUniqueName();
if (serverUrl.match(/\/$/)) {
serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}
return serverUrl;
}
function getDataParam() {
//Get the any query string parameters and load them
//into the vals array
var RetVals = new Array();
var vals = new Array();
if (location.search != "") {
vals = location.search.substr(1).split("&");
for (var prmCounter = 0; prmCounter < vals.length; prmCounter++) {
vals[prmCounter] = vals[prmCounter].replace(/\+/g, " ").split("=");
}
//look for the parameter named 'data'
var found = false;
for (var _prmCounter = 0; _prmCounter < vals.length; _prmCounter++) {
if (vals[_prmCounter][0].toLowerCase() == "data") {
RetVals = parseDataValue(vals[_prmCounter][1]);
}
}
}
return RetVals;
}
function parseDataValue(datavalue) {
if (datavalue != "") {
return decodeURIComponent(datavalue).split("&");
}
}
function GetParam(vals, attribute) {
var val = '';
var found = false;
for (i = 0; i < vals.length && !found; i++) {
if (vals[i].indexOf(attribute) > -1) {
val = vals[i].split('=')[1];
found = true;
break;
}
}
return val;
}
</SCRIPT>
<META charset=utf-8></HEAD>
<BODY onload=submitForm()>
<FORM id="AdvancedFind" method="post" action="">
<INPUT name=FetchXml type=hidden>
<INPUT name=LayoutXml type=hidden>
<INPUT name=EntityName value=contact type=hidden>
<!--Replace DefaultAdvFindViewId valu to contact's default advanced find view Guid-->
<INPUT name=DefaultAdvFindViewId value={00000000-0000-0000-00AA-000000666400} type=hidden>
<INPUT name=ViewId value={00000000-0000-0000-00AA-000000666400} type=hidden>
<INPUT name=ViewType value=4230 type=hidden>
<INPUT name=SortCol value=fullname:1; type=hidden>
<INPUT name=UIProvider type=hidden>
<INPUT name=DataProvider type=hidden> </FORM></BODY></HTML>
I haven't tried this (yet) but I think it should be possible to do this (in a supported manner) using URL addressable views. Somehow create the view in CRM (either manually before time using adv find for example) or create it dynamically with JS. Then it should be possible to "invoke" the view per link above.
Disclaimer: This is all theory. If you get something working maybe let us know.
Yes, I did on the Dynamics CRM 2011, It's working all deployments, Online/OnPremise and Hosted(IFD),
Create a Javascript web-resource, and create your FetchXML then send to Custom advanced Find Web resource.
Create a Html web-resource for Showing Advanced Find Grid that execute created dynamic FetchXml for all Entity.

Categories