Calculate total of dynamic values of readonly inputs. Jquery and AJAX - javascript

So I have my form pretty much done and I need to calculate the total values of input fields after AJAX fills them based on user selects. I have tried and tried and tried to find a solution but nothing is working... ugh.
Here's the html for the input fields that need to be calculated and the field that the sum needs to be returned to:
<input type="text" class="form-control prices" id="lt1total" placeholder="Amount" value="" readonly>
<input type="text" class="form-control prices" id="lt2total" placeholder="Amount" value="" readonly>
<input type="text" class="form-control prices" id="lt3total" placeholder="Amount" value="" readonly>
<input type="text" class="form-control disabled" id="lttotal" placeholder="Amount" value="" readonly>
Here is the AJAX request (there is one for each they all work correctly):
$.ajax({
method: 'GET',
url: 'example.url',
data: {
lt1datetype: lt1datetype,
lt1tt: lt1tt,
}
}).done(function(result) {
console.log('', result);
$('#lt1total').val(result);
});
And this is the only jquery function that I have gotten to even put a value for #lttotal :
$(document).ready(function() {
var sum = 0;
$(".prices").each(function(){
sum += Number($(this).val());
});
$("#lttotal").val(sum);
});
It only outputs 0 for the amount. The values that AJAX is getting are like this 123.00 or 1234.00 I'm stuck and aggravated. Any help or direction would be greatly appreciated.

Use $.when to run the calculations code after all the requests have been completed.
var request1 = $.ajax({
method: 'GET',
url: 'example.url',
data: {...}
}).done(function(result) {
console.log('', result);
$('#lt1total').val(result);
});
var request2 = $.ajax({
method: 'GET',
url: 'example.url',
data: {...}
}
}).done(function(result) {
console.log('', result);
$('#lt2total').val(result);
});
$.when(request1, request2....., requestn).done(function(){
// set totals here instead of on page load
})

Related

Jquery result is not coming without alert

I did a live search function Laravel 7 using jquery. I used the keyup function. I have written the code tested each and every time for the keypress the alert is working and result also coming but I stop the alert search result is coming I tried the keypress & keydown event also same issues. I don't what is the issue please help me to solve this issue.
<form id="small-search-box-form" action="{{route('MainSearchProduct')}}" method="get">
<input type="text" class="search-box-text" id="search_query" name="search" placeholder="Search store" />
<input type="submit" class="button-1 search-box-button" value="Search" />
<ul class="search-drop" id="result">
</ul>
</form>
$(document).ready(function() {
var input_search = $('#search_query');
input_search.keyup(function() {
//alert(input_search.val());
var query = input_search.val();
$.ajax({
url: "{{ route('MainSearchQuery') }}",
type: "GET",
data: {
'proSearch': query
},
success: function(data) {
$('#result').html(data);
}
}, 10000);
});
$(document).on('click', 'li', function() {
var value = $(this).text();
$('#search').val(value);
$('#result').html("");
});
});

Can't write AJAX output variable in html form

I need to print inside a span tag ("estimation2") the result of a calculation (for now, just a simple sum of the two input boxes "SHm2" and "STm2"). I'm using an AJAX call to perform that task. It seems to work perfectly until the alert, which shows the correct result, but for some reasons I can't write that result in my html form. I've been looking around and tried several things, yet none of them worked. For instance I've tried using the write method but it didn't work or stuff like $("#estimation2").html(estimation); or
document.getElementById("estimation2").innerHTML = estimation;
The only way I managed to get it written was by using window.onload, but this generates the calculation when the page loads, and I don't want that. I only want the AJAX code to be triggered when I click on my button.
Also, just for info, the calculation is made in my django view, even though I don't think it's relevant here as it looks to work properly. I'm really lost here, could you please help?
Here is my html code and the AJAX script:
<input type="text" id="SHm2" name="SHm2" maxlength="10" type="number" value="50">
<input type="text" id="STm2" name="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" onclick="calculate()">Estimation</button>
<label>Result:</label>
<span id="estimation2"></span>
<script type="text/javascript">
function calculate () {
var SHm2 = $('#SHm2').val();
var STm2 = $('#STm2').val();
$.ajax({
url: '/myApp/templates/homepage/',
type: 'POST',
data: {
'SHm2':SHm2,
'STm2':STm2,
estimation: 'estimation',
},
success: function(estimation) {
alert(estimation);
document.getElementById("estimation2").innerHTML = estimation;
}
});
}
</script>
so what you wanna do is run the JS after the HTML document has loaded, and as mentioned in the comment section you need to add type="button" to estimation button
HTML
<input type="text" id="SHm2" name="SHm2" maxlength="10" type="number" value="50">
<input type="text" id="STm2" name="STm2" maxlength="10" type="number" value="50">
<button id="estimation" name= "estimation" type="button" onclick="calculate()" >Estimation</button>
<label>Result:</label>
<span id="estimation2"></span>
JS
$(document).ready(function() {
function calculate() {
var SHm2 = $("#SHm2").val();
var STm2 = $("#STm2").val();
$.ajax({
url: "/myApp/templates/homepage/",
type: "POST",
data: {
SHm2: SHm2,
STm2: STm2,
estimation: "estimation"
},
success: function(estimation) {
console.log(estimation);
document.getElementById("estimation2").innerHTML = estimation;
}
});
}
});

Way to get data from HTML form to Microsoft Flow without a page refresh and no php

I am trying to create an HTML form that tallies who is at a sports game, and then pass that data to Microsoft Flow. I have the html form behind a JavaScripted Geofence. I want to be able to take that form data, and without a page refresh, compile it into a JSON, then pass it to Microsoft Flow, without using PHP or an inbetween step.
I have read that AJAX may help me do this, but AJAX seems to be used mostly to POST data to a PHP file. I am not entirely sure how the Flow trigger works. I am using the Flow trigger "When an HTTP Request is Received". How would I go about giving data from this form to Flow? Thank you. (to clarify the code, when the check in button is pushed, getLocation() makes the form visable).
<h4 id="loc" style="text-align:center;"></h4><br>
<h4 id="word" style="text-align:center;"></h4><br>
<div class="wow fadeInUp" data-wow-delay="0.2s" style="text-align:center;">
<form id="yummyfood" style="display:none;" action="javascript:void(0);" name="CheckIn" method="post">
<p><label for="name">First Last Name. (Use same name every time or you won't get your points.)</label>
<input type="text" name="name" id="name"></p>
<p><label for="email">School Email Address</label>
<input type="text" name="email" id="email"></p>
<p><label for="grade">What Grade are you in?</label>
<input type="text" name="grade" id="grade"></p>
<p><label for="game">Which game are you at?</label>
<input type="text" name="game" id="game"></p>
</form>
<button value="Submit" type="button" onclick="formdone()">
</div>
<!--FormScript-->
<script>
function submit(){
console.log("i win")
}
function submitform() {
console.log("one")
var form = document.getElementById("yummyfood")
var formData = JSON.stringify($("#myForm").serializeArray());
$.ajax({
type: "POST",
url: "https://prod-93.westus.logic.azure.com:443/----Fay0OuN2k",
data: formData,
success: function(formdone){},
dataType: "json",
contentType : "application/json"
console.log(formData)
});
}
function formdone() {
yummyfood.style.display = 'none'
}
</script>
I am getting nothing from this and many many variations of it. Any help is appreciated.
There are a number of syntax errors in your code sample along with orphaned methods like submit() and submitform() which will never be called resulting in the ajax code never being run.
Here is a working example derived from your code samples that you provided. It should be enough to get you going.
<form id="myForm">
<p>
<label for="name">First Last Name. (Use same name every time or you won't get your points.)</label>
<input type="text" name="name" id="name">
</p>
<p>
<label for="email">School Email Address</label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="grade">What Grade are you in?</label>
<input type="text" name="grade" id="grade">
</p>
<p>
<label for="game">Which game are you at?</label>
<input type="text" name="game" id="game">
</p>
</form>
<input id="submitButton" type="button" value="Submit">
<script>
// Bind button click event to function
$(function () {
$('#submitButton').click(submit);
});
/**
* Submits the form.
*/
function submit() {
var formData = $("#myForm").serializeArray();
var jsonData = formDataToJson(formData);
// Post data to http endpoint
$.ajax({
type: "POST",
url: "https://prod-93.westus.logic.azure.com:443/----Fay0OuN2k", // Replace with Microsoft Flow HTTP request action URL
data: jsonData,
dataType: "json",
contentType: "application/json;charset=UTF-8"
})
.done((data, textStatus, jqXHR) => {
console.log(textStatus);
})
.fail((jqXHR, textStatus, errorThrown) => {
console.log(`${textStatus}: ${errorThrown}`);
});
}
/**
* Converts form data to json.
* #param {Object} formData - The form data.
*/
function formDataToJson(formData) {
var object = {};
formData.forEach((value, key) => {
object[value.name] = value.value
});
return JSON.stringify(object);
}
</script>
Pro Tips
The HTTP request trigger in Flow is always expecting a content type header of application/json.
Set the Request Body JSON Schema of your Flow HTTP request action to match schema of the data you are sending.
{
"type": "object",
"properties": {
"name": {
"type": "string"
},
"email": {
"type": "string"
},
"grade": {
"type": "string"
},
"game": {
"type": "string"
}
}
}

Take input from html field and store it in JSON object (lots of input fields)

I am looking for a way to take input from an HTML form and store it into a JSON object for use with AJAX. I can't use the normal $('#id').val();, because, as you can see below, there are a lot of fields. Here is some sample code
Javascript/jQuery:
$(document).ready(function() {
$('.add-to-cart').click(function() {
var id = $(this).attr('id');
//var qty = $(this).attr('qty'); <- need the quantity from the field
console.log(id);
//console.log(qty);
$.ajax({
url: 'addproduct',
type: 'POST',
datazType: 'JSON',
data: {
"id": id
//"qty": qty
},
success: function(addedproduct) {
console.log(addedproduct.name);
$('#cart').append('<li>'+ addedproduct.name +'</li>');
},
error: function() {
console.log('failed to add product');
}
})
});
});
HTML:
<p class="name">{{$product->name}}</p>
<input type="number" id="qty" class="qty" name="qty">
<button type="submit" id="{{$product->id}}" class="add-to-cart">Add to cart</button>
Help me please, or at least guide me in the right direction, this HAS to happen using AJAX.
jQuery's selialize method is what you are looking for. It serializes the values of inputs in a form.
Helpful example: https://stackoverflow.com/a/6960586/4180481

not able to get input value via JS

I have a form which has two jQuery datapicker input fields, and a form button,
From: <input class="input-large" type="text" id="datepicker_from" name="datepicker_from">
To: <input class="input-large" type="text" id="datepicker_to" name="datepicker_to">
<a class="btn btn-primary" onclick="get_call_details(1, from_date, to_date )" >Check Availability</a>
What i am trying to do is get the date of both fields datepicker_from and datepicker_to and then on click of a form button call function get_call_details(1, from_date, to_date )
The problem is i am not able to get the value of both date fields
Following is how i am trying to get the date field values
$("#datepicker_from").blur(function(){
var from_date = document.getElementsByName('datepicker_from').value;
alert (from_date);
});
$("#datepicker_to").blur(function(){
var to_date = document.getElementsByName('datepicker_to').value;
alert (to_date);
});
and this is the JS function I am trying to pass the both dates to
function get_call_details(id, from_date, to_date) {
alert(id, from_date, to_date );
$('#dvloader').show();
$.ajax({
url: 'outlook_calendar.php',
type: 'POST',
data: {'userid': id},
success: function (data) {
$(this).parent("#availability").append(data);
$("#availability").html(data);
$('#dvloader').hide();
}
});
}
All i want is to get the dates of both fields and pass it to function on click of a button, But I am not able to get the dates. I will appreciate any help.
Why not just write this all into a jquery function attached to the a click event:
From: <input class="input-large" type="text" id="datepicker_from" name="datepicker_from">
To: <input class="input-large" type="text" id="datepicker_to" name="datepicker_to">
<a class="btn btn-primary" id="checkavail" >Check Availability</a>
$('#checkavail').click(function(){
var from = $("#datepicker_from").datepicker('getDate');
var to = $("#datepicker_to").datepicker('getDate');
$('#dvloader').show();
$.ajax({
url: 'outlook_calendar.php',
type: 'POST',
data: {'userid': 1, 'from':from, 'to':to},
success: function (data) {
$(this).parent("#availability").append(data);
$("#availability").html(data);
$('#dvloader').hide();
}
});
I think the better approach would be to read the to and from date inside get_call_details function.
Function get_call_details(id)
{
from_date = $("#datepicker_from").val();
to_date = $("#datepicker_to").val();
}
The getElementsByName() returns an array of result. you should use the getElementById or either use the jQuery selector $('#yourId').val().

Categories