Retrieveing Multiple lines of text using var query - javascript

I currently have a JS file which displays a single line know issue entered by a user via a SharePoint list. The div id it displays on the page is 'knowntitle'.
I now have been asked to display further information, so that the user would have another field to fill in on the SharePoint list called Further Details would be a Multiple Lines of Text field.
I wrote the original pages a year ago, and I'm a bit rusty! I've made a start and commented out what I've done so far. Any help on how to proceed would be gratefully received, js below:
function getDeviceKnownIssues() {
//var txtfurtherinfo = "";
var txtTitleKnown = "<ol>";
var query = "http://xxx/sites/it/ITInfrastructure/_vti_bin/listdata.svc//Knownissues?$filter=DeviceID eq " + window.DeviceId + "";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function(data, textStatus, jqXHR) {
$.each(data.d.results, function(index, item) {
var KnownTitle = item.Title;
//var FurtherInfo = item.Info;
txtTitleKnown = txtTitleKnown + "<li>" + KnownTitle + "</li>";
});
txtTitleKnown = txtTitleKnown + "</ol>";
//$('furtherinfo').append(txtName);
$('#knowntitle').append(txtTitleKnown);
});
call.fail(function(jqXHR, textStatus, errorThrown) {
alert("Error retrieving data: " + jqXHR.responseText);
});
}

You can concatenate the further info together with line breaks \r\n and them display them in the cell:
$.each(data.d.results, function(index, item) {
txtTitleKnown += "<li>" + item.Title + "</li>";
if(item.Info != undefined) {
txtfurtherinfo += item.Info + "\r\n";
}
});
txtTitleKnown = txtTitleKnown + "</ol>";
$('#knowntitle').append(txtTitleKnown);
$('#furtherinfo').append(txtfurtherinfo);

Related

jQuery mobile mega dropdown adds more and more buttons

I am using a jquery plugin to generate a mega dropdown on my mobile website:
The menu is generated dynamically: everytime the user clicks on the right arrow, an api call is made to gather all sub-points to the clicked menu-entry. Down the menu everything works fine, but when I click on "back" it seems that there is added a forward/back-button for each menu-level:
This is my code:
// Catching the click-event
$(document).on('click','.next-button', function(){
var subCatContainer = $(this).next('.subcats');
var current = $(this).parent('.shopCatWithSub');
var categoryid = current.data('categoryuuid');
console.log('Next clicked');
console.log(categoryid);
if(typeof categoryid !== "undefined"){
buildSubcats(categoryid, subCatContainer, standardUrl);
} else {
console.log("No category set!");
}
});
// Get subcategories from API:
function buildSubcats(catid, subCatContainer, standardUrl) {
$.ajax({
type: 'GET',
url: 'https://my-awesome-url.de/api?category-id=' + catid,
dataType: 'jsonp',
contentType: 'application/json',
success: function (data) {
handleResponse(data, subCatContainer, standardUrl);
},
error: function(XMLHttpRequest, textStatus, errorThrow) {
console.log(errorThrow);
if (jQuery.isFunction(callback)) {
}
}
});
}
// Build and add new nav-elements:
function handleResponse(data, subCatContainer, standardUrl){
var output = '';
$.each(data, function(key, category){
var element = '';
var uladd = "";
var aClassAdd = "";
if(category.hasSubcategories) {
uladd = '<ul class="subcats"></ul>';
aClassAdd = 'has-next-button';
}
element = '<li class="shopCatWithSub" data-categoryuuid="' + category.categoryUUID + '">'
+ '<a class="text-truncate menu-item ' + aClassAdd + '" href="' + standardUrl + category.categoryUUID + '">'
+ '<i class="icon-' + category.categoryIconClass + ' mr-2"></i>'
+ category.displayName
+ '</a>'
+ uladd
+ '</li>';
output += element;
});
subCatContainer.empty();
subCatContainer.html(output);
// Re-initialize menu
$('.nav-mobile').mobileMegaMenu();
}
I assume that there is a problem with the re-initializing of the complete menu-structure. But I can't figure out how to handle it.

Flickr API loading images

Hello I am new to APIs and I am struggling a lot with the Flickr API. I tried looking up videos and articles and it was overwhelming. What I am trying to do for my project is have a user search up restaurants using the Yelp API. Once they get a list of restaurants, each list item will have a select button. When the user clicks the select button, images of that location should pop up in a div on the HTML page. I manage to get the Yelp API to work however I am struggling with how to make the images load when the user clicks the select button. I am completely lost and any help would be appreciated. Below is my code.
HTML:
<div class="col-xs-6">
<h2 id="title">Manhattan</h2>
<div>
<h2>Photos</h2>
<div id="photos"></div>
</div>
</div>
JavaScript:
$(document).ready(function () {
$('#getposts_form').submit(function(event) {
event.preventDefault();
$('#output').empty();
var search = $('#search').val();
var title = $('#title').text();
var categories = $('#categories').val();
var price = $("#price").val();
console.log(search);
console.log(categories);
console.log(price);
$("#ajaxIndicator").modal('show');
// make the ajax request
$.ajax({
url: 'yelp.php',
type: 'GET',
dataType: 'JSON',
data: {
location: title,
categories: categories,
price: price
},
success: function(serverResponse) {
console.log(serverResponse);
var businesses = serverResponse.businesses;
console.log(businesses);
var myHTML = '';
for(var i = 0; i < serverResponse.businesses.length; i++){
myHTML += '<li class="tweet list-group-item">';
myHTML += '<ul class="list">'
myHTML += '<li><span class="user"><b>' + serverResponse.businesses[i].name + '</b></span></li>';
myHTML += '<li><span class="user">' + serverResponse.businesses[i].price + '</span></li>';
myHTML += '<li><span class="user">' + serverResponse.businesses[i].latitude + '</span></li>';
myHTML += '<li><span class="user">' + JSON.stringify(serverResponse.businesses[i].categories) + '</span></li>';
myHTML += '<li><span class="user"><button class="btn btn-default" type="submit" id="select">Select</button></span><li>';
myHTML += '</ul>'
myHTML += '</li>';
}
$('#output').append(myHTML);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error');
console.log(errorThrown);
console.log(jqXHR);
},
complete: function() {
$("#ajaxIndicator").modal('hide');
}
});
});
//ajax call for flickr api
$('.select').submit(function(event) {
event.preventDefault();
$('#photos').empty();
var lat = $('#lat').val();
var long = $('#long').val();
$("#ajaxIndicator").modal('show');
make the ajax request
$.ajax({
url: 'http://api.flickr.com/services/rest/?method=flickr.photos.search&api_key="here i added my own key"&format=json&nojsoncallback=1',
type: 'GET',
dataType: 'JSON',
data: {
//lat: lat,
//long:long,
},
success: function(serverResponse) {
console.log("flickr");
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error');
console.log(errorThrown);
console.log(jqXHR);
},
complete: function() {
$("#ajaxIndicator").modal('hide');
}
});
});
What you need to do is
Extract the urls and store them in an array
Loop through array, creating a new child image with the src set correctly
var photos = $("#photos")
for (var i = 0; i < arr.length; i++) {
var image = "<img src=" + encodeURL(arr[i]) + "></img>"
photos.append(image)
}
I think that you should focus on simpler apis for the time being

JQuery Ajax button isn't working

I am extremely new at writing ajax and working with a restful api... so, bear with me.
I have a Laravel 5.2 RESTful API that I am using on the backend, and I'm attempting to simply load a list of categories using Jquery / Ajax. As you click through the categories, each child category loads fine, but I cannot seem to get the "back" button to work (by this, I mean the LI I am generating, not the browser back button). When you click it, it shows the alert - and the data is correct, but that's it. The list doesn't refresh and populate with the appropriate items.
EDIT
There are no errors being thrown to the javascript console either. It just won't populate from the ajax call.
EDIT
I removed the request.abort() right after I made the original post.
EDIT
Here is the JSON returned from the URL api/categories/4 - as an example.
[{"id":6,"parent":4,"name":"sub_subcat4_1","slug":"sub_subcat4_1","description":null,"created_at":null,"updated_at":null},{"id":7,"parent":4,"name":"sub_subcat4_2","slug":"sub_subcat4_2","description":null,"created_at":null,"updated_at":null}]
EDIT
Here is the HTML for the #categories
<div class="row">
<div class="col-sm-12">
<ul id="categories">
</ul>
</div>
The Javascript
<script>
/*
* This loads the default / root categories.
*/
function getRootCategories() {
$.getJSON("api/categories", function(data) {
var categories = [];
$("#categories").html("");
$.each(data, function(key, val) {
$("#categories").append("<li class='subcat' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>');
});
});
}
/*
* This loads the sub categories if there's any data returned. Otherwise, just leave the user where they are.
*/
function getSubcats(cat) {
var dataID = cat.getAttribute("data-id");
alert(dataID);
if(dataID == "null") {
getRootCategories();
}
else {
$.getJSON("api/categories/" + dataID, function (data) {
if (data.length != 0) {
$("#categories").html("");
var newCats = '';
var parent = '';
$.each(data, function (key, val) {
parent = "<li class='subcat' data-id='" + val.parent + "' onClick='getSubcats(this);'>Back</li>";
newCats += "<li class='subcat' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>';
});
$("#categories").append(parent + newCats);
}
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache:false });
getRootCategories();
});
</script>
Ok, I just had my variables all mixed up. I wasn't setting the correct parent id.
The new script looks like this -
<script>
var previous = null;
/*
* This loads the default / root categories.
*/
function getRootCategories() {
$.getJSON("api/categories", function(data) {
var categories = [];
$("#categories").html("");
$.each(data, function(key, val) {
$("#categories").append("<li class='subcat' data-parent='" + val.parent + "' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>');
previous = val.parent;
});
});
}
/*
* This loads the sub categories if there's any data returned. Otherwise, just leave the user where they are.
*/
function getSubcats(cat) {
var dataID = cat.getAttribute("data-id");
previous = cat.getAttribute("data-parent");
if(dataID == "null") {
getRootCategories();
}
else {
$.getJSON("api/categories/" + dataID, function (data) {
if (data.length != 0) {
$("#categories").html("");
var newCats = '';
var parent = '';
$.each(data, function (key, val) {
parent = "<li class='subcat' data-id='" + previous + "' onClick='getSubcats(this);'>Back</li>";
newCats += "<li class='subcat' data-parent='" + val.parent + "' data-id='" + val.id + "' onClick='getSubcats(this);'>" + val.name + '</li>';
});
$("#categories").append(parent + newCats);
}
})
.fail(function(jqxhr, textStatus, error) {
console.log("Request Failed: " + textStatus + " - " + error);
});
}
}
$(document).ready(function() {
$.ajaxSetup({ cache:false });
getRootCategories();
});
</script>

sometimes ajax works & sometime not & click on row function is also not working

can we write two ajax success function on same page because sometimes its work sometime not
doajaxpost function is to load data in 2nd dropdown list when 1st dropdown list onchange function call by using ajax
and searching function is to load data in table by using ajax
but it sometime get execute properly sometimes not showing any result
function doAjaxPost(instituteId) {
alert(instituteId);
// get the form values
/* var name = $('#name').val();
var education = $('#education').val(); */
$.ajax({
type : "POST",
url : "/paymentGateway/merchant",
dataType : "json",
data : "institutionId=" + instituteId,
success : function(data) {
// we have the response
alert(data + "hiee");
var $merchantId = $('#merchant');
$merchantId.find('option').remove();
$("#merchant").append("<option value='ALL'>ALL</option>");
$.each(data, function(key, value) {
$('<option>').val(value.merchantId).text(value.merchantId)
.appendTo($merchantId);
});
},
error : function(e) {
alert('Error: ' + e);
}
});
}
function searching() {
// get the form values
var institutionId = $('#instiuteId').val();
var merchantId = $('#merchant').val();
var userType = $('#userType').val();
var userStatus = $('#userStatus').val();
var userId = $('#userId').val();
alert("insti=" + institutionId + "mecrhant=" + merchantId + "usertyep="
+ userType + "users=" + userStatus + "userid=" + userId);
$.ajax({
type : "POST",
url : "/paymentGateway/searching",
dataType : "json",
data : {
institutionId : institutionId,
merchantId : merchantId,
userId : userId,
userStatus : userStatus,
userType : userType
},
success : function(data) {
// we have the response
alert(data);
/* var $merchantId = $('#dynamictable');
$merchantId.find('table').remove();
$('#dynamictable').append('<table></table>');
var table = $('#dynamictable').children(); */
$("#tablenew tbody tr:has(td)").remove();
$.each(data, function(key, value) {
/* alert(value.institutionId); */
$('#tablenew tbody:last').append(
"<tr><td>" + value.userId + "</td><td>"
+ value.firstName + "</td><td>"
+ value.userStatus + "</td><td>"
+ value.userType + "</td><td>"
+ value.userAddedBy + "</td><td>"
+ value.userRegisteredDateTime
+ "</td><td>" + value.recordLastUpdatedBy
+ "</td><td>" + value.recordLastUpdatedTime
+ "</td></tr>");
});
},
error : function(e) {
alert('Error: ' + e);
}
});
}
It could be a caching issue, try to setup
$.ajaxSetup({ cache: false });
See
How to prevent a jQuery Ajax request from caching in Internet Explorer?
I got the same problem. You'll have to use the class instead of ID to make it work. Use $(".merchant") to replace $("#merchant"), and update 'merchant' to be a class.

Can't Grab Query String in JavaScript

We were provided function getQueryStringVariableByItemID for our project and are using function getData to use a web service for a game's details from a games table. We believe the getData part is working fine since we use a similar POST on another page. Is getQueryStringVariableByItemID not properly grabbing the query string?
We call getData with the body tag of html as onload="getData()". Many thanks in advance!
Code:
<script type="text/javascript">
function getQueryStringVariableByItemID(ItemID) {
//use this function by passing it the name of the variable in the query
//string your are looking for. For example, if I had the query string
//"...?id=1" then I could pass the name "id" to this procedure to retrieve
//the value of the id variable from the querystring, in this case "1".
ItemID = ItemID.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + ItemID + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.search);
if (results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
function getData() {
var ItemID = getQueryStringVariableByItemID(ItemID)
$.ajax({
type: "POST",
url: "./WebServiceTry.asmx/GetGameDetails",
data: "{'ItemID': '" + escape(ItemID) + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var data = response.d;
$('#output').empty();
$.each(data, function (index, item) {
var Title = item.Title
var Price = "$" + item.Price
var Year = "Year: " + item.Year
var Developer = "Developer: " + item.Developer
var Platform = "Platform: " + item.Platform
$('#output').append('<li>' + Title + '</li>');
$('#output').append('<li>' + Price + '</li>');
$('#output').append('<li>' + Year + '</li>');
$('#output').append('<li>' + Developer + '</li>');
$('#output').append('<li>' + Platform + '</li>');
$('#output').listview('refresh');
});
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
</script>
The ItemID you are passing in the getData(while calling inside the getData) should be undefined because the function doesnt have that variable.Pass a valid id and it will work fine

Categories