How to append a div into a div with variables Javascript - 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);
}

Related

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>

Pulling a Usable Link out of a JSON Object

I need to figure out how to have a link that I pull from a JSON object an ACTUAL link that the user can click and follow to the site instead of just text. I feel like it's gotta be a quick fix, but I can't seem to figure it out! Thanks for the help!!
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function(response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='deals[i].deal.untracked_url'>" + deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
})
};
Assuming your fetched data is correctly used, here's why your link doesn't work : the href is actually deals[i].deal.untracked_url instead of its content.
try this instead :
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $('' + deals[i].deal.untracked_url + "");
couponInfo.append(newUntrackedURL)
}
})
};
Without the generated JSON, I can't help you further if this solution doesn't helps.
Look like maybe you had a typo:
'deals[i].deal.untracked_url' should be 'deals["+ i +"].deal.untracked_url'
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='deals["+ i +"].deal.untracked_url'>" +
deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
});
Scratch that - you want it to pull the value not write out "deals[i].deal.untracked_url." To do that you do the below.
function sqoot(URL) {
$.ajax({
url: URL,
method: "GET"
}).done(function (response) {
var deals = response.deals
var untrackedURL = $("#untrackedURL");
var couponInfo = $("#info");
for (i = 0; i < deals.length; i++) {
var newUntrackedURL = $("<a href='"+deals[i].deal.untracked_url+"'>" +
deals[i].deal.untracked_url + "</a>");
couponInfo.append(newUntrackedURL)
}
});

Getting undefined/no result when printing out api callback

I am trying to run my script that is going to search for a movie title from a movie database. I get results in the console and no errors. But in my renderMovies function it's supposed to store the API movie title, plot etc in my variables, but when I print it out in a list it either gives me nothing (blank) or undefined. I am kind of new to jQuery, AJAX and APIs so I'm following a guide, so the code is not entirely written by me.
OBS: I get undefined when using this $("<td>" + plot + "</td>"), but blank when using $("<td>").append(title). You can find that code in the middle of the renderMovies function.
For example: I search for the movie 'Avatar' and I get two results. However the two results gets "stored" as undefined in the plot description and blank from the title.
$(document).ready(function(){
$(init);
function init() {
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody");
function searchMovie(){
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title=" + title + "&token=b81c6057-20cf-4849-abc4-decbf9b65286&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&keyword=0&quotes=0&fullSize=0&companyCredits=0&filmingLocations=0",
dataType: "jsonp",
success: renderMovies
});
};
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title); // blank
var plotTd = $("<td>" + plot + "</td>"); // undefined on my website
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I've reordered your functions and calls because some of the variables were undefined. (Google Chrome -> F12 (opens developers console))
This returns a response on a button click.
$(document).ready(function () {
function searchMovie() {
var movieTitle = $("#movieTitle");
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title=" + title + "&token=b81c6057-20cf-4849-abc4-decbf9b65286&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&keyword=0&quotes=0&fullSize=0&companyCredits=0&filmingLocations=0",
dataType: "jsonp",
success: renderMovies
});
}
function renderMovies(movies) {
console.log(movies);
var movieInfo = movies.data.movies;
var table = $("#results");
var tbody = $("#results tbody");
tbody.empty();
for (var m in movieInfo) // Tar information från apin och stoppar in i egna variabler.
{
var movie = movieInfo[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title); // blank
var plotTd = $("<td>" + plot + "</td>"); // undefined on my website
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
$("#searchMovie").click(searchMovie);
});

It does not work "onclick" with attr () from JQuery

I'm trying to add an "onclick" event with their respective function from js JQuery to an interactive table td I'm doing in another .php file, the problem is not executed in the place where I want to do it but if the same instruction is executed correctly within an AJAX request a few lines below, will show you the code:
This instruction is giving me the problem:
$(td).attr("onclick","agregar_pensum_etapa2 (this,'"+subject+"','"+level+"','"+stage+"');");
And this, the function I want to run with the "onclick"
function agregar_pensum_etapa2(td,subject,level,stage){
$(document).ready(function(){
// Capture variables.
var id_periodo = $("#id_periodo").val();
var id_asignatura = subject;
var id_nivel = level;
var id_etapa = stage;
var id_mencion = null;
if (level> 3) {
id_mencion = 0;
}
// Modifiable column.
var tr = $(td).parent();
var index_td = $(td).index();
// First field
var valor_anterior = $(td).text();
$(td).html("<img src =" images / save_64.png 'width = '16' height = '16 '> & nbsp; & nbsp; & nbsp;' + '<input value = "' + valor_anterior + '" type = "text" style = "width: 40px; border: 1px solid #aaa;" onkeypress = "return soloNumeros (event);" maxlength = "2"> ');
$(td).removeAttr("onclick");
$(td).find("input").focus();
// Second field
var valor_anterior_cs = $(tr).find("td:eq("+(index_td+1)+")").text();
var checked_cs = "";
if (valor_anterior_cs === "X"){checked_cs = "checked"}
$ (tr) .find ("td: eq (" + (index_td + 1) + ")") html ("<input type = 'checkbox'" + checked_cs + ">").
// Third field
var valor_anterior_hum = $(tr).find("td:eq("+(index_td+2)+")").text();
var checked_hum = "";
if(valor_anterior_hum === "X") {checked_hum = "checked"}
$(tr).find("td:eq("+(index_td+2)+")").html("<input type = 'checkbox'"+checked_hum+">");
/ ************************************************* *********** /
$(td).find("img").click(function(){
var hora_asignatura = $(td).find("input").val();
var mencion_cs = "NO";
if($(tr).find("td:eq("+(index_td+1)+")").find("input").is ("checked")){mencion_cs = "YES";}
var mencion_hum = "NO";
if($(tr).find("td:eq("+(index_td+2)+")").find("input").is("checked")){mencion_hum = "YES";}
if(hora_asignatura === ""){
if(valor_anterior != ''){
$(td).html(valor_anterior);
$(tr).find("td:eq("+index_td+1)+")").text(valor_anterior_cs);
$(tr).find("td:eq("+(index_td+2)+")").text(valor_anterior_hum);
}else{
$(td).html("");
$(tr).find("td:eq("+(index_td+1)+")").text("");
$(tr).find("td:eq("+(index_td+2)+")").text("");
}
\\// --> HERE IS NOT WORKING <-- \\//
$(td).attr("onclick","agregar_pensum_etapa2(this,'"+subject +"','"+level+"','"+stage+"');");
}else if(hora_asignatura == "0"){
if(valor_anterior! = ''){
$(td).html(valor_anterior);
$(tr).find("td:eq("+(index_td+1)+")").text (valor_anterior_cs);
$(tr).find("td:eq("+(index_td+2)+")").text (valor_anterior_hum);
}else{
$(td).html("<img src =" images / diagonal.png 'height = '16' style = 'width: 15px ">");
$(tr).find("td:eq("+(index_td+1)+")").text("");
$(tr).find("td:eq("+(index_td+2)+")").text("");
}
\\// --> HERE IS NOT WORKING <-- \\//
$(td).attr("onclick","agregar_pensum_etapa2(this,'"+subject+"','"+level+ "','"+stage+"');");
}else{
$.ajax({
async: true,
cache: false,
dataType: "html"
type: 'POST'
url: "../Controlador/CtrlPensum.php"
data: {
id_periodo: id_periodo,
id_asignatura: id_asignatura,
id_nivel: id_nivel,
id_etapa: id_etapa,
hora_asignatura: hora_asignatura,
mencion_cs: mencion_cs,
mencion_hum: mencion_hum,
id_mencion: id_mencion,
record: "register"
},
success: function (response) {
//alert (response);
if($.trim(answer) === "1") {
$(td).html(hora_asignatura);
var marcar_cs_x = "";
if(mencion_cs === "SI"){marcar_cs_x = "X";}
var marcar_hum_x = "";
if(mencion_hum === "SI"){marcar_hum_x = "X";}
$(tr).find("td:eq("+(index_td+1)+")").html (marcar_cs_x).
$(tr).find("td:eq("+(index_td+2)+")").html (marcar_hum_x).
\\// --> HERE IT WORKS <-- \\//
$(td).attr("onclick", "agregar_pensum_etapa2 (this,'"+subject+"','"+level+"','"+stage+"');");
cargarTablaResumen ();
} Else {
alert ("Error SQL statement is not executed." + response);
}
//tr.fadeOut(500).fadeIn(500);
},
beforeSend: function () {}
Error: function (objXMLHttpRequest) {}
});
}
});
});
}
I try this:
$(td).click(function(){
$(td).attr("onclick","agregar_pensum_etapa2 (this,'"+subject+"','"+level+ "','"+stage+"');");
});
And in the html it prints correctly but does not work, like he was not the "onclick" there. And the function if it works, I put the onclick to that function when I load the page and if it works, but when I click the td and give back to click to restore does not restore the onclick.
Instead of setting the onclick attribute, why not do use .click() again with closures? So your code would be something like...
$(td).click(function(){
var td = this;
$(td).click(function () {
agregar_pensum_etapa2(td,subject,level,stage);
});
});
Do you write
$(Document)
Instead of $(document) with small letter "d".

My javascript doesn't run without alert

I am having a problem with a block of my code, this section creates boxes of chocolates based on what a user chooses in a previous step and what data is pulled from the database in the api script.
the problem is that it doesn't work without the alert('hi') in it. if i take that out it will just create an empty box without dropping the flavors in it, the flavor the flavors are inserted with the createFlavorArray function.
var product = new Array();
var price = new Array();
var size = new Array();
$(function () {
$.ajax({
type: 'POST',
url: 'phpscripts/api.php',
data: "",
dataType: 'json',
success: function(rows)
{
count = 0;
for (var i in rows)
{
var row = rows[i];
product[count] = row[0];
price[count] = row[1];
size[count] = row[2];
count++;
}
}
});
});
//b = box
//o = option that is inside the box
//nextBoxId is the box id
//nextFlavorId is the option or flavor id
var nextBoxId = 1;
var nextFlavorId = 1;
var orderCap = 0;
var subTotal = 0;
var numOfChocolates = 0;
var numOfBoxes = 0;
$(document).ready(function(){
while (halfPoundBoxes > 0) {
$("#boxes").append('<div id="b'+nextBoxId+'"></div>');
$('#b'+nextBoxId).addClass('div-table-selection');
$('#b'+nextBoxId).append($('#minusBox').clone().attr('id', "m"+nextBoxId));
$('#b'+nextBoxId).append('<div style="display:table-row"></div>');
//call the function to loop through and create the number of flavor options needed
var x = 0;
alert('hi');
while(x < product.length){
if ('1/2lb Box' == product[x]) {
createFlavorArray(size[x], nextBoxId);
subTotal += price[x] * 1;
$('#b'+nextBoxId).attr('title', product[x]);
}
x++;
}
//clone the delete box button and make it visible
$('#m'+nextBoxId).show(500);
$('#b'+nextBoxId).append("<br />");
if (orderCap == 0) {
$('#boxes').append('<div id="msg"><p>If you wish to add another box to your order select the size and click +1 Box.</p></div>');
}
$("#m"+nextBoxId).click(function() {
$(this).parent().remove();
orderCap--;
//if they're ordering zero boxes hide the order button
//remove total price
//remove the message
if (orderCap == 0)
{
document.getElementById('orderBtn').style.display = "none";
$("#msg").remove();
$("#totalPrice").empty();
}
if (orderCap < 10)
{
$("#cap").remove();
$("#addBox").show(500);
}
var y = 0;
while (y < product.length) {
if ('1/2lb Box' == product[y]) {
subTotal -= price[y] * 1;
numOfChocolates -= size[y] * 1;
}
y++;
}
$('#totalPrice').html("<p>Sub Total: " + subTotal + "</p>")
//subtract the new
$('#finalpaypal').val(subTotal);
});
nextBoxId++;
orderCap++;
numOfBoxes++;
$('#totalPrice').html("<p>Sub Total: " + subTotal + "</p>")
halfPoundBoxes--;
}
The reason your code is working only when using an alert(), is that the alert() action is giving your jQuery AJAX request a few seconds to return a value to your success() call back function.
You should move any code which is affected by your callout function, into the callout function also, so that this code runs in the correct order.
Alternatively you could not run your AJAX request asynchronosly by adding async:false, but as #Rocket has commented, this isn't recommended.
$.ajax({
async: false,
You need to put the code in a function and run it after the ajax success is finished
...
$(function () {
$.ajax({
type: 'POST',
url: 'phpscripts/api.php',
data: "",
dataType: 'json',
success: function(rows)
{
count = 0;
for (var i in rows)
{
var row = rows[i];
product[count] = row[0];
price[count] = row[1];
size[count] = row[2];
count++;
}
do_after_ajax();
}
});
});
function do_after_ajax(){
while (halfPoundBoxes > 0) {
$("#boxes").append('<div id="b'+nextBoxId+'"></div>');
$('#b'+nextBoxId).addClass('div-table-selection');
....
}
It looks like you're trying to operate on markup returned by your ajax. That code needs to be moved into the success callback of the ajax request. The reason the alert call makes it work is simply that it delays everything else long enough for the page to finish loading.

Categories