bootstrap popover update content - javascript

how do you update the content of bootstrap popover after ajax success, I specifically need to change the value of the input field that I have but once I close the popover and click on it, the original value of the input field shows up? can someone help me out?
<button class="btn btn-primary edit" data-content='<input type="text" id="name" value="some value">
<button class="btn btn-primary save">Save</button>'>Edit</button>
JavaScript:
$('.edit').popover({
placement: 'left',
html: true,
});
$('body').on("click", ".save", function() {
var name = $('#name').val();
$.ajax({
type: "POST",
url: "test.php",
data: {
name: name
},
cache: false,
success: function(response) {
if (response.indexOf("success") != -1) {
$('#name').val(name);
$('.edit').popover('hide').next('.popover').remove();
}
}
});
});
after the data is saved the popover is closed and when I click edit again the old value shows in the input box.

Please find enclosed a working demo of a popover that will be updated with the response from an ajax request.
I've removed your request parameters just for the demo to be able to do the request with mocky.io.
The trick was to use .attr('value', text) instead of .val(text). I'm not exactly sure what's going on here. Maybe someone can explain why that's different.
But with attr it changes the popover and it works.
Another thing that is required is to recreate the popover. I also wanted to destroy the first popover but that doesn't work. So I created the same popover again.
You can also find the same code here at jsFiddle.
There is a bug in the code here at SO. If you get the data from the server and then close the popover, the data will be reset to initial value.
Don't know what's wrong, because it works at jsFiddle with-out that bug.
Update 04.12.2014:
I've improved the code a bit. Now there is a close button in the popover and the data is stored so the data from server is still available when the popover is re-opened.
The bug mentioned above was probably not a SO issue, it was because the data from server was not properly stored. That is also fixed now.
I've also removed some not needed script tags in the demo because tooltip and popover are already included in bootstrap 3.
Update 05.12.2014:
I have another improvement to the code.
The line $(this).parent().find('.close').click(...) is not working like I wanted it. I wanted to add the handler only to the close button of the current popover. But it adds it to all elements with class .close.
Because $(this).parent() is the body element. I think it is better to do it like this:
var current_popover = '#' + $(e.target).attr('aria-describedby');
var $cur_pop = $(current_popover);
$cur_pop.find('.close').click({});
With aria-describedby you'll get the id of the current popover and then you can find the close button of that popover.
$(function () {
var editData = 'new value';
var doPopover = function (item, text) {
$('#name').attr('value',text); // use set attr and not val()
//$('#name').val(text); //<<<< not working here doesn't set DOM properly
var $pop = $(item);
$pop.popover({
placement: 'right',
title: 'edit <a class="close" href="#">×</a>',
trigger: 'click',
html: true,
content: function () {
return $('#popup-content').html();
}
}).on('shown.bs.popover', function(e) {
// console.log('triggered');
// 'aria-describedby' is the id of the current popover
var current_popover = '#' + $(e.target).attr('aria-describedby');
var $cur_pop = $(current_popover);
$cur_pop.find('.close').click(function(){
//console.log('close triggered');
$pop.popover('hide');
});
});
return $pop;
};
// enable popover
doPopover('.edit', editData);
// edit button click handler to show popover
$('.edit').click(function() {
doPopover('.edit', editData);
});
$('body').on("click", ".save", function (e) {
e.preventDefault();
var name = $('#name').val();
//console.log($popover);
$.ajax({
type: "GET", //"POST",
url: "http://www.mocky.io/v2/547f86501713955b0a8ed4da", //"test.php",
data: {
//name: name
},
cache: false,
success: function (response) {
editData = response.data;
doPopover('.edit', editData);
console.log('response: ', editData);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<button class="btn btn-primary edit" data-html="true" data-toggle="popover" class="edit" data-title="Edit">Edit</button>
<div id="popup-content" class="hide">
<input type="text" id="name" value="some value" />
<button class="btn btn-primary save">Save</button>
</div>

Related

Laravel js DataTable: how do I assign a value from js back to the .blade?

I have these rows:
each row is being outputted by the DataTable plugin within app.js
my target is this particular value, ${row.category_id}
let TABLE = $('#categoryList').DataTable({
{ data: 'id', name: 'id', width: '10%', orderable: false, searchable: false,
render: (data, type, row) =>{
let html = "";
if(row.category_name && row.category_name.toUpperCase() !== "GENERAL"){
html += `<ul class="list-inline no-margin">`;
html += `<li class="list-inline-item">
<button type="button" value="${row.category_id}" class="edit_category btn btn-outline-secondary"><i class="fas fa-edit" aria-hidden="true"></i> Edit</button>
</li>`;
html += `</ul>`;
}
return html;
}
}
});
now I have this blade file, index.blade.php that is connected to app.js using:
<script src="{{asset('/modules/bbr-category-configuration/js/app.js')}}"></script>
What I need to resolve is the constant below:
#section('scripts')
<script type="text/javascript">
const SELECTED_CATEGORY_ID = 1;
</script>
#endsection
by default it is set as 1, but this needs to changed each time the 'Edit' button is clicked (refer to the screenshot). Once the button is clicked, I need to get ${row.category_id} and assign it to the const SELECTED_CATEGORY_ID. What is the correct way of doing this?
TLDR: how do I pass a value from .js back to .blade.php?
What I tried:
my first obstacle is to get the value from ${row.category_id} on click, but here is where I got stuck
$(document).on('click', '.edit_category', function () {
console.log(${row.category_id});
});
I cannot console.log (to test if I got the correct variable) outside the DataTable because it cannot be read, or do it inside toe columns because it is not the right syntax.
please feel free to ask for any clarifications.
First of all, if your variable's data will change during the process then it is not const it should be declared as let. You should know the difference between var let and const.
And you can use data-* attributes in the edit button so you can easily fetch the category_id when that button is clicked eg:
<button type="button" data-category=`${row.category_id}`class="edit_category">Edit</button>
Then on click event, you can get that data using
$('.edit_category').click(function (e) {
SELECTED_CATEGORY_ID = $(this).data('category');
});
You can fetch the value attribute of the button too using jquery. But generally, I don't use that. Or I haven't seen much usage of that too. You can try it like this too
$('.edit_category').click(function (e) {
SELECTED_CATEGORY_ID = $(this).value;
});

How to receive AJAX (json) response in a divs with same class name individually?

I've been getting crazier day after day with this, I can't find an answer, I've spent like 100h+ with this... I hope someone could help me out!
UPDATE:
So to make myself more clear on this issue and be able to get help from others, I basically have 3 containers named "main-container" they all have 3 containers as childs all with the same class name, and when I submit the button, I trigger an ajax function to load the JSON strings comming from php into the child divs, the problem is that I get the 3 "main_containers" to load the ajax at the same time, I only want to load the ajax if I press the button of each "main_container" individually.
I've been using jquery and vanilla JS as well but seems I just can't get it done!
This is how I currently trigger the button with jquery:
$('.trigger_button_inside_divs').click(my_ajax_function);
And this is how my ajax looks like:
function my_ajax_function(){
$.ajax({
dataType: "JSON",
type: 'POST',
url: test.php,
success: function(data) {
$('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
$('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
$('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);
}
});
}
HTML looks like this:
<div class="main_container">
<div class="my_div">
//div_to_render_JSON_1
</div>
<div class="my_div">
//div_to_render_JSON_2
</div>
<div class="my_div">
//div_to_render_JSON_3
</div>
<button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
<div class="main_container">
<div class="my_div">
//div_to_render_JSON_1
</div>
<div class="my_div">
//div_to_render_JSON_2
</div>
<div class="my_div">
//div_to_render_JSON_3
</div>
<button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
<div class="main_container">
<div class="my_div">
//div_to_render_JSON_1
</div>
<div class="my_div">
//div_to_render_JSON_2
</div>
<div class="my_div">
//div_to_render_JSON_3
</div>
<button class="trigger_ajax_function_btn">Click to load ajax</button> //this btn loads ajax into the div class "my_div"
</div>
So in conclusion, each of those 6 "divs" has a button that triggers an function containing my ajax to render inside that particular div. But what I get is that every time I click that triggering button, I get the ajax to render in all of the 6 divs, instead of render on each particular div only when I click its particular button.
Thanks a lot people, I really hope to get this done!
Cheers.
PD:
This is something a programmer did to achieve what I'm trying to achieve but I just can't figure out what in this code is that is making possible clicking 1 button and affect THAT html element , even though they all have the same class.
(function(){
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
var xhr = new XMLHttpRequest();
var el;
function SetDataInTheForm()
{
var resp = JSON.parse(xhr.response)
var pt=0
var ct=0
var gt=0
Array.prototype.forEach.call(el.querySelectorAll(".test"),function(e,i){
e.innerHTML=resp[i].name
})
Array.prototype.forEach.call(el.querySelectorAll(".p"),function(e,i){
e.innerHTML=parseFloat(resp[i].p).toFixed(0)
pt+=parseFloat(resp[i].p)
})
Array.prototype.forEach.call(el.querySelectorAll(".c"),function(e,i){
e.innerHTML=parseFloat(resp[i].c).toFixed(0)
ct+=parseFloat(resp[i].c)
})
Array.prototype.forEach.call(el.querySelectorAll(".g"),function(e,i){
e.innerHTML=parseFloat(resp[i].g).toFixed(0)
gt+=parseFloat(resp[i].g)
})
el.querySelector(".wtp").innerHTML=parseFloat(resp[0].total).toFixed(0)+" "+resp[0].unit
el.querySelector(".wtc").innerHTML=parseFloat(resp[1].total).toFixed(0)+" "+resp[1].unit
el.querySelector(".wtg").innerHTML=parseFloat(resp[2].total).toFixed(0)+" "+resp[2].unit
el.querySelector(".pt").innerHTML=pt.toFixed(0)
el.querySelector(".ct").innerHTML=ct.toFixed(0)
el.querySelector(".gt").innerHTML=gt.toFixed(0)
}
function HandleSubmit(e)
{
el=e.currentTarget
e.preventDefault();
xhr.open("POST","/url_here.php",true)
xhr.setRequestHeader("content-type","application/x-www-form-urlencoded")
xhr.onload=SetDataInTheForm
var button=e.currentTarget.querySelector("input[type=submit][clicked=true]")
button.removeAttribute("clicked")
xhr.send($("#"+e.currentTarget.id).serialize()+"&"+button.getAttribute("name")+"=on")
}
[].forEach.call(document.querySelectorAll("._form_"),function(form){
form.addEventListener("submit",HandleSubmit,false);
})
})()
Remember that $('.div_container_to_render_JSON') is a new selector that selects all elements with a class div_container_to_render_JSON. What you want to happen is figuring out where that click came from, and find the corresponding div_container_to_render_JSON.
Luckily for you, a jQuery click handler sets the this keyword to the HTMLElement where the click was captured. You can use this to get the parent element.
$('.your-button').on('click', function () {
const myButton = $(this);
$.ajax({
// ...
success (data) {
myButton.parent().html(data.PHP_JSON_RECEIVED);
// or if you need to find a parent further up in the chain
// myButton.parents('.div_container_to_render_JSON').html(data.PHP_JSON_RECEIVED);
}
});
});
The problem is that your class selector is indeed selecting all your divs at the same time.
Solution, set identifiers for your divs as such:
<div class="my_div" id="my_div_1">
and then you can use those id's to fill in the data:
$('#my_div_1').html(data.PHP_JSON_1_RECEIVED);
and repeat for your 6 divs (notice the change from class selector '.' to identifier selector '#')
Thanks for the replies people. I finally figured it out after days of hard work, it was something really simple.. here's the answer:
$('.trigger_button_inside_divs').click(my_ajax_function);
var thisButton = $(this);
var thisDiv = thisButton.closest(".main_container");
function my_ajax_function(){
$.ajax({
dataType: "JSON",
type: 'POST',
url: test.php,
success: function(data) {
thisDiv.find('.div_to_render_JSON_1').html(data.PHP_JSON_1_RECEIVED);
thisDiv.find('.div_to_render_JSON_2').html(data.PHP_JSON_2_RECEIVED);
thisDiv.find('.div_to_render_JSON_3').html(data.PHP_JSON_3_RECEIVED);
}
});
}

Knockout JS - On click load modal edit form for the item selected

I apologize in advance for the lenghty explanation. I have a web application that loads a grid of records. Each grid row shows only portions of the total record. The user is presented with an Edit button on the grid for each row records. So far I have my web applications fully working with JQuery but after I found out about Knockout js I needed to implement it to my web application.
With KO I set the data-bind="attr: { 'data-ID': ID }" on the button to identify what record is being edited. I am then able to grab the ID of the button and pass it on to my function as such:
$(document).on("click", ".edit_button", function() {
var Button_ID = $(this).data("id");
IncidentManager.showIncidentDetails(Button_ID);
$('#myModal').modal({ backdrop: 'static', keyboard: false });
});
Clicking the Edit button would shows a modal and displays an editor revealing all the fields of the record they selected. This is the part I am having the most trouble with. With JQuery I can accomplish this part by using the code below. But I am not understanding how to implement this with knockout js, can't figure out how to tell knockout to reveal all the fields of the record the user selected.
// This function will loadup the data into the modal form,
showIncidentDetails: function (Button_ID) {
if (Button_ID == null) return;
$.ajax({
url: this.basePath()+'/GDI_PROD_Incidents('+Button_ID+')',
cache: false,
dataType: 'json',
success: function (data) {
$('#DeleteButton').show();
$.each(data, function (index, incident) {
$('#Incident_ID').val(incident.ID);
$('#Description').val(incident.Description);
$('#Composante').selectpicker('val', incident.Composante.split(","));
$('#Incident').val(incident.Incident);
$('#état').find('option[value="'+incident.ÉtatValue+'"]').attr("selected",true);
$('#Priorité').find('option[value="'+incident.PrioritéValue+'"]').attr("selected",true);
$('#Duré').val(incident.Duré);
$('#DateDeDébut').val(incident.Date_de_début);
$('#DateDeFin').val(incident.Date_de_fin);
$('#support').selectpicker('val', incident.Groupe_Support_Prime.split(","));
$('#Autres_Groupe_Support_Prime').attr('value', incident.Autres_Groupe_Support_Prime);
$('#Prime').find('option[value="'+incident.ResponsableValue+'"]').attr("selected",true);
$('#Impact').val(incident.Impact);
$('#Temps_Consacré').attr('value', incident.Temps_Consacré);
$('#Type_de_temps').find('option[value="'+incident.Type_de_tempsValue+'"]').attr("selected",true);
$('#Journal_des_actions').val(incident.Journal_des_actions);
$('#Dépannage_effectué').val(incident.Dépanage);
$('#Suivi').val(incident.Suivi);
$('#Ressources').val(incident.Ressources);
});
}
});
},
This is the knockout code I have written so far:
<script type="text/html" id="Incidents">
<tr>
<td class='over_flow_control'><button class='edit_button btn btn-default btn-sm' type='button' value='Edit' data-bind="attr: { 'data-ID': ID }"><i class='glyphicon glyphicon-edit'></i></button></td>
<td class='over_flow_control' data-bind="text:Incident"></td>
<td class='over_flow_control'><h4><span class='priorité_span' data-bind="text:PrioritéValue"></span></h4></td>
<td class='over_flow_control' data-bind="text:Composante"></td>
<td class='over_flow_control text-left' data-bind="text:Description"></td>
<td class='over_flow_control Date_de_début_cell' data-bind="text:Date_de_début"></td>
<td class='over_flow_control' data-bind="text:ResponsableValue"></td>
</tr>
</script>
<script type="text/javascript">
function load_active_incidents() {
var self = this;
self.ActiveIncidents = ko.observableArray([]);
$.getJSON("../../../../_vti_bin/listData.svc/GDI_PROD_Incidents?$filter=ÉtatValue%20ne%20%27Fermé%27&$orderby=PrioritéValue desc",function (data) {
if (data.d.results) {
self.ActiveIncidents(ko.toJS(data.d.results));
}
}
);
}
$(document).ready(function () {
ko.applyBindings(new load_active_incidents());
});
</script>
I would really appreciate any help at this point.
For each different element of state in your view, you're going to want to have an observable in your viewmodel. For example, your DeleteButton should have a visible binding:
<button data-bind="visible:showDeleteButton">...
You usually don't need to have ids on elements when using Knockout because you don't have to select them to fiddle with them. You change what they're bound to and Knockout updates the element.
Where you have things like
$('#Incident_ID').val(incident.ID);
You would do something like
incidentId(incident.ID);
in your viewmodel, where incidentId is an observable. Have you gone through the Knockout tutorials? The documentation is quite good and the tutorials are very helpful for getting an understanding of how to do things.

Passing in a global javascript array to jQuery document(ready)

I have the following html rendered from templating (jsRender)
<div class="noteActions top" style="z-index: 3;">
<span onclick="noteAction('add', 13808, 0 );"></span>
<span onclick="noteAction('update',13808, 106344 );"></span>
<span onclick="noteAction('delete', 13808, 106344 );"></span>
</div>
My issue is I have a function outside the document ready that is setting a data array that later, a jquery dialog window submits via ajax to the handler to update the database
What's happening is the data array correctly passes everything except the jquery vals by class selector (pr-body, pr-title), they pass as NULL
javascript - outside document (ready)
var updateUrl = 'handlers/Poster.ashx',
data;
function noteAction(action, prospectID, noteID){
data = {
'operation': action,
'prospectid':prospectID,
'note-body' : $('.pr-body').val(),
'note-title' : $('.pr-title').val(),
'note-id':noteID,
};
if (action == 'add'){
$( "#dialogPostIt" ).dialog("open", "option", "title", "Add Post It");
} else if (action == 'update'){
$( "#dialogPostIt" ).dialog("open", "option", "title", "Edit Post It");
} else if (action == 'delete'){
if (!confirm('Are you sure you want to delete')) return false;
$.post(updateUrl+"?operation=delete&noteid="+noteID, function(data) {
$('#stickyNote-'+noteID).remove();
});
}
}
jquery - document ready
$(document).ready(function() {
$( "#dialogPostIt" ).dialog({autoOpen: false, modal:true,
buttons: {
'Save': function() {
$.ajax({
url: updateUrl,
data: data,
success: function(json, textStatus, jqXHR){
.....
html
<div id="dialogPostIt" >
<form id="postItNow" action="" method="post" class="note-form">
<label for="note-title">Title (description)</label>
<input type="text" name="note-title" id="note-title" class="pr-title" value="" />
<label for="note-body">Text of the note</label>
<textarea name="note-body" id="note-body" class="pr-body" cols="30" rows="6"> </textarea>
</form></div>
I previously was setting the data array inside the dialog save button function(), which worked fine, but I needed to make some of the array elements dynamic based on event
The array doesnt have to be global from my requirements, i just couldnt think of another way todo this
As Always, any help is greatly appreciated
Well, i feel like a real dope, it actually is working fine, issue was pilot error -_-
The data array was returning the values correctly, problem is there was no values yet , as the data was set prior to the subsequent dialog containing the form, so no form vals couldve been filled in yet
the fix
javascript outside the document ready
function noteAction(action, prospectID, noteID){
data = {
'operation': action,
'prospectid':prospectID,
'notebody' : '',
'notetitle' : '',
'noteid':noteID,
};
jquery in dialog (document ready)
$( "#dialogPostIt" ).dialog({autoOpen: false, modal:true,
buttons: {
'Save': function() {
data.notebody = $('.pr-body').val();
data.notetitle= $('.pr-title').val(),
$.ajax({
url: updateUrl,
data: data,

How to display a input button and close the current window

I have a call to a service using ajax, i would like if everything goes well on the ajax call to enable or display an input (maybe in a div?) on my page that when clicked it will close the current window. What is the best way to do this using javascript?
Here is my function of a javascript class:
MyFunction.prototype.init = function(param1, param2) {
this.MyParams = new Hash();
this.MyParams.set("param1", param1);
this.MyParams.set("param2", param2);
new Ajax.Request('MyService.asmx/MyServiceFunction', {
method: 'post',
onSuccess: //how can i do what i mentioned here?,
onFailure: failureFunc,
onException: ajaxError,
parameters: this.MyParams
});
}
Any help would be much appreciated
On the onSuccess part you have to put something like this:
OnSuccess: function() {
$('div_to_show').show();
}
In the HTML part you will have this:
<div id="div_to_show">
<input type="button" name="close" id="close" value="close" onclick="javascript:window.close();" />
</div>
Of course you have to hide the div on document loading.

Categories