Processing Ajax Data Using External Function Results in Error - javascript

I have an Ajax function below which returns data. I can log data to the console, but I want to process the "skilllist" in a separate function to generate HTML to add to the overall string. The function returns the HTML, but when it does so it generates an error just because the function is called.
My AJAX function looks like:
$("#search").click(function() {
$.ajax({
type: "POST",
dataType: "json",
url: "/search/projectsearchsimple/",
data: { csrfmiddlewaretoken:'{{ csrf_token }}',
search : $("#id_search").val() },
success: function(data) {
//update_messages(data.messages);
console.log(data);
$("#resultsarea").show();
$("#resultspanel").empty();
data = JSON.parse(data);
var resultshtml = "";
for(i=0;i<data.length;i++) {
var skilllist = [...data[i].skilllist];
var skillsbox = createSkillsBox(skilllist);
resultshtml = resultshtml + "<div class='row'><div class='col-2'>" +
"<a href='/project/projectpage/" + data[i].id + "'>" +
data[i].name + "</a>" + "</div>" + "<div class='col-2'>by " +
data[i].owner__username + "</div><div class='col-3'>Created on: " +
data[i].created + "</div></div>";
}
$("#resultspanel").append(resultshtml);
}
});
});
The external function looks as:
function createSkillsBox(skills) {
skillsboxhtml = "<div class='menu-outer'><div class='table'><ul id='skills{{ job.id }}' class='horizontal-list skillsboxuser'>";
for(i=0;i<skills.length;i++) {
skillsboxhtml += "<li><strong>" + skills[i] + "</strong></li>"
}
skillsboxhtml += "</ul></div></div>";
return skillsboxhtml;
}
The error received in the console sates "TypeError: data[i] is undefined[Learn More]". If I comment out the line "var skillsbox = createSkillsBox(skilllist);" it works doesn't error.
The data variable contains:
[{"skilllist": ["Programming", "Musician", "Writing"], "name": "Project KFC", "id": 3, "owner__username": "kyle", "created": "18/11/19 10:00", "description": "description"}]
I have tried moving the function to inside the Ajax method and I have tried with passing data[i] direct before i tried the shallow copy.
Can anyone help?

Related

Passing List String from C# to JavaScript

I am currently trying to check if a value of a string variable is "Apple". Now I need to pass a list of fruits to javascript from C#.
C# Code
List<String> fruits = new List<String>{"Apple","Mango","Orange"}
JavaScript Code
$(document).on('click','#dvAppContent input:checkbox[id*=chkfunction]', function () {
ToggleApplication(this);
});
function ToggleApplication(currentFunction) {
var fruitName = $(currentFunction).closest('ui').parent('label').text().trim();
If(fruitName == "Apple")
{
return true;
}
}
Use Ajax call in JavaScript.
Something like this:
<script>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "/api/StudentAPI/GetAllStudents",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//alert(JSON.stringify(data));
$("#DIV").html('');
var DIV = '';
$.each(data, function (i, item) {
var rows = "<tr>" +
"<td id='RegdNo'>" + item.regNo + "</td>" +
"<td id='Name'>" + item.name + "</td>" +
"<td id='Address'>" + item.address + "</td>" +
"<td id='PhoneNo'>" + item.phoneNo + "</td>" +
"<td id='AdmissionDate'>" + Date(item.admissionDate,
"dd-MM-yyyy") + "</td>" +
"</tr>";
$('#Table').append(rows);
}); //End of foreach Loop
console.log(data);
}, //End of AJAX Success function
failure: function (data) {
alert(data.responseText);
}, //End of AJAX failure function
error: function (data) {
alert(data.responseText);
} //End of AJAX error function
});
});
</script>
And in the backend in c#, something like this:
public class StudentAPIController : Controller
{
// GET: api/GetAllStudents
[HttpGet]
public IEnumerable<PersonalDetail> GetAllStudents()
{
List<PersonalDetail> students = new List<PersonalDetail>
{
new PersonalDetail{
RegNo = "2017-0001",
Name = "Nishan",
Address = "Kathmandu",
PhoneNo = "9849845061",
AdmissionDate = DateTime.Now
},
new PersonalDetail{
RegNo = "2017-0002",
Name = "Namrata Rai",
Address = "Bhaktapur",
PhoneNo = "9849845062",
AdmissionDate = DateTime.Now
},
};
return students;
}
}

Retrieveing Multiple lines of text using var query

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);

manipulate partial view's content with jquery

With the code below I am trying to update PartialView's HTML.
open_Modal_AssignAmendRoles = function (url) {
$.ajax({
url: url,//PartialView URL
cache: false,
type: "POST",
dataType: "html",
success: function (data, textStatus, XMLHttpRequest) {
var modalhtml = data;
var result = datafetchfunction("action URL", )
if (result.compleate == true) {
result.data.employeeroles.forEach(function (roletype) {
var tagbox = $(modalhtml).find("#tagbox" + roletype.clientroletypeid);
var span = $(modalhtml).find("#rolecontainer" + roletype.clientroletypeid);
var roletypeid = roletype.clientroletypeid
roletype.roles.forEach(function (role) {
var roleid = role.FK_ClientRoleID
var roledescription = role.ClientRole_Description;
var rolecode = role.ClientRole_Code
var markup = ""
markup += " <li class='taglist' id='" + roleid + "'>"
markup += " <button onclick='$(this).parent().remove()' class='tagclose'>"
markup += " <span class='glyphicon glyphicon-remove' aria-hidden='true'></span>"
markup += " </button>"
markup += " <a class='assignedrole' href='Javascript:void(0);' onclick='pop_click_fn(this)'"
markup += " role-id='" + roleid + "' role-type-id=" + roletypeid + ""
markup += " data-toggle='popover' data-trigger='hover' data-content='" + roledescription + "' data-placement='top' > " + rolecode + " </a>"
markup += " </li>";
$(span).append(markup)
})
})
openModal( modalhtml);
}
}
});
}
Step 1:
On button click the open_Modal_AssignAmendRoles() function is called. Then it goes to the success() function.
Step 2:
var result = datafetchfunction("action URL" )
this fetch data as JSON format
Step 3:
Then I start some loop, I already create some spans and find them with
var span = $(modalhtml).find("#rolecontainer" + roletype.clientroletypeid);
Step 4:
then I build a markup and assign this
$(span).append(markup)
and finally, call
openModal( modalhtml);
But modalhtml is not updated as expected, it means lis which I created with loop is not added.
Can someone tell me what is the problem and how to solve this?

Phonegap data storage mechanism using localStorage-adapter.js

How do I use this library localstorage-adapter.js to be able to store data from my server query processing??
I get a library when i see the app from Christophe Coenraets then I want to try it into my application.
My code to access data from server :
$(document).ready(function() {
$('#loading_panel').show();
get_news();
function get_news(){
var serviceURL = "http://www.mydomain.com/api/";
var SistemPakar;
$.ajax({
type : 'GET',
url : serviceURL + 'news.php',
async: true,
beforeSend: function(x) {
if(x && x.overrideMimeType) {
x.overrideMimeType("application/j-son;charset=UTF-8");
}
},
dataType : 'json',
success : function(data){
AllData = data.items;
if(AllData==''){
$('#loading_panel').hide();
$('#empty').show();
}else{
$('#loading_panel').hide();
$('#tampilData').show();
$.each(AllData, function(index, loaddata) {
var data = loaddata.id;
var image = loaddata.img;
var tanggal = loaddata.tanggal;
var strExplode = tanggal.split("-");
var strJoinExplode = strExplode[2]+ '-' +strExplode[1]+ '-' +strExplode[0];
$('#sispakList').append(
'<img src="logo/'+image+'.png"/>'+
'<h4>' + loaddata.judul + '</h4>' +
'<p>' + loaddata.isi +'</p>' +
'<p>' + strJoinExplode + '</p>');
});
$('#sispakList').listview('refresh');
}
},
error: function(jqXHR, exception) {
$('#loading_panel').hide();
$('#conn_failed').show();
}
});
}
});
How do when the data is first captured by the results of the application and use localstorage-adapter.js to save the data as a mechanism that made ​​Christophe Coenraets on the application??

Changing global variables in a ajax call

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.

Categories