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>";
Related
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);
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
I have more than three TextBoxes. I want to send this data as in the code. The "indeks " value is always the last click. How do I keep the index?
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
if (txtvalue != "") {
if (i)
field += " and ";
field = field + "[" + obje[indeks]+ "]" $(this ).val() + "'";
i++;
}
});
});
},
As I wasn't sure if I got your question right, I prefered to comment on your topic - but now it seems that my answer helped you, so I decided to post it as an actual answer:
1st step: declare an array outside your success handler
2nd step: push the index and the value for the element into this array
3rd step: loop through all entries of the array and build your 'select' statement
Here is your edited example:
https://jsfiddle.net/Lk2373h2/1/
var clickedIndexes = [];
click:function(e) {
var item = e.itemElement.index();
indeks = item;
}
var field= "";
onl: function () {
$.ajax({
type: "GET",
cache:true,
url: MYURL,
success: function (msg, result, status, xhr) {
var obje = jQuery.parseJSON(msg)
var i = 0;
field = " ";
$('#wrapper *').filter(':input').each(function () {
$(this).attr('id', i);
var txtvalue=$(this).val();
if (i)
clickedIndexes.push({
index: indeks,
value: $(this ).val()
});
var selectString = "";
for (var u = 0; u < clickedIndexes.length; u++) {
selectString += "[" + obje[clickedIndexes[u].index].ALAN + "]" + "=" + "'" + clickedIndexes[u].value + "'";
}
field = selectString;
i++;
});
});
},
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 + "'";
I've been trying to get this right for quite some time, I'm trying to append the object from the first ajax call after the second ajax call. But the for loop seems to iterate the changing of the value to the last result before appending the information, having the last post appended every time.
var scribjson =
{
"user_id" : localStorage.viewing,
};
scribjs = JSON.stringify(scribjson);
var scrib = {json:scribjs};
$.ajax({
type: "POST",
url: "getScribbles.php",
data: scrib,
success: function(result)
{
var obj = jQuery.parseJSON(result);
for(var i = 0; i < obj.length; i+=1)
{
var userjson =
{
"user_id" : obj[i].user_id
};
userjs = JSON.stringify(userjson);
var user = {json:userjs};
localStorage.post = obj[i].post;
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
}
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
Since ajax calls It looks like the all success functions of the inner ajax call are being called after the loop has ended, so i will always be the last iterated value.
Try this:
(function(i)
{
$.ajax({
type: "POST",
url: "getRequestsInfo.php",
data: user,
success: function(result)
{
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
},
error: function()
{
alert('An Error has occured, please try again.');
}
});
})(i);
This will create a closure on i, which will give each ajax call its own copy of the current value.
Use an IIFE:
success: (function(i){return function(result) {
var obj2 = jQuery.parseJSON(result);
$('#listOfScribbles').append("<tr><td><img id = 'small_pic' src = '" + obj2[0].profileImage + "'/></td><tr><td>" + obj2[0].firstname + " " + obj2[0].lastname + "</td></tr> ");
$('#listOfScribbles').append("<tr><td>" + obj[i].post + "</td></tr>");
}})(i),
etc. Currently your loop generated ajax success handlers contain a direct reference to the counter itself, which (by the time they are called) has reached its final value.