fetch data from SQL and populate dynamicaly on html - javascript

i am working on simple retail management web app.i have sale page which have a input field which gets data from a bar code scanner.here is sample code of it
html code
<div id = "sale-form" class="form-group">
<label>PRODUCT CODE</label>
<input type="text" id ="get-code"><span class="errors" id="get-code- error"></span>
</div>
<script>
$(document).ready(function(){
$('#get-code').focus();
})
</script>
<div id="bill">
</div>
j query
$('#get-code').bind('change paste ',function(){
var vall = $(this).val();
if(vall == ""){
$('#get-code-error').text("NO PRODUCT CODE ENTERED");
}
else{
//run some script to fetch data and add row to $('#bill') dynamically;
}
})
i need help in the script which fetches data from SQL based on product code
adds a editable row to the div with id bill every time when new data is typed in input.i have tried with html table but unable to do that.

You almost did it: you have the change and paste event and it should work.
In the else statement, where you have the comment just make an ajax request to the web server to get the data and on the success parse the response and display it in the div. Documentation of the ajax method of jquery can be found here: http://api.jquery.com/jquery.ajax/
If the problem is adding the row in the div: just use the append method of jquery.

Related

How to Set Header Text of Modal Dialog According to the Table element and his ID

Hello everyone and sorry in advance for my very bad English.
I'm working on an ASP.NET MVC project with a JavaScript framework as the front-end.
I have a table which contains customer names retrieved from a database. Now I want to show a modal dialog and set the text of its header according to the customer name which has been clicked. At the same time I would like to get the customer Id. For example, when clicking "Georges", the modal dialog pops up and its header text is set to "Georges".
Here is my code.
The customer table look like this:
<div class="col-lg-6">
<div class="container-fluid" id="DailyTask">
<h4>Daily Tasks</h4>
#if (Model != null)
{
List<SchedulerTool.Models.spGetDailyBatchTask_Result> batches = Model.DailyTask;
foreach (var batch in batches)
{
<div class="bs-callout bs-callout-warning" id="dailybatch">
<input name="currentdailyBatchId" id="#batch.BatchId" hidden type="text" value="#batch.BatchId" />
<input name="currentdailyBatchName" id=" #batch.BatchName " hidden type="text" value=#batch.BatchName />
<button class="btn btn-group-justified" id="dailybatchTask" data-title="#batch.BatchName" data-target="#dailybatchTaskModal" data-toggle="modal" data-bid="#batch.BatchId">
<span class="fa-bitbucket-square" id="name">#batch.BatchName</span>
</button>
</div>
}
}
</div>
The JavaScript code is:
$('dailybatchTask').on('click', function ()
{
var batchId = $(this).data('bid');
var batchName = $(this).data('title');
// Here I set the table name a template table
$("h4 a#bathDailyTaskModalLabel").html(batchName);
// Here I set the Id to a template table
loadMasterTable("LoadObjectsNotBatched", batchId, DailyBatchElementUrl, "DailyBatchCollapseElementId");
});
Customers table:
The modal that is popover when clicked on customer:
The problem is: when I clicked on the first element of the customer table, the modal is correctly shown (the header and id are correct) but when I clicked on the others elements the JavaScript code is not executed.
Hope someone can try to understand my problem and will help me!
You are trying to catch all buttons by ids. But in HTML ids must be unique. Because that jquery your click event only matches first data. You need to fix ids before jquery part. If you really need it you can define a counter for loop and use it like this;
id="dailybatchTask-#counter"
But you already defined data-bid so basically, you can just add a class name for the button like this;
class="btn btn-group-justified daily-batch-button"
then only you need to;
$('daily-batch-button').on('click', function () {
...
...
...
});

HTML Select field calls web services through ajax

I have some modal with forms where I create object to store into database.
In these forms I have a Select field like this:
<div class="form-group" id=existingUser>
<label>Username</label> <select class="form-control select2"
style="width: 100%;" th:field="*{user}">
<option th:each="user: ${users}" th:value="${user.username}"
th:text="${user.username}"></option>
</select>
</div>
where users is passed from Controller with Model. With this approach I have to update all page to refresh the values inside select field otherwise I can only update the table where I show the new created object but I can't use the new field in select.
The problems are the performance and the look refreshing page, furthermore I can't use these instruction to show my message
location.reload();
//reload only the tag with id carsTable, so only the table
//$('#carsTable').load(document.URL + ' #carsTable');
$('#addCarModal').modal("hide");
notifyMessage("Your car has been created!", 'success');
function notifyMessage(textMessage, typeMessage){
$.bootstrapGrowl(textMessage, {
type: typeMessage, // (null, 'info', 'error', 'success')
});
}
Is there a way to call ajax when modal is called? Or can I pass data from javascript to HTML (if I retrive values when add button is clicked).
Sometimes I also check if select field are empty and in this case show a message inside the modals instead form.Thanks
UPDATE. I thouth this code:
To start with only success manage:
function freeUserController($scope) {
$http.get("https://localhost:8080/users/")
.success(function(data) {
$scope.users = data;
});
}
in my html page:
<div ng-controller="freeUserController" class="form-group" id=existingUser>
<label>Username</label> <select class="form-control select2"
style="width: 100%;" name="user">
<option ng-repeat="user in users" value="{{user.username}}">
{{user.username}}</option>
</select>
</div>
I assume you are rendering the HTML on the server. There is probably no way to make it re-render just that element. However, there are different ways you can do this:
One, you could start using client-side MVC / rendering like Angular.js. That way, you could automatically refresh the select field when a new field is added.
Two, you could put the new option into the select field without using an MVC system. That would require uncoupling the data from the view, so I wouldn't recommend it. However, you could have the submit button perform an ajax call to make sure the server reacted correctly, and only add the new option when the server response has arrived. Your code would look something like this:
$.ajax(url).done(function(){
$('#my-select').append('<option>').html('your data')
}).fail(function(){
// show error message...
});

PHP undefined index from function send via jQuery

I am trying to make a function that will insert a html code (div) into a container, said div has an ID of the number of elements inside that container +1 (so when it adds the first it won't be 0). I am fairly (read 1 week) new to JS, jQuery and PHP so I am having trouble tyding up my code so it can do what I need.
Right now when I use the function it is displaying a undefined index error. The process the code should run is this:
In one page I enter some data and click a Accept button which saves that data into a database (Done).
2.When I click the accept button it also call a function that creates the aforementioned div, this code is in another file and its called with:
<script src="js/createLabDiv.js"></script>
The code of function goes like this (most likely with error >.< )
function agregar("#btnAceptar") {
var div = document.createElement('div'); //Creates div variable.
div.id = querySelectorAll('lista > div').length +1; //assigns id to div based on elements inside the list
var numero = div.id; //I'll need this to display a specific set of info depending on the div id.
'<div class="box"> // Code for the div.
<p>Lab #'numero'</p>
<p class="info">Info</p>
<p class="info">Reservar</p>
</div>';
document.getElementById('lista').appendChild(div); //Where it is isnserting it.
var request = $.ajax({ //Here it gets muddy, I want to send this data to a php file so I can call it on my list.php
url: "includes/functionsLabs.php",
type: "post",
data: {
'call': 'createDiv',
'pDiv':div,
'pNumero':numero},
dataType: 'json',
});
}
3.On my includes php file I have:(Again kinda murky)
function getLabs(){
$idDiv=createDiv();
$query = "SELECT bk.idlab , bk.capacidad, bk.carrera, bk.ubicacion FROM labs as bk WHERE bk.idlab = $idDiv";
$result = do_query($query);
return $result;
}
function createDiv(){
$idDiv = $_POST['pNumero'];
echo $div = $_POST['pDiv'];
$result = $idDiv;
return $result;
}
4.And lastly in a different page I have:
<div class="scroll-area" id="lista">
<?php createDiv() ?>
</div>
Just in case, all of these pages contain the scrip for the js. and the includes for the php.
Both of them are working with the data I entered into my database for testing purposes, also the add (agregar) button on the add.php IS inserting correctly the data from the form, the list.php page which includes the piece of code just above this wall of text is also working when displaying the data from one Lab I already added to the database, the reason I needed number above was that when I called this:
<div class="popUp1 hide" id="popUpCorrecto1">
<div class="estiloPopUp">
<span>InformaciĆ³n de laboratorio</span>
<span value="Cerrar" id="btnCerrar">x</span>
</div>
<?php displayLabs() ?>
<input type="button" value="Eliminar" id="btnEliminar" onclick="eliminar()" />
<input type="button" value="Modificar" id="btnModificar" onclick="window.location='modificarLab.html';" />
</div>
It was displaying the info of all the labs in the databse, thus why I added the WHERE bk.idlab = #idDiv.
I am quite stuck right now, so any kind of help would be very appreciated, I will probably be able to reply until tomorrow cuz I think I feel kinda sick from staring at my monitor all day >.>
Thanks a lot in advance and best wishes!

Display form result on same page using php with smarty

My web app is integrated to facebook. I created a form in tpl file with only has one input, which is select input. User has to choose one of his facebook group. The value of the option is id of each group.
So this is what i would like to do :
When user change the option (onchange), list of members of the selected group will appear bellow the select div. I don't know what i should use (javascript, jquery, ajax, etc) and how to implement it in my code.
Here my code snippet :
{* --- form in tpl file --- *}
<form method="post">
<fieldset>
<div class="row">
<p style="font-weight:bold;">Choose your facebook group :</p>
</div>
<div class="row">
<select name="group" onchange="idontknow">
{foreach from=$userGroupsData item=group}
<option value="{$group.id}">{$group.name}</option>
{/foreach}
</select>
</div>
<div class="row">
{* the place where members list will appear *}
</div>
</fieldset>
</form>
PHP code to retrieve member list of selected group (if I use submit method) :
<?php
$groupId = $_POST['group'];
$groupmember = $facebook->api('/'.$groupId.'/members');
$membergroup = $groupmember['data'];
foreach ($membergroup as $membergroups) {
echo "<li>".$membergroups['name']."</li>";
}
?>
Any help would be greatly appreciated. Thank you
I would make an Ajax request using jQuery:
$(function() {
$('body').on('change', 'select[name="group"]', function() {
var groupId = $(this).val();
$.post('path/to/your/script', groupId)
.done(function(data) {
$('form .row').html(data);
});
});
});
If it were me, I would have the backend return JSON data instead of HTML and I would build the HTML dynamically in the Ajax callback.
Also, this scenario is one of the many reasons I prefer to use MVC architecture on the backend. If you were using an MVC framework like say CodeIgniter for example, the URL you're posting the data to would take care of the routing like this:
MVC-style URL = 'mycontroller/mymethod/myparam'.
In this example, mycontroller would be the class (script) you're calling, mymethod would be the specific function you want to call in the controller, and myparam would be the data you're passing to that function.

How to wait to append the data until after the form data has been added?

When I click the #screenrId, it submits the default data without having time to add the new data the user inputs. How to wait to append the data until after the form input field data has been added?
http://jsfiddle.net/XVCVE/1/
<script type="text/javascript">
$(document).ready(function() {
Screenr.Recorder( { subject:""}).appendTo("screenrId");
});
</script>
<form>
<h4>Subject <input name="subject" id='subject' type="text" ></h4>
</form>
<div id="screenrId" ></div>
I am trying to add the form data to the screen.recorder function before it appends it? Screenr.Recorder( { subject:""}).
Pretty sure I just fixed it: http://jsfiddle.net/XVCVE/3/
The problems:
The "javascript" section in jsfiddle assumes raw javascript, no <script> tags, so I moved that code to the top.
You had a very strange way to make sure the correct HTTP protocol (HTTP or HTTPS) was used to load the 3rd party library, when the browser will do that automatically if you just don't write the http: or https:.
After that, the button appeared after a slight delay.

Categories