Jquery loop with AJAX, looping through bootstrap modal - javascript

I am getting data from database, looping trough it and appending to the div in html page. It works until I am looping trough function witch contains bootstrap MODAL. I am passing parameters to function but every MODAL that was created display first row of my database table. My goal is to loop trough my function(MODAL) and pass different rows of my table, not only the first one.
VARIBLE WITH MY HTML
var table = {
createTable: function(result) {
$.each(result, function(i, column) {
$("#loopRows").append(
'<tr id="post"><td>' + column.ID + '</td>' +
'<td>' + column.Title + '</td>' +
'<td><button type="button" class="btn btn-primary" data-toggle="modal" data-target="#details">Details</button>+showBookmark.showItemTemplate(column.Title, column.Url, column.User)+</td>'
});
}
}
AJAX REQUEST
$(document).ready(function() {
$.ajax({
type: "GET",
url: 'http://localhost:62795/api/bookmarks',
success: function(result) {
table.createTable(result);
}
});
});
BOOTSTRAP MODAL WITH HTML FORM
var showBookmark = {
showItemTemplate: function(title, url, user) {
return '<div class="modal fade bs-example-modal-sm" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" id="details">' +
'<label for="recipient-name" class="control-label"> Title:' + title + '</label>' +
'<label for="message-text" class="control-label"> Url:' + url + '</label>' +
'<label for="message-text" class="control-label"> User:' + user + '</label>' +
'</div>'
}
}

Related

Creating a dynamically generated accordion with bootstrap 4 with onclick AJAX calls

Ok, so there are a few parts to what I'm trying to do. I've gotten my JSON data returned to me, and now I need to make a Bootstrap accordion table with each main row containing four 'table cells' or an equivalent thereof, but when I click on that row, I want to display the rest of the information in the accordion directly underneath the row. However, I'm not quite sure how to dynamically generate a multi-row accordion table with an unknown number of rows, since this is more about creating a table with an actual <tbody> tag unlike my last terrible attempt at this. Any help here? I saw this question but it didn't seem applicable to my needs at all. Here's something that's ALMOST there, but it needs to be able to use correctly aligned table rows and cells in the places where the text is on the main rows.
https://codepen.io/Sp00ky/pen/akVkyV
I need to be able to have nicely aligned rows and columns...this should look like a table with a dropdown panel for every row when finished.
$(jQuery.parseJSON(JSON.stringify(response))).each(function() {
var foNum = this['Factory Order#'];
var pO = this['PO#'];
var status = this['Status'];
var shipDate = this['Ship Date'];
var dat = '{\"username\":' + "\"" + username + "\"}";
$.ajax({
url: BASE_URL + "portal/getdata/orders/" + foNum,
method: 'POST',
cors: true,
data: dat,
dataType: "json",
contentType: "application/json",
success: function (response) {
$('.orders').append(
'<div class="panel panel-default">'+
'<div class="panel-heading" role="tab" id="heading_'+index+'">'+
'<tr>'+
'<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse_'+index+'" aria-expanded="true" aria-controls="collapse_'+index+'">'+
'<td>' + foNum + '</td><td>' + pO + '</td><td>' + status + '</td><td>' + shipDate + '</td>' +
'</a>'+
'</tr>'+
'</div>'+
'<div id="collapse_'+index+'" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading_'+index+'">'+
'<div class="panel-body">'+
'blahblah'+ //PUT DETAILS HERE
'</div>'+
'</div>'+
'</div>'
);
index+=1;
},
error: function (response) {
alert("Error: Could not get details.");
}
});
});

One page app doesn't refresh with Ajax and SQL requests (online only)

I'm trying to build a trip organiser. It's a one page app. There are a list of trips, with their activities on one side, and the Google Map on the other side.
Screenshot here : http://hpics.li/fc1b59c
I have two main files : one called app.js, where I trigger events with forms and click on buttons. Then I get or send data to travelAPI.php, where I send and retrieve data from the database.
When I add a trip or an activity; I empty the whole list, then I retrieve all the trips and activities again from the DB.
In my local environment, everything works fine. But when I tried to put it online, it's a mess. SQL requests work fine, but my trips list doesn't update, and I don't understand why. Actually, the list seems to refresh, but with the same results, and without the trip I just added. (But the trip is pushed into the database)
To display the new trip, I need to clear Google Chrome cache.
I tried to analyse this issue with Postman extension, but it seems to come from the client side.
Ajax request:
function insertTrip() {
$.ajax({
url: 'travelAPI.php?call=insertTrip',
type: 'POST',
data: {
cityName: $("input[name=cityName]").val(),
date: $("input[name=date]").val(),
dateUpdatePlace: $.now()
},
success: function() {
initTripList();
}
});
};
initTripList method:
function initTripList() {
$("#tripList").html('');
var listPlace = new Array();
$.ajax({
type: "GET",
url: "travelAPI.php?call=getTrips",
dataType: "json",
success: function(data) {
for (var i = 0; i < data.length; i++) {
if (i === 0) {
$("#tripList").append('<div class="trip" data-id="' + data[i].idPlace + '"><div class="headingName"><p class="tripName">' + data[i].namePlace + '</p><img class="editNameAction" src="imgs/edit.png" width="30px" alt="edit"></div><div class="editName" style="display:none"><input type="text" name="tripName" value="Text to edit"><img class="confirmEditName" src="imgs/validate.png" width="30px" alt="valider"></div><p class="tripDate">' + data[i].datePlace + '</p><div class="editDate" style="display:none"><input type="text" name="tripDate" value="Text to edit"><img class="confirmEditDate" src="imgs/validate.png" width="30px" alt="valider"></div><ul><li data-id="' + data[i].idActivity + '">' + data[i].nameActivity + '<img class="deleteActivity" src="imgs/delete.png" style="width: 15px;"></li></ul></div>');
} else {
if ($.inArray(data[i].idPlace, listPlace) != -1) {
$('.trip[data-id="' + data[i].idPlace + '"] ul').append('<li data-id="' + data[i].idActivity + '">' + data[i].nameActivity + '<img class="deleteActivity" src="imgs/delete.png" style="width: 15px;"></li>');
} else {
$("#tripList").append('<div class="trip" data-id="' + data[i].idPlace + '"><div class="headingName"><p class="tripName">' + data[i].namePlace + '</p><img class="editNameAction" src="imgs/edit.png" width="30px" alt="edit"></div><div class="editName" style="display:none"><input type="text" name="tripName" value="Text to edit"><img class="confirmEditName" src="imgs/validate.png" width="30px" alt="valider"></div><p class="tripDate">' + data[i].datePlace + '</p><div class="editDate" style="display:none"><input type="text" name="tripDate" value="Text to edit"><img class="confirmEditDate" src="imgs/validate.png" width="30px" alt="valider"></div><ul><li data-id="' + data[i].idActivity + '">' + data[i].nameActivity + '<img class="deleteActivity" src="imgs/delete.png" style="width: 15px;"></li></ul></div>');
}
}
listPlace.push(data[i].idPlace);
}
}
});
setTimeout(function() {
initTripListSec();
}, 100);
};

Ajax MySQL POST responses with Object without data

I am using that code to send a POST request to add data to a mysql table.
var todoItem = $(this).serialize();
$.ajax({
type: "POST",
url: "/test",
data: todoItem,
dataType: "json",
success: function(data, textStatus, jqXHR) {
console.log(data);
if(data.success){
$('#todo-list').append(
'<li class="list-group-item">' +
'<span class="lead">' +
data.todo +
'</span>' +
'<div class="pull-right">' +
'Edit' +
'<form style="display: inline" method="POST" action="/test/${data.id}">' +
'<button type="submit" class="btn btn-sm btn-danger">Delete</button>' +
'</form>' +
'</div>' +
'<div class="clearfix"></div>' +
'</li>'
);
} else {
$("#todo-list").append(
'<li class="list-group-item">' +
'<span class="lead">' +
'Fail' +
'</span>' +
'<div class="clearfix"></div>' +
'</li>'
);
}
}
Then i want to use data from the response to append to my list.
But if(data.success) isnt passing. why is that?
Also my data in console.log looks like object Object and doesnt contain the inserted row data.
Do i need to send a get request now to retrieve the last data row?

URL Name not resolved in Jquery

I am trying to dynamically build up HTML using JQuery in ASP.NET MVC5. I have so far had success, but the URL cannot be resolved in the JQuery Code.
My code looks something like this:
$.ajax({
type: 'POST',
url: '#Url.Action("QuerySearch")',
dataType: 'json',
data: {
queryName: $("#queryText").val()
},
success: function (data) {
// var items = '';
$.each(data, function (i, item) {
var resource_Url = item.ResourceURL;
// var resource_url = item.ResourceURL;
var append_data = $('<div class="row">'
+ '<h3>' + item.ResourceTitle + '</h3>'
+ '</div>'
+ '<div class="row">'
+ '<span class="label label-primary" style="margin:3px;font-size:small;">'
+ item.ResourceEducation
+ '</span>'
+ '<span class="label label-warning" style="margin:3px;font-size:small;">'
+ item.ResourceGrades
+ '</span>'
+ '<span class="label label-info" style="margin:3px;font-size:small;">'
+ item.ResourceSubject
+ '</span>'
+ '<a href="#Url.Content("' + item.ResourceURL + '")">'
+ '<img src="#Url.Content("~/Content/Resources/download_icon.png")" alt="Download Resource" style="height:24px;width:24px;"/>'
+ '</a>'
Although this code is able to retrieve the image for the download_icon defined in my project, it is not able to display / embed the URL fetched from the server by my function which I am trying to display in the <a href> tag.
Any help is greatly appreciated.
You will need to pass the complete url value from the server as a property of the data received. Or have it stored locally
ASP code doesn't run in the browser, only on server
The trick was simple, the href tag had to be changed to:
'<a href="' + item.ResourceURL + '">'
It worked like a charm

How to open Bootstrap modal pop-up one after other?

In mvc application, I have a HTML table on which data is created on load using Ajax. This HTML table consists of N number of records, I have applied Pagination to the table using Jquery so that only 10 records are added to a single page on the table.
Now the first column of the html table is checkbox which means that if I select the checkbox in the header all the records in the particular page of the table would be selected. I have few buttons on the top which does certain functionalities among them is a delete button which deletes all the records which are selected from the table. Now the problem is that for each records a Modal Popup should show up asking "Do you want to delete the records of {somename}?". I have a confirm button and a cancel button.
On click of "Confirm" the particular record details would be deleted and then again a new pop-up should display asking confirmation to delete the records. Like wise if I click Cancel then the current popup should be closed and new one should open asking confirmation to delete the records.
Following is the code that I did
//Create a modal popup
function BootstrapModalPopUp(modalId, ButtonConfirmID, ButtonCancelID, ButtonText, modalTitle, modalBody) {
var popUpContent = '<div class="modal fade" id="myModal' + modalId + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">'
+ '<div class="modal-dialog" role="document">'
+ '<div class="modal-content">'
+ '<div class="modal-header">'
+ '<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>'
+ '<h4 class="modal-title" id="myModalLabel">' + modalTitle + '</h4>'
+ '</div>'
+ '<div class="modal-body">'
+ '<h4 class="modal-title" id="myModalLabel">' + modalBody + '</h4>'
+ '</div>'
+ '<div class="modal-footer">';
if (ButtonConfirmID != '') {
popUpContent += '<button id="btn' + ButtonConfirmID + '" type="button" class="btn btn-primary" data-dismiss="modal">Confirm</button>'
+ '<button id="btn' + ButtonCancelID + '" type="button" onclick="modalpopupcancel()" class="btn btn-primary" data-dismiss="modal">' + ButtonText + '</button>'
}
else {
popUpContent += '<button id="btn' + ButtonCancelID + '" type="button" onclick="modalpopupcancel()" class="btn btn-primary" data-dismiss="modal">' + ButtonText + '</button>'
}
+ '</div></div></div></div>';
$('#myModalPopups').append(popUpContent);
}
//On click of the button
function EmailConfirmationSubmit(buttonName) {
$('#' + buttonName).click(function () {
//Getting the number of CheckBox
var $chkboxes = $('#tblMemberList').find("tr input[type='checkbox']:checked");
//Getting the ID (checked value) from the CheckBox and storing in Array
var checkBoxVals = $chkboxes.map(function () { return $(this).attr('id'); }).toArray();
//remove the first element of the checkbox. This is the header of the checkbox which we dont need to show the pop up for
if ($.inArray('memberListHeaderCheckBox', checkBoxVals) > -1) {
checkBoxVals.splice($.inArray("memberListHeaderCheckBox", checkBoxVals), 1);
}
var ModalIdBeforeCreation = 'DeleteConfirmation';
var ModalConfirmIDBeforeCreation = '_DeleteConfirm';
var ModalCancelIDBeforeCreation = '_DeleteCancel';
//Checking the Array whether it is not empty
if (!isArrayEmpty(checkBoxVals)) {
//Loop through each selected checkbox
checkBoxVals.forEach(function (CheckBox) {
//Get id and name of the check box. The name is the pension ID
var CheckBoxID = $("#" + CheckBox).val();
var CheckBoxName = $("#" + CheckBox).attr('name').toString();
var ModalId = ModalIdBeforeCreation + CheckBoxID;
var ModalConfirmID = ModalConfirmIDBeforeCreation + CheckBoxID;
var ModalCancelID = ModalCancelIDBeforeCreation + CheckBoxID;
var ModalMessage = 'Do you want to delete the records for the member ' + CheckBoxName + ' ?'
$("#"+ModalId).remove();
//Create dynamic pop up based on each Pension ID which is selected on Html Table
BootstrapModalPopUp(ModalId, ModalConfirmID, ModalCancelID, 'Cancel', 'Delete Confirmation', ModalMessage);
});
var checkBoxID = $('#' + checkBoxVals[0]).attr('id');
CreateAlertsForActions(ModalIdBeforeCreation,ModalConfirmIDBeforeCreation,ModalCancelIDBeforeCreation,checkBoxVals,checkBoxID,PageActions.OnDelete,Controllers.CommutedPensions,"OnDelete");
}
else {
//do something
}
});
}
//Create alerts
function CreateAlertsForActions(ModalIdBeforeCreation,ModalConfirmIDBeforeCreation,ModalCancelIDBeforeCreation,CheckBoxArray,checkBoxID,PageAction,ControllerName,ActionName)
{
var checkBoxValue = $('#' + checkBoxID).val();
var index = CheckBoxArray.indexOf(checkBoxID);
//Again get the new ID
checkBoxID = $('#' + CheckBoxArray[index+1]).attr('id');
if(checkBoxValue != undefined)
{
var ModalId = ModalIdBeforeCreation + checkBoxValue;
var ModalConfirmID =ModalConfirmIDBeforeCreation + checkBoxValue;
var ModalCancelID = ModalCancelIDBeforeCreation+ checkBoxValue;
$('#myModal'+ModalId).modal('show');
//On Confirm Click
$('#myModal' + ModalId).on('click', '#btn' + ModalConfirmID, function () {
AjaxRequestToControllerAction(ControllerName,ActionName,PageAction,checkBoxValue);
CreateAlertsForActions(ModalIdBeforeCreation,ModalConfirmIDBeforeCreation,ModalCancelIDBeforeCreation,CheckBoxArray,checkBoxID,PageAction,ControllerName,ActionName);
});
//Popup Cancel button click event
$('#myModal' + ModalId).on('click', '#btn'+ModalCancelID, function () {
CreateAlertsForActions(ModalIdBeforeCreation,ModalConfirmIDBeforeCreation,ModalCancelIDBeforeCreation,CheckBoxArray,checkBoxID,PageAction,ControllerName,ActionName);
});
//Popup close button click event
$('#myModal' + ModalId).on('click', '#btn'+ModalCancelID, function () {
CreateAlertsForActions(ModalIdBeforeCreation,ModalConfirmIDBeforeCreation,ModalCancelIDBeforeCreation,CheckBoxArray,checkBoxID,PageAction,ControllerName,ActionName);
});
//When the mouse is clicked out side of the popup
$('#myModal' + ModalId).on('hidden.bs.modal', function () {
CreateAlertsForActions(ModalIdBeforeCreation,ModalConfirmIDBeforeCreation,ModalCancelIDBeforeCreation,CheckBoxArray,checkBoxID,PageAction,ControllerName,ActionName);
});
}
}
function AjaxRequestToControllerAction(Controller, ActionMethod, Action, CheckBoxValue) {
$.ajax({
//The Url action is for the Method FilterTable and the Controller CurrentYearApplications
//url: '#Url.Action("' + ActionMethod + '", "' + Controller + '")',
url: '/' + Controller + '/' + ActionMethod + '/',
//The text from the drop down and the corresponding flag are passed. Flag represents the Index of the value in the dropdown
data: { ID: CheckBoxValue, PageAction: Action },
contentType: "application/json; charset=utf-8",
//Json data
datatype: 'json',
//Specify if the method is GET or POST
type: 'GET',
//Error function gets called if there is an error in the ajax request
error: function (jq, status, message) {
//Show error
},
//Gets called on success of the Ajax Call
success: function (data) {
//Do things after success
}
});
}
Everything works fine for me, if there are just 4,5 records selected, but when I select around 10 records and choose to delete them, the first 4,5 work fine, then the popup seems to crash.
Any help in this regard or suggestions for alternative methods to follow would be really appreciated.
Thanks in Advance.

Categories

Resources