Show message in div after saving - javascript

I save some data in my MYSQL database, after saving I wan't to show a text in my div with id #msg. Can somebody help me.
<script>
$(document).ready(function () {
$("#btnAdd").click(function (e) {
/* Retrieving value from textboxes */
var besproken = $('#besproken').val();
var afspraken = $('#afspraken').val();
var coachings_id = $('#coachings_id').val();
var verlengen = $('#verlengen').val();
$.post("save_coaching.php", {
besproken: besproken,
afspraken: afspraken,
coachings_id: coachings_id,
verlengen: verlengen
}, function (data) {
$("form")[0].reset();
});
return false;
});
});
</script>

Just use the .html( ) method on your #msg div:
$.post("save_coaching.php", {
besproken: besproken,
afspraken: afspraken,
coachings_id: coachings_id,
verlengen: verlengen
}, function (data) {
$( "#msg" ).html( data );
$("form")[0].reset();
});
This is assuming the data variable is a simple string. If it's JSON you'll want to use JSON.parse( data ) to convert it back to an object, and then print out the properties you need.

You have few options todo this, for example You can control visibility by CSS.
$.post("save_coaching.php", {
besproken: besproken,
afspraken: afspraken,
coachings_id: coachings_id,
verlengen: verlengen
}, function (data) {
// place code here to manipulate showing the notification div
});
For manipulate code, You can write:
document.getElementById('#msg').style.visibility = 'visible' or 'hidden'
visible or hidden is depend on what You want todo with your #msg element.

Related

Update the values of dropboxes in a html table via javascript

In one page I have three connected dropboxes with parent child relation in this order
Company->Analysis->Scenario
I also have the pair or Node dropboxes in a html table which should be repeated in each row. These dropboxes values should be changed as the parent Scenario dropbox combo value changes.
I also want them to show the relevant value as selected for each row.
This maybe straightforward for a frontend developer but I am struggling a lot.
The top dropboxes are nearly ok. For the dropboxes from the table I managed to change the first row at one point but now lost that version :(
Can you please help me to solve this. I tried nearly everything?
Kind Regards,
Sofia
enter image description here
This is the related code part
`<script charset="utf-8" type="text/javascript">
function _updateNodes() {
var source_elms = document.querySelectorAll("[id='source1']");
for(var i = 0; i < source_elms.length; i++){
source_elms[i].setAttribute('disabled', 'disabled');
if (source_elms[i].hasChildNodes()) {
source_elms[i].empty();
}
for (node in allowed_nodes){
if node[0]==edge.source_id and node[2]== scenario_id
source_elms[i].append($('<OPTION value = node[0] selected>node[1]</option>');
endif
if node[0]!=edge.source_id and node[2]== scenario_id
source_elms[i].append($('<OPTION value = node[0]>node[1]</option>');
endif;
}
}
}
// jQuery selection for the 2 select boxes
var dropdown = {
company: $('#company'),
analysis: $('#analysis'),
scenario: $('#scenario'),
source: $('#source1'),
target: $('#target1')
};
// function to call XHR and update analysis dropdown
function updateAnalysiss() {
var send = {
company_id: dropdown.company.val()
};
dropdown.analysis.attr('disabled', 'disabled');
dropdown.scenario.attr('disabled', 'disabled');
dropdown.analysis.empty();
dropdown.scenario.empty();
$.getJSON("{{ url_for('_get_analysiss') }}", send, function(data) {
data.forEach(function(item) {
dropdown.analysis.append(
$('<option>', {
value: item[0],
text: item[1]
})
);
});
dropdown.analysis.removeAttr('disabled');
dropdown.scenario.removeAttr('disabled');
updateScenarios();
_updateNodes();
});
}
function updateScenarios() {
var send = {
analysis_id: dropdown.analysis.val()
};
dropdown.scenario.attr('disabled', 'disabled');
dropdown.scenario.empty();
$.getJSON("{{ url_for('_get_scenarios') }}", send, function(data) {
data.forEach(function(item) {
dropdown.scenario.append(
$('<option>', {
value: item[0],
text: item[1]
})
);
});
dropdown.scenario.removeAttr('disabled');
});
}
var scenario_id = Null;
function updateNodes() {
scenario_id: dropdown.scenario.val()
}
// event listener to company dropdown change
dropdown.company.on('change', function() {
updateAnalysiss();
});
// event listener to analysis dropdown change
dropdown.analysis.on('change', function() {
updateScenarios();
});
// event listener to scenario dropdown change
dropdown.scenario.on('change', function() {
alert("aa");
_updateNodes();
alert("bb");
});
$('#company').change(function() {
updateAnalysiss();
});
$('#analysis').change(function() {
updateScenarios();
});
$('#scenario').change(function() {
alert("aa1");
_updateNodes();
alert("bb1");
});
// call to update on load
updateAnalysiss();
</script>
`

Populate Bootstrap modal form fields from JSON

I've got a Bootstrap modal that displays a large form (30+ inputs).
I wrote the following code to populate the first few fields from JSON.
$('#seg-detail-modal').on('shown.bs.modal', function (e) {
var modal = $(this);
$.get( "includes/segdata.json", function( data ) {
$('#seg-detail-modal').find("input[name='segCode']").val(data.segCode);
$('#seg-detail-modal').find("input[name='orgName']").val(data.orgName);
$('#seg-detail-modal').find("input[name='referenceId']").val(data.referenceId);
});
});
Is there a more efficient way of populating a large form than what I'm doing here?
You could just iterate through the object properties and match selector to property in that loop.
Something like:
$('#seg-detail-modal').on('shown.bs.modal', function(e) {
var $inputs = $(this).find(':input');
$.getJSON("includes/segdata.json", function(data) {
$.each(data, function(key, val) {
$inputs.filter('[name="' + key + '"]').val(val);
});
});
});
If a property exists that doesn't have a match the selector will just fail quietly

Getting Data from button click for Jquery

I am using the "Second Solution" from this problem:
call the same jQuery function in multiple buttons
I am dynamically creating my buttons, based on an input, so there is currently 45 buttons! (used to select page number)
Is there a way to use the value of the button as data in my $.get so I can pull the data for the page?
$('.bclick').click(function(){
$.getJSON("url", { page: [need button data here] }, function(data){
//Some actionable code
})
});
.bclick is the class given to each of the buttons created.
when you are inside of the function, the reserved word this is a reference to your clicked button.
$('.bclick').click(function(){
var page = $(this).val();
$.getJSON("url", { page: page }, function(data){
//Some actionable code
})
});
If your buttons are created dinamically probably this solution won't work. I may suggest you to use $.on():
$("parent selector or form selector").on("click", ".bclick", function(){
var page = $(this).val();
$.getJSON("url", { page: page }, function(data){
//Some actionable code
})
})
If you are generating buttons dynamically, then use .on.
$(function(){
$(document).on("click", ".blick", function(){
var $this = $(this);
var buttonName = $this.attr("name");
});
});
Sample code
Yes you can by adding an extra attribute to your .bclick element, for example
<button class="bclick" data="your data here"></button>.
Then
$('.bclick').click(function(){
var buttonData = $(this).attr('data');
$.getJSON("url", { page: buttonData }, function(data){
//Some actionable code
})
});

Appending item to list with Ajax after post - layout related

I have an activity stream for both users use, and site-wide view. Currently when a user posts an update, I have it displaying a default bootstrap success alert. I have seen other websites append the new post to the list by sliding down the existing items, and appending the newest post to the top of the list.
I am attempting to do just that, but I am not sure how to add it with all the proper styling. (code below). I am tried adding all the <div> tags that make up one activity item in my feed, but without success.
TL;DR - Is there a way to have ajax look at the current top activity item, clone it, and append it to the top? It would make the code more dynamic for my use, and avoid having to place CSS inside the .js file.
jQuery(document).ready(function ($) {
$('form#postActivity').submit(function (event) {
event.preventDefault();
$postActivityNow = (this);
var subject = $('#activity_subject').val();
var message = $('#activity_content').val();
var data = {
'action': 'postAnActivity',
'subject': subject,
'message': message,
}
$.ajax({
type: 'post',
url: postAnActivityAjax.ajaxurl,
data: data,
error: function (response, status) {
alert(response);
},
success: function (response) {
if (response.success) {
bootstrap_alert.success('Activity Added');
} else {
if (response.data.loggedIn == false) {
bootstrap_alert.warning('you are NOT logged in');
console.log('you are not logged in')
}
if (response.data.userExists == false) {
console.log(response);
bootstrap_alert.warning(response.data.alertMsg);
console.log(response.data.alertMsg)
}
}
}
});
});
});
you can also use .prependTo()
var newActivity = $( ".activity" ).first().clone();
newActivity.prependTo( ".parentDiv").hide().slideDown();
FIDDLE
To clone an element: jQuery.clone()
var newItem = $("#myDiv").clone();
To append it as first child: jQuery.prepend()
$("#parentDiv").prepend( newItem );
Regards,
hotzu
I have already done in the past using $.prepend()
Check this url for more information jquery append to front/top of list

Removing an unbind on a button in jquery?

function getData(url) {
$.getJSON(url, function(result) {
$('#formNav ul').append('<ul/>')
$.each(result, function() {
var list = $('#formNav li'),
listItem = $('<li/>'),
html = listItem.append($('<h5/>').text(this.name));
$.each(this.items, function() {
listItem.append($('<a />').attr('href', this.id).text(this.name))
});
list.append(html)
});
});
};
$(function(){
var Menu = {
$menu: $('.config-nav #formNav'),
$trades : $(".config-nav select#tradesmanList"),
$skills : $(".config-nav select#jobList"),
init: function(){
var $menu = Menu.$menu;
// Set menu up
$menu.children("li").addClass('closed');
$menu.find(".js-reveal").hide();
Menu.$skills.attr("disabled", "disabled");
Menu.$trades.on("change", function($skills){
Menu.$skills.removeAttr("disabled");
});
// bind to click on the item...
$menu.on("click", "h4", this.toggle);
},
toggle: function() {
// Toggle the hide show of the drill down menu
var $this = $(this),
$category = $this.parent();
console.log($this.parent().index());
var data = getData("test.json");
$category.addClass("loading").toggleClass("open");
$this.next(".reveal").delay(100).toggle(0, function(){
$category.Data;
$category.removeClass("loading");
});
}
};
Menu.init();
});
I have a function that returns json data , i then call this function in the Menu function to display the data however every time i click the button the data just keeps being generated instead i want it to display the data and then once it is clicked again hide the data? if anyone has any advice that would be great.
Thanks.
When ever you call the toggle function You seem to get the data using
var data = getData("test.json"); and then use it to populate the list..
Why don't you move the getData method to outside the toggle function and instead move it to to init function .. Look's like it should be fine then..

Categories

Resources