AJAX query to DB onchange, before form submit - javascript

I have a user setup/create form that includes requesting a users license/certification number as part of the user setup process. However, i need the license information entered to be validated and returned to target DIV Onchange before the full form is actually submitted normally. As I understand it, a AJAX POST would be the way to do that but I have never used AJAX. I was looking at an example on W3schools here
but it is using the value set by a single select. In my case I have 3 separate form fields that normally are sanitized and sent to a standalone PHP file thats expecting 3 variables via POST method on SUBMIT like normal.
Can someone show me example of how I could accomplish the AJAX call made by the w3schools example when i need to pass/submit 3 variables to receiving PHP processing file, using the POST method when the LAST FORM FIELD is exited (onblur)?
FORM
<div>Active license?<input name="sffl" type="checkbox" value="1">Yes | License#
<input name="dig1" type="text" size="5" maxlength="1" placeholder="5">-
<input name="dig2" type="text" size="8" maxlength="2" placeholder="12">-
<input name="dig3" type="text" size="7" maxlength="3" value="XXX" disabled>-
<input name="dig4" type="text" size="7" maxlength="2" value="XX" disabled>-
<input name="dig5" type="text" size="7" maxlength="2" value="XX" disabled>-
<input name="dig6" type="text" size="10" maxlength="5" placeholder="22131">
</div>
TARGET FOR RESPONSE
<div id="datatarget"> </div>

This is code I cut and pasted from an ajax call that checks time. It sends more than one variable to the server.
Editing again to point out that this ajax call uses jquery, which some complain about but I find it to be very simple and straightforward for ajax calls.
$("#startdate,#starttime,#enddate,#endtime" ).change(function(){
$("#date_error").show(''); //clears the error display
$("#date_error").html('...validating'); //puts a temporary value
var startdate=$("#startdate").val();
var starttime = $("#starttime").val();
var enddate=$("#enddate").val();
var endtime=$("#endtime").val();
startdate = startdate + ' ' + starttime; //combine date and time
enddate = enddate + ' ' + endtime; //combine date and time
$.post("http://www.mysite.net/contest/validate/",
{
startdate:startdate, //sends to server with post collection
enddate:enddate,
id:id
},
function(data,status) {
$("#date_error").html(data);
}); //.post
}); // keyup

The following code worked, as i understand it after a few hours of playing with it this is a combination of jquery/ajax??? in any case this was the end result that was successful:
<div>Active license?<input name="sffl" type="checkbox" value="1">Yes | License#
<input name="dig1" type="text" size="5" maxlength="1" placeholder="5">-
<input name="dig2" type="text" size="8" maxlength="2" placeholder="12">-
<input name="dig3" type="text" size="7" maxlength="3" value="XXX" disabled>-
<input name="dig4" type="text" size="7" maxlength="2" value="XX" disabled>-
<input name="dig5" type="text" size="7" maxlength="2" value="XX" disabled>-
<input name="dig6" type="text" size="10" maxlength="5" placeholder="22131">
</div>
m
$(document).ready(function() {
$("#dig6").blur(function(){
$.ajax({
type : 'POST',
url : 'test.php',
data: {
var1 : $('#dig1').val(),
var2 : $('#dig2').val(),
var3 : $('#dig6').val()
},
success:function (data) {
$("#datatarget").append(data);
} }); }); });
test.php contained:
echo $_POST["var1"].'<br>';
echo $_POST["var2"].'<br>';
echo $_POST["var3"].'<br>';

Related

Collect all values from uniq ids and pass them

So I'm having trouble with JS and how to correctly collect and pass all values from a text field and hidden field on a button click.
<input autocomplete="off" id="add_109_01000340002001010_id" name="add_109_01000340002001010[id]" type="hidden" value="113000674">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001010_name" name="add_109_01000340002001010[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
<input autocomplete="off" id="add_109_01000340002001009_id" name="add_109_01000340002001009[id]" type="hidden" value="112000674">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001009_name" name="add_109_01000340002001009[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
<input autocomplete="off" id="add_109_01000340002001021_id" name="add_109_01000340002001021[id]" type="hidden" value="11405181">
<input add_type_code="109" autocomplete="off" autocomplete_key="109" id="add_109_01000340002001021_name" name="add_109_01000340002001021[name]" onkeyup="fillFlatNumber(this)" size="3" style="height: 10px" type="text" class="ac_input">
Those are text fields and hidden fields with unique ids. They are 'connected'. When you change the value in the text field, the value in the hidden field changes automatically.
When you click on a button, then values that will be written in the text field should be processed in js
function room_group() {
$('.add').bind('click', function() {
var hidden_values = 'something here' // Let's get all values here and pass them to the get request
var values = 'something here' // Let's get all values here and pass them to the get request
$.post('/link/definition', {
val: values,
hidden_val: hidden_values
},
function(response) {
location.reload();
}
);
});
}
The question is how to collect all of those values correctly? Unfortunately, I have no idea...
It depends on how you want to format your values.
You can serialize the values by searching for them with an appropriate selector and then you can create a JSON string as value.
var hiddenValues = JSON.stringify($("input[type='hidden']").serializeArray());
var textValues = JSON.stringify($("input[type='text']").serializeArray());
console.log(hiddenValues);
console.log(textValues);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" value="h1" name="hidden1" />
<input type="hidden" value="h2" name="hidden2" />
<input type="text" value="t1" name="text1" />
<input type="text" value="t2" name="text2" />
Your POST will be something similar to:
var hiddenValues = JSON.stringify($("input[type='hidden']").serializeArray());
var textValues = JSON.stringify($("input[type='text']").serializeArray());
$.post('/link/definition', {
val: textValues,
hidden_val: hiddenValues
},
function(response) {
location.reload();
}
);

jquery and javascript obtained input value of input type equals text but it is empty even though it's not

When i try to obtain the values of input type=text is empty even though they are not. Any idea why?
var form_data = new FormData(document.getElementById('box')); // Creating object of FormData class
var cust_name = document.getElementById("cust_name").value;
var order_num = $("#order_num").val();
$("#search").click(function(){
console.log(cust_name) //they are empty even though it's not
console.log(order_num) //they are empty even though it's not
$.ajax({
url: "search.php",
method: "POST",
data: {cust_name: cust_name, order_num: order_num},
error: function (request, status, error) {
$("body").append("<div style='background:rgba(255,0,0,0.8);float:left;position:fixed'>" + request.responseText + "</div>")
}
}).done(function(msg) {
$("body").append("<div style='background:rgba(255,0,0,0.8);float:left;position:fixed'>" + msg + "</div>")
});
});
});
and here is my html code:
<form id="box" method="post">
<input type="text" id="order_num" name="order_num" placeholder="🔠Order number"/> <br/>
<input type="text" id="cust_name" name="cust_name" placeholder="🔠Customer name"/> <br/>
sent date: <input type="date" name="sent_date" id="sent_date"/><br/>
<input type="text" id="sales_person" name="sales_person" placeholder="🔠sales person"/><br/>
<input type="button" id="search" class="button" value="search" name="search"/>
</form>
You need to attach an event listener to the submit event of your form to get the values when the user submits. Here's a stripped down working example.
The problem with your code is that it runs right away when the page loads, and because JavaScript is a runtime language, it doesn't go back and update those variables with the current value.
You could also put those two variable declarations INSIDE your click handler (Shown in bottom solution).
Solution (Preferred)
document.getElementById('box').addEventListener('submit', function(e) {
e.preventDefault();
var form_data = new FormData(this);
var cust_name = document.getElementById("cust_name").value;
var order_num = document.getElementById("order_num").value;
console.log(cust_name, order_num);
});
<form id="box" method="post">
<input type="text" id="order_num" name="order_num" placeholder="🔠Order number"/> <br/>
<input type="text" id="cust_name" name="cust_name" placeholder="🔠Customer name"/> <br/>
<button type="submit">Search</button>
</form>
Notes
I used <button> instead of <input type="button">
I passed this to FormData because we have a reference to it from the event handler
I used e.preventDefault() to stop the page from refreshing by default.
Solution (Minimal Code Change)
$("#search").click(function(){
var form_data = new FormData(document.getElementById('box'));
var cust_name = document.getElementById("cust_name").value;
var order_num = $("#order_num").val();
console.log(cust_name);
console.log(order_num);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="box" method="post">
<input type="text" id="order_num" name="order_num" placeholder="🔠Order number"/> <br/>
<input type="text" id="cust_name" name="cust_name" placeholder="🔠Customer name"/> <br/>
sent date: <input type="date" name="sent_date" id="sent_date"/><br/>
<input type="text" id="sales_person" name="sales_person" placeholder="🔠sales person"/><br/>
<input type="button" id="search" class="button" value="search" name="search"/>
</form>

Jquery - Passing input values to a radio button

I am using MySQL and ajax to pull specific info from a table and then I am passing one of those values to a radio button.
User enters their ID number and it automatically adds the full name, email address and manager from the MySQL table.
I then pass the manager value to a radio button, but it's not working unless I actually click on the manager input field.
I tried, blur, change, keyup, focusin/out but its still not passing the value until I actually click on the input field.
PLEASE NOTE - it works fine if I manually add a value to the manager's field.
Any ideas?
<input type="text" name="id" id="id" value="" >
<input type="text" class="hidden" name="name" id="name" value="" >
<input type="text" class="hidden" name="email" id="email" value="" >
<input type="text" class="hidden" name="manager" id="manager" value="" >
<input type="radio" name="defaultmanager" id="defaultmanager" value="">
<label for="defaultmanager" id="defmanager" >Default manager:</label>
<input type="radio" name="reason" id="otherreason" value="">Other
<input type="text" name="otherreason" />
<script>
$('#manager').bind("change paste keyup", function() {
var val = $(this).val();
$('#defmanager').text('Default Manager:' + val);
});
</script>
Again it works fine but I have to actually click on the input field in order for the value to be passed to the radio button.
Here's the code that automatically adds the name, email and manager:
$(function() {
$( "#id" ).on( 'blur' , function() {
$('#table1 tr').removeClass("hidden");
// getting the value that user typed
searchString=$(this).val();
// forming the queryString
var data = 'telefoon='+searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "query2.php",
data: data,
success: function(html){ // this happens after we get results
result = String(html).split("|");
$("#name").val(result[0]);
$("#email").val(result[1]);
$("#manager").val(result[4]);
}
});
}
return false;
});
});
Where you are programmatically changing the value of the manager field, you need to trigger the change event:
$("#manager").val(result[4]).change();
A full, working example is here:
$('#manager').bind("change paste keyup", function() {
var val = $(this).val();
$('#defmanager').text('Default Manager:' + val);
});
//Set value of the manager field from the database here
$('#manager').val('Bob Marley').change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="id" id="id" value="" >
<input type="text" name="name" id="name" value="" >
<input type="text" name="email" id="email" value="" >
<input type="text" name="manager" id="manager" value="" >
<input type="radio" name="defaultmanager" id="defaultmanager" value="">
<label for="defaultmanager" id="defmanager" >Default manager:</label>
<input type="radio" name="reason" id="otherreason" value="">Other
<input type="text" name="otherreason" />
i guess there's a million ways to do everything. I don't know why i wasnt thinking clear. :( Here's what i ended up doing:
$(function() {
$( "#id" ).on( 'blur' , function() {
$('#table1 tr').removeClass("hidden");
// getting the value that user typed
searchString=$(this).val();
// forming the queryString
var data = 'telefoon='+searchString;
// if searchString is not empty
if(searchString) {
// ajax call
$.ajax({
type: "POST",
url: "query2.php",
data: data,
success: function(html){ // this happens after we get results
result = String(html).split("|");
$("#name").val(result[0]);
$("#email").val(result[1]);
$("#manager").val(result[4]);
$("#defmanager").val(result[4]);
}
});
}
return false;
});
});

How Do I pass a value in a input box, to another input box

I am trying to pass values between boxes.
So, When a User types inside of the first text box:
<input type="text" placeholder="Your personal message" id="valbox"></input>
<input type="submit" name="design1" id="butval" value="Choose Design"></input>
Then they click the 'choose design' button, and what they typed in, gets passed to another
input text box on the same page.
this is the second input box i want to pass it to.
<input type="text" class="input-text" name="billing_last_name" id="billing_last_name" placeholder="" value="">
Any help would be much appreciated
thank you
Live Demo
Instead of a submit type input use a button type input.
HTML
<input type="text" placeholder="Your personal message" id="valbox"></input>
<input type="button" name="design1" id="butval" value="Choose Design"></input>
<input type="text" class="input-text" name="billing_last_name" id="billing_last_name" placeholder="" value="">
JS
window.onload = function(){
document.getElementById('butval').onclick = function(){
document.getElementById('billing_last_name').value = document.getElementById('valbox').value;
}
};
First add a clicklistener for the submit button and inside that callback pass the text through the elements
document.getElementById("butval").addEventListener("click", function(event){
var text = document.getElementById("valbox").value;
document.getElementById("billing_last_name").value = text;
event.preventDefault();
return false;
});
this is by far easiest in jquery given
<input type="text" placeholder="Your personal message" id="valbox"></input>
<input type="submit" name="design1" id="butval" value="Choose Design"></input>
<input type="text" class="input-text" name="billing_last_name" id="billing_last_name" placeholder="" value="">
use a simple
$("#butval").click(function(event){
$("#billing_last_name").html("<p>"+$("#valbox").html()+"</p>");
event.preventDefault();
});
but better change type="submit" to type="button" then you can remove the essentially unnecessary line event.preventDefault();

targeting a specific form with serialize()

Following on from my previous question, which was so quickly answered by Meder it wasn't funny, there's now an additional question that's popped up in the process of making a reusable jQuery form submitted that doesn't take the user away from where they were.
Problem
The jQuery serialize() function is performing its magic on all forms within a page, and not the specific form which was submitted. Example code below.
How do I capture the form's unique name/id, and replace "form" within $("form").serialize() with the name of the target form so only that is serialised?
Form code
<form name="contact" id="contact" action="">
<input name="_recipients" type="hidden" value="joe#fake.com" />
<input name="_subject" type="hidden" value="Title" />
...
<fieldset>
<label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label><br />
<label for="email" id="email_label">Return Email</label>
<input type="text" name="email" id="email" size="30" value="" class="text-input" />
<label class="error" for="email" id="email_error">This field is required.</label><br />
<label for="phone" id="phone_label">Return Phone</label>
<input type="text" name="phone" id="phone" size="30" value="" class="text-input" />
<label class="error" for="phone" id="phone_error">This field is required.</label><br/>
<br />
<input type="submit" name="submit" class="button" id="submit_btn" value="Send your suggestion" />
</fieldset>
</form>
jQuery serialise and post
var dataString = $("form").serialize();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "/_global/assets/scripts/formmail/formmail.asp",
data: dataString,
...
var dataString = $('#contact').serialize()
If you are attaching an event handler to a button or the form's submit event then you can refer to it with this if inside the submit event handler function scope, eg
$('#contact').submit(function() {
alert( $(this).serialize() );
});
I highly recommend reading http://docs.jquery.com/Selectors
By using the "form" string as a selector, you are actually getting all the FORM elements within the page, in order to select only one form, you can:
Get the specific form by its id attribute (using the id selector):
var dataString = $("#contact").serialize();
Or by its name attribute (using the attributeEquals selector):
var dataString = $("form[name=contact]").serialize();
$("#contact").serialize()
Instead of using serialize there's a nice plugin that allows you to post your forms asynchronously. All you have to do is:
$(function() {)
$('#contact').ajaxForm();
});
Also don't forget to assign the correct action to the form, it shouldn't be empty.

Categories