HTML Select field calls web services through ajax - javascript

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...
});

Related

Why aren't my JS functions not being executed if the model of the page is populated with data?

I am developping a web app, using ASP .NET Core 2.0
I have a partial view that contains a form.
Then I have an action method inside a controller that is executed through a JS function, that uses AJAX.
This action method populates a model and returns the form partial view and corresponding model.
The function works well, as long as the model is not populated.
I need to fetch a record from the database when a determined field is filled and then loses focus. This works for the first time, when the model used in the form is empty. However, after finding a record for the first time and filling the form, the function is not executed anymore.
Also, the validations of the field also don't work after a record is loaded.
Here's the form partial view:
<form id="myform">
<div asp-validation-summary="All" class="text-danger"></div>
<div class="form-group col-lg-2">
<label asp-for="Client.Name">Client</label>
<input asp-for="Client.Name" id="ClientName" />
</div>
<div class="form-group col-lg-1">
<label asp-for="Cliente.Phone"></label>
<input asp-for="Cliente.Phone" id="Phone"/>
</div>
</form>
The JS/AJAX function:
<script>
$("form").on("blur", "#Phone", function () {
var phone = document.querySelector('#Phone').value;
alert('select client by phone=' + phone);
//Send the JSON array to Controller using AJAX.
$.ajax({
type: "POST",
url: "/Home/GetClienteByPhone",
data: "phone=" + phone,
success: function (res) {
$('#myform').html(res);
}
})
});
</script>
Finally, the controller action method (Controller=Home):
public IActionResult GetClienteByPhone(string phone)
{
if (!string.IsNullOrEmpty(phone))
{
var model = new FormViewModel();
model.Client = _db.Clients.Where(c => c.Phone == phone).FirstOrDefault();
return PartialView("_Form", model);
}
return PartialView("_Form");
}
On my View, I render the partial view into a div with id="myform"
Anyone knows why?
Thanks
It seems you're replacing your entire form in the AJAX callback. When you do that, you're also killing any attached event handlers. If you need the event handler to persist, you need to delegate it to a parent element that remains on the page after the replacement. You are using jQuery's delegate handler function, but your delegate itself is being replaced. You either need to not replace the entire form and just replace some child inside, or use a higher parent element than your form.

fetch data from SQL and populate dynamicaly on html

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.

Multiple data objects in Ractive template

I am in the middle of the development of a standalone widget in jQuery and RactiveJS template. Initially the widget is opened with dynamic input form elements and these elements are populated with AJAX call. Here the email is a static field. This is the initial view for the user. When a user clicks on a button in the widget, it will validate the form and send another AJAX-POST call with validated data and show the response of the request on a div inside the widget template itself. If the POST call fails, some error message should be displayed in the same div. I have successfully implemented the initial view of the widget and validation. Below is my code:
Template
<div> <!-- all the mustache {{}} variables are coming from the loadData() ajax call -->
{{#partial widget-header}}
<header>
<div >
<img alt="logo"><span>{{clientID}}</span>
</div>
</header>
{{/partial}} {{>widget-header}}
<section>
<div>
<div>
<form>
<span>Complete required fields </span> {{#partial mandatory}}
<em>*</em> {{/partial}}
{{#each items}}
<div>
<div>
<label>{{dynamicField}}</label>{{>mandatory}}</div>
<div>
<input type="text" name="{{dynamicField}}" maxlength="20">
<div>{{dynamicFieldHelp}}</div>
</div>
</div>
{{/each}}
<div >
<div>
<label>Your Email Id</label>{{>mandatory}}
</div>
<div >
<input type="text" name="email">
<div>enter your email</div>
</div>
</div>
<div >
<input type="button" value="Submit Form" on-click="formValidate">
</div>
</form>
</div>
</div>
</section>
</div>
JavaScript
this.ractive = new Ractive({
el: 'widgetContent',
template: mainTemplate,
data: function loadData() {
$.ajax({
async: false,
url: "https://example.com/xyz/" +employeeNo,
success: function (response) {
initialData = response.payload[0];
}
});
return initialData; // return the dynamic form elements in data field.
},
oncomplete: function () {
self.center();
}
});
this.ractive.on({
formValidate: function (ev) {
validate the form and send AJAX-POST call then display the response data in a div -
this is where I am stuck..
},
});
But the problem I am facing here in the second AJAX-POST call. I am not able to use a second data field in the ractive initialization. How can I implement this part ? If I use a second data field in the ractive, it will not call the first AJAX call for displaying the form elements. So my understanding is like only one data field can be added in the ractive initialization.
Do I need to use any advanced ractive concepts such as components to implement this part? Can someone help me on this.
note:- I haven't added divs for result handling in the template since I am stuck
You don't want two data members; what you want is for your data to contain a separate field for the response data. Based on what you have, data should initially be something like:
{
items: [],
response: 0
}
I would add an oninit function where you do the initial AJAX call, then when you get the response do ractive.set("items", items) to set it. Using set will cause Ractive to automatically update the view with your new items.
Next, in your formValidate function, make your AJAX call. When the response comes back, again use set to notify Ractive of the change: ractive.set("response", response). Add your div to the template:
{{#response}}
<div>{{response}}</div>
{{/}}

Comparing form input to JSON object

I have a popup modal that displays on page load that has the following form in it:
<form class="enterForm">
<label class="modalFields" id="userName" style="display: none;">
<span>user Number :</span>
<input type="text" name="userNum" placeholder="User Number" required/>
</label>
</form>
<label>
<span> </span>
<input type="submit" value="Submit" class="submitButton">
<input type="hidden" id="hiddenInput">
</label>
And on user submission of the form, I want to hit a certain API via an AJAX call, which returns a JSON that looks like:
{
"results":[
{
"person":{
"firstName":"John",
"lastName":"Smith"
},
"userNumber":"12345"
}
]
}
If the userNumber matches the value that the user submitted, I then want to update the nav bar to say the person's first name. In terms of process flow I want it to go: user types in user number -> submits form -> AJAX call hits API -> checks to see if user input matches userNumber value in JSON --> if match, selects the firstName value and updates it in the nav bar. How could I go about achieving this?
Considering you know how to do AJAX calls and you're using an API, integrating jQuery to facilitate the thing shouldn't be too hard (if it is, I included additional information after the solution).
Solution
JavaScript
//On form submit
$('#enterForm').submit(function(){
var userNum = $('[name="userNum"]').val();
//AJAX call to your API
$.ajax({
url: 'myAPICall.php',
/* data: {userNumber: userNum}, //If necessary */
success: function(data) {
// Note: this code is only executed when the AJAX call is successful.
if(data.results.userNumber == userNum){
$('#navBarFirstName').text(data.results.person.firstName);
}
},
error: function (err) {
//If the AJAX call fails, this will be executed.
console.error(err);
}
dataType: 'JSON'
});
return false; //Prevents the page refresh if an action is already set on the form.
});
Explanation
You use jQuery to bind a function (event listener) to the submit event of your form.
When the submit event is triggered, the function runs:
It gets the value of your DOMElement with the name attribute "userNum"
It makes an AJAX call to your API (with/without the userNum value, you choose if you want to check that on the server side or not)
On success, (when the call is done successfully), it updates the navbar content using .text() with the firstName attribute of your JSON response.
Including jQuery
You can integrate jQuery by including the script within your HTML page. You can either download it or use a CDN:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js">
/* Don't put your code in here it won't be parsed */
</script>
<!-- the following tag could also be <script src="link/to/your/script.js"></script> -->
<script>
/* Your actual script */
</script>
Make sure to put this line before your actual javascript file containing the script written above, otherwise jQuery won't be initialized and the script won't work.

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.

Categories