Get two value inputs in javascript - javascript

I'm creating a "real-time" checker which checks the input the user has given to check if it's already available on the database (e.g. username, phone number)
the input box:
<input type = "text" name = "user_username" placeholder="Username" onkeyup="chkstudidnumber(this.value)" autocomplete="off" required/><br/>
<div id = "msg"></div>
the javascript:
<script>
function chkstudidnumber(val)
{
$.ajax ({
type:"POST",
url:"check_username.php",
data:'username='+val,
success: function(data){
$("#msg").html(data);
}
});
}
</script>
and finally the php file:
<?php
include("dev_connection.php");
$g_username = htmlentities($_POST['username']);
$stud_username = mysqli_escape_string($con,$g_username);
$sql = "SELECT * FROM users WHERE username = '$stud_username' LIMIT 1 ";
$result = mysqli_query($con,$sql);
$count = mysqli_num_rows($result);
if($count==1) {
echo "<div id = 'msg_error'>";
echo "<img src = './img/img_error.png' style='height:20px;width:20px;vertical-align:middle;'> ";
echo " that username is already registered<br/>";
echo " if you forgot your password, please contact us";
echo "</div>";
} else {
echo "<div id = 'msg'>";
echo "<img src = './img/img_check2.png' style='height:10px;width:10px;'> ";
echo "username available";
echo "</div>";
}
?>
Now, I want to do this on my firstname and lastname input box
<input type = "text" name = "user_firstname" placeholder="Firstname"autocomplete="off" required/>
<input type = "text" name = "user_lastname" placeholder="Lastname"autocomplete="off" required/>
How can I apply the same javascript (or create a new one) to combine the two inputs into something like check_name.php?fname=samplename&lname=samplelastname

Change your function so that it can accept more then one params like:
function chkstudidnumber(val1, val2)
{
$.ajax ({
type:"POST",
url:"check_username.php",
data: {
'fname' : val1,
'lname' : val2
},
success: function(data){
$("#msg").html(data);
}
});
}

Simple use $('form').serialize() in ajax data function to get all the form input's on php page so that you can have all input's like username, first name, last name and all.
Try This:
<script>
function chkstudidnumber(val)
{
$.ajax ({
type:"POST",
url:"check_username.php",
data:$('form').serialize(),
success: function(data){
$("#msg").html(data);
}
});
}
</script>
If you have multiple form on the page then you can also provide class or id to the form and use that with serialize function to post that form data only.

<script>
function chkstudidnumber()
{
var firstName = $("input[name=user_firstname]").val();
var lastName = $("input[name=user_lastname]").val();
$.ajax ({
type:"POST",
url:"check_username.php",
data:'username='+firstName+'lastname='+lastName,
success: function(data){
$("#msg").html(data);
}
});
}
</script>
<input type = "text" name = "user_firstname" placeholder="Firstname"autocomplete="off" required/>
<input type = "text" name = "user_lastname" placeholder="Lastname"autocomplete="off" required onkeyup="chkstudidnumber()" />

Related

Not able to submit form using ajax, php and jquery

I am trying to submit a form using ajax. In the backend part, i am trying to print the values of "fname", "location" and "image" in order to check if the data is reaching there or not
But when I am trying to do console.log to check for response, I get the following message
for dataString
filename=girl.jpgfname=johnlocation=Richmond, Virginia
for fname
Severity: Notice Message: Undefined index: fname
for image
No response
I am not able to fetch the data at the backend, can anyone please help me with this
Form
<form class="form-inline" id="form_add" enctype="multipart/form-data">
<input type="file" id="file-input" name="file-input" accept="image/*" >
<input type="text" class="form-control name" id="fname" placeholder="First Name" >
<select class="location" id="location" >
<option value="">Location</option>
<?php foreach($location as $loc): ?>
<option value="<?php echo $loc->city.', '.$loc->state;?>" ><?php echo $loc->city.', '.$loc->state;?></option>
<?php endforeach; ?>
</select>
<button type="submit" class="save_btn" id="submit" > <img src="save.png" class="Save"> </button>
</form>
Script
<script>
$("#submit").click(function()
{
event.preventDefault();
var filename = $('input[type=file]').val().replace(/C:\\fakepath\\/i, '');
var fname = $("#fname").val();
var location = $("#location").val();
var dataString = 'filename='+ filename + 'fname='+ fname + 'location='+ location;
if(filename != "" || fname != "" || location != "")
{
$.ajax({
type: "POST",
url: "Data/add_data",
data: dataString,
cache: false,
success: function(result){
console.log(result);
console.log(dataString);
}});
}
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
On backend
$config['upload_path'] = './assets/client_img/.';
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = 1024 * 8;
$config['encrypt_name'] = TRUE;
$this->load->library('upload', $config);
$data = $this->upload->data();
echo $img_name = $data['file-input'];
echo $_POST['fname'];
The selected values in the form was:
name of the file = girl.jpg
first name(fname) = John
value i had select from location dropdown = Richmond, Virginia
{
$.ajax({
type: "POST",
url: "Data/add_data",
data: {
filename : filename,
fname:fname,
location:location
},
cache: false,
success: function(result){
console.log(result);
console.log(dataString);
}});
}
for image only keep this
var filename = $('input[type=file]').val()
as codeignitor will show only the name in controller, no need to replace or ci wont be able to figure the path
the problem lies in your
dataString
you can do this:
var dataString='filename=' + filename + '|fname=' + fname + '|location=' + location;
so when you receive dataString in the backend (php) , you can split the dataString using:
$dataString=explode('|', $dataReceived);
so you can get each part by doing this:
$filename=$dataString[0];
$fname=$dataString[1];
$location=$dataString[2];
hope it helps
Your dataString must be a JavaScript Object.
var data = {filename: filename, fname: fname, location: location};

jQuery code is stopping the products from being inserted into the database

When I include the $.post jQuery code, the product info does not get inserted into the database. However, when I remove the $.post jQuery code, the products are successfully inserted into the database.Please help.
index.html
<html>
<body>
<h1>Enter Product Details</h1>
<form id = "product_form" method = "post" action = "insert.php">
<input type = "text" id = "n" name = "productname" placeholder = "Product name"></br>
<input type = "text" id = "b" name = "brandname" placeholder = "Brand name"></br>
<input type = "number" id = "q" name = "quantity" placeholder = "Quantity"></br>
<button id = "save_button">Save information</button>
</form>
<p id = "result"></p>
<button id = "btn">Test Button</button>
<script type = "text/javascript" src = "js/jquery.js"></script>
<script type = "text/javascript" src = "js/script.js"></script>
</body>
</html>
insert.php
<?php
$name = $_POST['productname']; //'productname' is from html input
$brand = $_POST['brandname']; //'brandname' is from html input
$quantity = $_POST['quantity']; //'quantity' is from html input
$con = new mysqli ('localhost', 'root', '', 'tutorial');
if ($con -> connect_error) {
echo 'database connect error';
}
//Prepare statement to insert into database
$stmt = $con -> prepare ("INSERT into products(name, brand, quantity) VALUES (?, ?, ?)");
// Bind the variables to the values
$stmt -> bind_param ("ssi", $name, $brand, $quantity);
//Execute
if($stmt -> execute()){
echo "success";
}
else {
echo "failure";
}
?>
script.js
$(document).ready(function(){
$('#btn').click(function(){
alert();
});
//The problem code!!!!
$('#product_form').submit(function(event){
event.preventDefault();
$.post(
'insert.php',
{
productname:$("#n").val(),
brandname:$("#b").val(),
value:$("#q").val(),
},
function(result){
if(result == "success"){
$("#result").html("Values inserted successfully!");
}
else{
$("#result").html("Error!");
}
}
);
});
});
In the second parameter to $.post you set the data to send to the server, you have
{
productname:$("#n").val(),
brandname:$("#b").val(),
value:$("#q").val()
}
So you need to change value: to quantity:, in order to have the ajax submission match what the traditional form submit would produce.

Passing javascript value to php and back

I am having some trouble with passing a javascript value to php and back.
The idea is that I have a form where a user fills out a postal code and is then (onBlur) presented with the correct street and city in two different input fields. The street and city are collected by POST method from an external php file (getAddress.php).
I know that the php script returns the correct values and the complete() function is called onBlur, but I don't know whether the value gets passed onto the php script and back.
Javascript
<script language="javascript">
function complete() {
var postalCode = document.getElementsByName("postalCode")[0].value;
if(postalCode.length === 6) {
var dataString = "postalCode=" + postalCode;
$.ajax({
type: "POST",
url: "getAddress.php",
dataType: "html",
data: dataString,
success: function(results) {
var json = JSON.parse(results);
document.getElementById("street").value = json.street;
document.getElementById("city").value = json.city;
}
});
}
}
</script>
getAddress.php
<?php
$postalCode = $_POST['postalCode'];
$postalCode = substr_replace($postalCode, ' ', 4, 0);
$sql = 'SELECT * FROM postalCodes WHERE postalCode="'.$postalCode.'"';
$res = $con->query($sql);
$res->data_seek(0);
while($row = $res->fetch_assoc()) {
$ID = $row['ID'];
$street = $row['street'];
$city = $row['city'];
$results[] = array('ID' => $ID, 'street' => $street, 'city' => $city);
}
echo json_encode($results);
?>
HTML
<input name="postalCode" type="text" maxlength="6" onBlur="complete()" /><br />
<input name="street" id="street" type="text" disabled /><br />
<input name="number" type="text" maxlength="6" /><br />
<input name="city" id="city" type="text" disabled /><br />
Change dataType: "html", to dataType: "json", and your $results is array so you need to use index
Try this:
function complete() {
var postalCode = document.getElementsByName("postalCode")[0].value;
if (postalCode.length === 6) {
var dataString = "postalCode=" + postalCode;
$.ajax({
type: "POST",
url: "getAddress.php",
dataType: "json",
data: dataString,
success: function(results) {
document.getElementById("street").value = results[0].street;
document.getElementById("city").value = results[0].city;
}
});
}
}
As you are getting 500 internal server error message one of the reason can be that
$con->query($sql) is failing, make sure $con is initialized and table and field name are correct.

How to get input tag id of html form?

<?php
$i = 1;
$query1 = mysql_query("SELECT * FROM `alert_history` ORDER BY `alert_history`.`id` DESC LIMIT ".$start.",".$per_page."");
while($result = mysql_fetch_array($query1)){
echo '<td colspan = "2"><form method = "POST" onsubmit = "submitform()" ><textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" id = "comment'.$i.'" name = "comment"></textarea> <br />';
echo '<input type = "text" id = "alertid'.$i.'" name = "alertid" value = "'.$result['id'].'">';
echo '<input type = "submit" name = "submit" value = "Comment" ></form></td>';
$i++;
}
?>
<script>
function submitform(){
var comment = $("#comment").val();
var alertid = $("#alertid").val();
alert(comment);
$.ajax({
type: "POST",
url: "analytic.php",
data:{cmt:comment,alert_id:alertid}
});
//return false;
}
</script>
How to get textarea tag and input tag id for javascript function ?
Both tag show in while loop so i want every textarea and input tag has different id.
If you generate dynamic id in text box that time if change something in text box that time store it's id in local variable and use it on in your code
<input type = "text" class="textBox" id = "alertid'.$i.'" name = "alertid" value = "'.$result['id'].'">';
var Id
$(document).on('change', "input.textBox", function () {
Id = $(this).attr("id");
alert(Id )
});
Hope this code can help you..
In jQuery, select the tag and use the .each():
$("textarea").each(function(){
alert($(this).attr("id"));
alert($(this).val());
});
$("input").each(function(){
alert($(this).attr("id"));
alert($(this).val());
});
Demo here (Client side).
so first you set the different IDs and then you fetch it.
var textAreaId = $('textarea').prop('id);
var inputId = $('input').prop('id);
Update
$i is constant for every single set of textarea and input combined together.
If you want to grab every set of textarea and input, you should rather assign the ID to instead of doing it for every textarea and input element.
<?php
$i = 1;
$query1 = mysql_query("SELECT * FROM `alert_history` ORDER BY `alert_history`.`id` DESC LIMIT ".$start.",".$per_page."");
while($result = mysql_fetch_array($query1)){
echo '<td colspan ="2" id='.$i.'"><form method = "POST" onsubmit = "submitform()" ><textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" name = "comment"></textarea> <br />';
echo '<input type = "text" name = "alertid" value = "'.$result['id'].'">';
echo '<input type = "submit" name = "submit" value = "Comment" ></form></td>';
$i++;
}
?>
<script>
function submitform(){
var comment = $(this).closest('td').find('textarea').val();
var alertid = $(this).parent().prop('id');
alert(comment);
$.ajax({
type: "POST",
url: "analytic.php",
data:{cmt:comment,alert_id:alertid}
});
//return false;
}
</script>
Try this one:
(See JsFiddle working demo)
<?php
$i = 1;
$query1 = mysql_query("SELECT * FROM `alert_history` ORDER BY `alert_history`.`id` DESC LIMIT ".$start.",".$per_page."");
while($result = mysql_fetch_array($query1)){
echo '<td colspan = "2"><form method = "POST" onsubmit = "submitform(this)" ><textarea onFocus = "myFunction(1)" onBlur = "myFunction(0)" id = "comment'.$i.'" name = "comment"></textarea> <br />';
echo '<input type = "text" id = "alertid'.$i.'" name = "alertid" value = "'.$result['id'].'">';
echo '<input type = "submit" name = "submit" value = "Comment" ></form></td>';
$i++;
}
?>
<script>
function submitform(form){
var comment = $(form).find("textarea").val();
alert(comment);
var alertid = $(form).find("input[name=alertid]").attr("id");
alert(alertid);
//Or if you mean:
var alertid = $(form).find("input[name=alertid]").val();
alert(alertid);
$.ajax({
type: "POST",
url: "analytic.php",
data:{cmt:comment,alert_id:alertid}
});
//return false;
}
</script>

is there a way to populate other textbox when onchange?

here's my code. I'm new to php. so sorry in advance.
I actually want to check my input in txtbarcode and if it is existing in my database I would like to populate the txtdescription but I don't know how to do it or is it even possible?
<?php
$barcode = $_POST['txtbarcode'];
$query = "SELECT * FROM product WHERE product_id = '$barcode'";
$query_exe = mysql_query($query);
$chk_query = mysql_num_rows($query_exe);
if($chk_query > 0)
{
$row = mysql_fetch_assoc($query_exe);
?>
<th class = "textbox"><input type = "text" name = "txtbarcode" value = "<?php echo $row['product_id']; ?>" style="width:80px"/></th>
<th class = "textbox"><input type = "text" name = "txtdescription" value = "<?php echo $row['product_name']; ?>" style="width:100px"/></th>
<?php
}
?>
You can do this using JQuery Ajax. Just using the change listener on the barcode field, it will send an ajax call to the check_barcode file - which will query the table and echo the data you want. The result will then be placed into the other textfield via JavaScript :).
The following is a separate PHP file.
<?php
//-----------------------------------
//check_barcode.php file
//-----------------------------------
if (isset($_POST['barcode'])) {
$query = mysql_query("SELECT * FROM product WHERE barcode = '".$_POST['barcode']."'");
$num_rows = mysql_num_rows($query);
if ($num_rows > 0) {
$row = mysql_fetch_assoc($query);
echo $row['product_name'];
}
}
?>
The following is your HTML and JavaScript code.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#txtbarcode').change(function() {
var barcode = $(this).val();
$.ajax({
url: 'check_barcode.php',
type: 'POST',
data: {barcode: barcode},
success: function(result) {
$('#txtdescription').val(result);
}
});
});
});
</script>
<input type="text" name="txtbarcode" id="txtbarcode" />
<input type="text" name="txtdescription" id="txtdescription" />
UPDATE: Returning more data, and populating extra fields.
You'll need you echo a json array from the php script which contains both of the values.
For example:
echo json_encode(array('product_name' => $row['product_name'], 'unit_measure' => $row['product_name']));
and then within the JavaScript
<script>
$.ajax({
url: 'check_barcode.php',
type: 'POST',
data: {barcode: barcode},
dataType: 'json',
success: function(result) {
$('#txtdescription').val(result.product_name);
$('#unitofmeasure').val(result.unit_measure);
}
});
</script>

Categories

Resources