Show callback after button click - javascript

This is pretty a newby question but I can't figure this one out because it is a different approach/way of writing then I'm used to!
I'm using the app "Back in Stock" for a webshop that's not shopify but something like that. This app shows a modal when a product is out of stock to register your email to recieve an update.
Further I created my own modal because of translation issues and more country related stuff.
I'm having trouble to create or to run a function to show a success or error message when I click a button.
The docs say that this is the way to grab all messages:
var notificationCallback = function(data) {
var msg = '';
if (data.status == 'OK') {
msg = data.message; // just show the success message
} else { // it was an error
for (var k in data.errors) { // collect all the error messages into a string
msg += data.errors[k].join();
}
}
alert(msg);
}
I have created a function that shows the popup and handles the submit:
<button class="notify_button pp pull-right" data-product-id="{{ product.id }}" data-variant-id="{{ product.vid }}" onclick="notify_me_function(this,event);">{{ 'Email when available' | t }}</button>
function notify_me_function(el ,event){
var variantId = $(el).data('variant-id');
var productId = $(el).data('product-id');
var itemName = $(el).closest('.item').find('.item-name').text();
$('#notify__').modal('show');
$('#notify__ #notify_button').on('click', function(e) {
e.preventDefault();
var email = $('#notify__ .form-horizontal input').val();
var $container = $('.completed_message');
// this piece of code below is also from the docs /////////
BIS.create(email, variantId, productId).then(notificationCallback);
//something like this?? ///
$container.txt(msg);
});
}
How do I show the msg from notificationCallback everytime I click the submit button inside the modal?

In your notify modal dialog html markup put something like
<div id="#puttexthere"></div>
then you can do
$('#puttexthere').text(msg);
Hopefully what you need.

Related

How to do update in listing for web by using firebase

I am creating admin panel in website and I am using firebase as a database in backend.I am able to display listing but when I click on the particular listing there status should change from 'pending' to 'accept' but it doesnt.I dont know where I did mistake.Please give suggestion and I attach js file and database screenshot
pl.js
var firebaseheadingRef = firebase.database().ref().child("user");
firebaseheadingRef.on('child_added',datasnapshot=>{
var title= datasnapshot.child("listing").child("title").val();
var userid= datasnapshot.child("username").val();
var type= datasnapshot.child("listing").child("title").val();
var publisheddate= datasnapshot.child("listing").child("publish").val();
var expirydate= datasnapshot.child("listing").child("expire").val();
$("#tablebody").append("<tr><td>"+title+"</td><td>"+userid+"</td><td>"+type+"</td><td>"+publisheddate+"</td><td><button type=button id=accept onclick=accept()>Accept</button><button type=button>Reject</button></td></tr>");
});
function accept()
{
firebaseheadingRef.on('child_changed',datasnapshot=>{
datasnapshot.child("listing").child("status").update({"status":"accept"});
setCommentValues(postElement, data.key, data.val().text, data.val().author);
});
}
database
listing display picture where I click on accept button then update of status should done
There are two places where you need to change your code:
First, in the code that generates the table, you have to pass the id of the node to the function call, as follows. You get the node id with the key property of the DataSnapshot.
.....
$("#tablebody").append("<tr><td>"+title+"</td><td>"+userid+"</td><td>"+type+"</td><td>"+publisheddate+"</td><td><button type=button id=accept onclick=accept('" + datasnapshot.key + "')>Accept</button><button type=button>Reject</button></td></tr>");
...
And secondly you have to write your accept() function in such a way it updates the database value, with the set() method. Like the following
function accept(userId) {
var nodeRef = firebase.database().ref("/user/" + userId + "/listing/status");
return nodeRef.set('accept');
}

Multiple Delete/Update using php- Codeigniter Ajax

The console.log(response) returns the code of whole page in console when I inspect it in ajax . I have created a codeigniter project with MySQL as back end database . I have fetched content from table from database into table. Now I want to give option to user of mulitple delete. Please take it into account that I am not actually deleting value from table I am just turning status of of that row to inactive. It goes as :
If status= 0 : the row's data will be visible in table.
If status= 1:the row's data will not be visible in table.
I have given checkbox option in the table to select multiple checkbox.
Here is my javascript:
To check all the check boxes:-
<script language="JavaScript">
function selectAll(source) {
checkboxes = document.getElementsByName('sport');
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
</script>
javascript to get value's from the checkboxes and send it to controller:
<script type="text/javascript">
function okay(){
var favorite = [];
$.each($("input[name='sport']:checked"), function(){
favorite.push($(this).val());
var txt=$(this).val();
});
for (var i = 0;i<favorite.length;i++) {
$.ajax({
url:('<?=base_url()?>/Repots/supervisor_muldel'),
type:'POST',
data:{'value_id':favorite[i]},
success:function(response)
{
console.log(response);
},
error:function(response)
{
console.log('nahi gaya');
},
});
//console.log(favorite[i]);
}
//alert("My favourite sports are: " + favorite.join(", "));
}
</script>
every check box is associate with particular values.
here the html button to call the fucntion:
<button onclick="okay();">Delete Selected</button>
Controller:Reports/supervisor_muldel:
//multiple delete supervisor
public function supervisor_muldel() {
$value_id = $this->input->post('value_id');
$selected_supervisor = array('supervisor_id' =>$value_id);
$staus=array('status'=>1);
$this->load->model('Entry_model');
$result = $this->Entry_model->supervisor_muldel($staus,$selected_supervisor);
}
Entry_model/supervisor_muldel:
//delete multiple supervisor
public function supervisor_muldel($staus,$condition)
{
$this->db->trans_start();
$this->db->where($condition)
->update('tbl_supervisor',$staus);
$this->db->trans_complete();
}
The console.log returns the code of whole page in console.I am stuck here.
You have put wrong ajax request URL.
Change
url:('<?=base_url()?>/Repots/supervisor_muldel'),
to
url:('<?=base_url()?>/Reports/supervisor_muldel'),
Look at the controller name in URL.

How do I populate a list field in a model from javascript?

I have a Kendo.MVC project. The view has a model with a field of type List<>. I want to populate the List from a Javascript function. I've tried several ways, but can't get it working. Can someone explain what I'm doing wrong?
So here is my model:
public class Dashboard
{
public List<Note> ListNotes { get; set; }
}
I use the ListNotes on the view like this:
foreach (Note note in Model.ListNotes)
{
#Html.Raw(note.NoteText)
}
This works if I populate Model.ListNotes in the controller when the view starts...
public ActionResult DashBoard(string xsr, string vst)
{
var notes = rep.GetNotesByCompanyID(user.ResID, 7, 7);
List<Koorsen.Models.Note> listNotes = new List<Koorsen.Models.Note>();
Dashboard employee = new Dashboard
{
ResID = intUser,
Type = intType,
FirstName = user.FirstName,
LastName = user.LastName,
ListNotes = listNotes
};
return View(employee);
}
... but I need to populate ListNotes in a Javascript after a user action.
Here is my javascript to make an ajax call to populate ListNotes:
function getReminders(e)
{
var userID = '#ViewBag.CurrUser';
$.ajax({
url: "/api/WoApi/GetReminders/" + userID,
dataType: "json",
type: "GET",
success: function (notes)
{
// Need to assign notes to Model.ListNotes here
}
});
}
Here's the method it calls with the ajax call. I've confirmed ListNotes does have the values I want; it is not empty.
public List<Koorsen.Models.Note> GetReminders(int id)
{
var notes = rep.GetNotesByCompanyID(id, 7, 7);
List<Koorsen.Models.Note> listNotes = new List<Koorsen.Models.Note>();
foreach (Koorsen.OpenAccess.Note note in notes)
{
Koorsen.Models.Note newNote = new Koorsen.Models.Note()
{
NoteID = note.NoteID,
CompanyID = note.CompanyID,
LocationID = note.LocationID,
NoteText = note.NoteText,
NoteType = note.NoteType,
InternalNote = note.InternalNote,
NoteDate = note.NoteDate,
Active = note.Active,
AddBy = note.AddBy,
AddDate = note.AddDate,
ModBy = note.ModBy,
ModDate = note.ModDate
};
listNotes.Add(newNote);
}
return listNotes;
}
If ListNotes was a string, I would have added a hidden field and populated it in Javascript. But that didn't work for ListNotes. I didn't get an error, but the text on the screen didn't change.
#Html.HiddenFor(x => x.ListNotes)
...
...
$("#ListNotes").val(notes);
I also tried
#Model.ListNotes = notes; // This threw an unterminated template literal error
document.getElementById('ListNotes').value = notes;
I've even tried refreshing the page after assigning the value:
window.location.reload();
and refreshing the panel bar the code is in
var panelBar = $("#IntroPanelBar").data("kendoPanelBar");
panelBar.reload();
Can someone explain how to get this to work?
I don't know if this will cloud the issue, but the reason I need to populate the model in javascript with an ajax call is because Model.ListNotes is being used in a Kendo Panel Bar control and I don't want Model.ListNotes to have a value until the user expands the panel bar.
Here's the code for the panel bar:
#{
#(Html.Kendo().PanelBar().Name("IntroPanelBar")
.Items(items =>
{
items
.Add()
.Text("View Important Notes and Messages")
.Expanded(false)
.Content(
#<text>
#RenderReminders()
</text>
);
}
)
.Events(e => e
.Expand("getReminders")
)
)
}
Here's the helper than renders the contents:
#helper RenderReminders()
{
if (Model.ListNotes.Count <= 0)
{
#Html.Raw("No Current Messages");
}
else
{
foreach (Note note in Model.ListNotes)
{
#Html.Raw(note.NoteText)
<br />
}
}
}
The panel bar and the helpers work fine if I populate Model.ListNotes in the controller and pass Model to the view. I just can't get it to populate in the javascript after the user expands the panel bar.
Perhaps this will do it for you. I will provide a small working example I believe you can easily extend to meet your needs. I would recommend writing the html by hand instead of using the helper methods such as #html.raw since #html.raw is just a tool to generate html in the end anyways. You can write html manually accomplish what the helper methods do anyway and I think it will be easier for you in this situation. If you write the html correctly it should bind to the model correctly (which means it won't be empty on your post request model) So if you modify that html using javascript correctly, it will bind to your model correctly as well.
Take a look at some of these examples to get a better idea of what I am talking about:
http://www.hanselman.com/blog/ASPNETWireFormatForModelBindingToArraysListsCollectionsDictionaries.aspx
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
So to answer your question...
You could build a hidden container to hold your list values like this (make sure this container is inside the form):
<div id="ListValues" style="display:none">
</div>
Then put the results your ajax post into a javascript variable (not shown).
Then in javascript do something like this:
$('form').off('submit'); //i do this to prevent duplicate bindings depending on how this page may be rendered futuristically as a safety precaution.
$('form').on('submit', function (e) { //on submit, modify the form data to include the information you want inside of your ListNotes
var data = getAjaxResults(); //data represents your ajax results. You can acquire and format that how you'd like I will use the following as an example format for how you could save the results as JSON data: [{NoteID ="1",CompanyID ="2"}]
let listLength = data.length;
for (let i = 0; i < listLength; i++) {
$('#ListValues').append('<input type="text" name="ListNotes['+i+'].NoteID " value="' + data.NoteID +'" />')
$('#ListValues').append('<input type="text" name="ListNotes['+i+'].CompanyID " value="' + data.CompanyID +'" />')
//for your ajax results, do this for each field on the note object
}
})
That should do it! After you submit your form, it should automatically model bind to you ListNotes! You will be able to inpsect this in your debugger on your post controller action.

Set flash message after redirect in angularjs

I am just starting with Angular js. I have a doubt in that. I want to set flash messsage after redirect.
In my case, I have a form and am saving the data through http requst. In the success function I put window.location(). It is another page. I want to set a flash message in that page.
js
$scope.Save_Details = function (id)
{
$http.post(base_url+"sur/sur/save_data/"+id,{data:$scope.Surdata}).
success(function(response) {
// $scope.successTextAlert = "Saved";
// $scope.showSuccessAlert = true;
window.location = "#/surpage/nextpage?show_message= true";
});
}
new update
var messageFlag = $location.search().show_message;
if(messageFlag && messageFlag === 'true'){
alert(messageFlag);
$scope.successTextAlert = "Saved";
$scope.showSuccessAlertMsg = true;
}
view
<div class="alert alert-success" ng-show="showSuccessAlert">
<button type="button" class="close" data-ng-click="switchBool('showSuccessAlert')">×</button> <strong> {{successTextAlert}}</strong>
</div>
Anyone help me?
Put this code in HTML -
<!-- message text -->
<div class=" panel-{{alerts.class}}" ng-show="alerts.messages" >
<div ng-repeat="alert in alerts.messages track by $index" class="panel-body alert-{{alerts.class}}" >{{alert}}</div>
</div>
Put this code in angular model -
$rootScope.alert = function(type,msg){
$rootScope.message.push(msg);
$rootScope.alerts = {
class: type,
messages:$rootScope.message
}
}
For success message -
$rootScope.alert('success',"Success !!!");
For Error message -
$rootScope.alert('danger',"Error.");
You can use toastr JS specially for flash.
http://codeseven.github.io/toastr/demo.html
By using below js code, you can display a flash message.
For success message :
toastr"success";
For Error message :
toastr"success";
EDIT - Adding code
yourAppModule.controller('nextPageController', function($location){
var messageFlag = $location.search().show_message;
if(messageFlag && messageFlag === 'true'){
//show your message
}
});
When you navigate to "nextpage" pass a flag along -> #/surpage/nextpage?show_message= true
In the "nextpage" controller, read the query string value for
"show_message" ( inject $location to your controller and get value
using $location.search().show_message)
if that value == true, show your flash message

How do I create a web link inside a javascript function and pass cell value as a parameter to servlet?

I am creating a table dynamically with JavaScript as you can see below. I want users to be able to click on the first column value and pass the value of the cell as a parameter to a J#EE servlet. Can you help me? Basically the first column should be links to a new page with a country details. How can I do that? Thank you.
Where do I put the link code?
function oneSecondFunction() {
$.get('DisplayCountries', function(responseJson) {
if (responseJson != null) {
$("#countrytable").find("tr:gt(0)").remove();
var table1 = $("#countrytable");
$.each(responseJson, function(key, value) {
var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td>" +
"<td></td><td></td></tr>");
rowNew.children().eq(0).text(value['id']);
rowNew.children().eq(1).text(value['country1']);
rowNew.children().eq(2).text(value['country2']);
rowNew.children().eq(3).text(value['country3']);
rowNew.children().eq(4).text(value['country4']);
rowNew.children().eq(5).text(value['country5']);
rowNew.children().eq(6).text(value['country6']);
rowNew.children().eq(7).text(value['country7']);
rowNew.children().eq(8).text(value['country8']);
rowNew.appendTo(table1);
});
}
});
and here is the link code. I have tried several options and it doesn't work.
id
First, assign a class to the first <td> something like <td class="linkHolder">.
Then, write a click handler to send ajax request to servlet:
$('#countrytable').on('click', '.linkHolder', function() {
var link = $(this).html();
$.post('/myservlet', {url: link}, function(response) {
//handle response here
});
return false;
});
You can access the link on the servlet side with the request parameter url

Categories