Get javascript values to insert them into mysql database - php

The following code is used for getting two values from two textboxes , calculate the sum using javascript and display the result in third textbox. When I click the button, I just want these textbox values (both input and result) to be inserted into mysql database. I want to do this in the same page. How can I get the javascript values to php for inserting them into database? It would be great if you could help.
Thanks
Jeny
Code:
<html>
<head>
<script language="javascript">
function getText3()
{
var in1=document.getElementById('in1').value;
var in2=document.getElementById('in2').value;
var in3 = parseInt(in1, 10) + parseInt(in2, 10);
document.getElementById('in3').value=in3;
}
</script>
</head>
<body>
<form>
<table width="306" border="0">
<tr>
<td width="146">Enter A </td>
<td width="144"><input name="text" type="text" id="in1"/></td>
</tr>
<tr>
<td>Enter B </td>
<td><input name="text2" type="text" id="in2"/></td>
</tr>
<tr>
<td height="41" colspan="2"> <center>
<button type="button" onclick="getText3()"> Get calculated result</button></center> </td>
</tr>
<tr>
<td><strong>RESULT</strong></td>
<td><input name="text3" type="text" id="in3"/></td>
</tr>
<tr>
<td> </td>
<td> </td>
</tr>
</table>
</form>
</body>
</html>

For this you should use jQuery (http://jquery.com/)
Just send them to your php file like the following:
// JS:
var in1 = $('#in1').val();
var in2 = $('#in2').val();
var in3 = parseInt(in1, 10) + parseInt(in2, 10);
$('#in3').val( in3 );
$.post('file.php', { one: in1, two: in2, three: in3 }, function(data) {
alert( data );
} )
PHP file get's them as normal POST params:
// file.php
echo $_POST['one'] . " + " . $_POST['two'] . " = " . $_POST['three'];

<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script language="javascript">
function getText3()
{
var in1=document.getElementById('in1').value;
var in2=document.getElementById('in2').value;
var in3 = parseInt(in1, 10) + parseInt(in2, 10);
document.getElementById('in3').value=in3;
$.ajax({
type: "POST",
url: "your_php_file_path.php",//you can get this values from php using $_POST['n1'], $_POST['n2'] and $_POST['add']
data: { n1: in1, n2: in2, add: in3 }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>

You can Pass the JavaScript Values to a HIDDEN Value in FORM and then POST the form to the PHP Page. Below is an example of how to set hidden value.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>
</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function setPrice(el){
var prices=[30, 20, 10];
var p=el.options.selectedIndex;
el.form.elements['price'].value=prices[p];
}
</script>
</head>
<body>
<form>
<select name="category" onchange="setPrice(this);">
<option value="men">
Men
</option>
<option value="women">
Women
</option>
<option value="under18">
Under 18's
</option>
</select>
<input name="price" type="hidden" value="30">
</form>
</body>
</html>
Hope this will help you!

Related

Json Ajax result in html option

view code i have : file one to show data two select box second select box depand on the first select box value
<?php
$con=mysql_connect("localhost","root","root");
mysql_select_db("register",$con);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#category").change(function(){
var value=$("#category option:selected").val();
$.ajax({
type:'post',
url:'subcat.php',
data:{ kvalue : value },
datatype:'json',
success:function(data){
alert(data);
$("#response").html(data);
}
})
})
})
</script>
<title></title>
</head>
<body>
<form method="post">
<table>
<tr>
<td>category:</td>
<td><select id="category">
<option>Select Category</option>
<?php
$query=mysql_query("select * from category");
while($row=mysql_fetch_array($query)){
?>
<option value="<?php echo $row['category'];?>"><?php echo $row['category'];?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td>Sub cat:</td>
<td><select >
<option >dependent dropdown</option>
<option id="response"></option>
</select>
</td>
</tr>
</table>
</form>
</body>
</html>
another page for ajax call:
This page return the data in json format to first file .problem is that i have one select box there i want to get these value in my option but i m getting this value and if m going to select on then all value auto selectrd
<?php
$con=mysql_connect("localhost","root","root");
mysql_select_db("register",$con);
$val=strtolower($_POST['kvalue']);
if($val=='mobile'){
$query=mysql_query("select mobile from subcat");
while($row=mysql_fetch_array($query)){
$row[] = $r;
print json_encode($row);
echo $row['mobile']."</br>";
}
}
problem``
i want to fetch data from json in html option but i get the value but it all in selected form how can i get or select the value one which i want??
check this demo code which select option update and your your connection and query , i just set manually data for test. this is your html file
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#category").change(function () {
var value = $("#category option:selected").val();
$.ajax({
type: 'post',
url: 'subcat.php',
data: {kvalue: value},
datatype: 'json',
success: function (data) {
alert(data);
$("#response").html(data);
}
})
})
})
</script>
<title></title>
</head>
<body>
<form method="post">
<table>
<tr>
<td>category:</td>
<td><select id="category">
<option>Select Category</option>
<option value="mobile">Mobile</option>
<option value="TV">Tv</option>
<option value="Phone">Phone</option>
</select>
</td>
</tr>
<tr>
<td>Sub cat:</td>
<td>
<select id="response">
<option>dependent dropdown</option>
</select>
</td>
</tr>
</table>
</form>
</body>
</html>
and this is your subcat.php file .i set manually data for test. if you want to select depend your option data just update your query
<?php
//$con=mysql_connect("localhost","root","root");
//mysql_select_db("register",$con);
$val = strtolower($_POST['kvalue']);
if ($val == 'mobile') {
//$query=mysql_query("select mobile from subcat");
$data = array('Option1', 'Option2', 'Option3');
foreach ($data as $value => $key) {
echo '<option value="' . $value . '">' . $key . '</option>';
}
}
if you select second option value using ajax send option then update query like
//$query=mysql_query("select mobile from subcat where subcat = '$val'");
and this is my demo data so need to replace your sql data

How to add dynamic textbox (row) and save to database using PHP

I have here my Javascript code that adds dynamic textbox (row) my problem is how can I save the values from the dynamic textbox to database using PHP script? Hope you can help me guys.. Thanks!
<script type="text/JavaScript">
function addRow(r){
var root = r.parentNode;//the root
var allRows = root.getElementsByTagName('tr');//the rows' collection
var cRow = allRows[0].cloneNode(true)//the clone of the 1st row
var cInp = cRow.getElementsByTagName('input');//the inputs' collection of the 1st row
for(var i=0;i<cInp.length;i++){//changes the inputs' names (indexes the names)
cInp[i].setAttribute('name',cInp[i].getAttribute('name')+'_'+(allRows.length+1))
}
root.appendChild(cRow);
}
function shownames(){
var allInp=document.getElementsByTagName('input');
for(var i=0;i<allInp.length;i++){
alert(allInp[i].name)
}
}
</script>
My HTML code:
<form method="POST" action="#"> <table width="1024" border="0" cellspacing="6" cellpadding="0"> <tr>
<td width="195"><div class="user"><input type="text" name="user_a" id="user" tabindex="6"/></div></td>
<td width="410"><div class="reported"><input type="text" name="user_b" id="reported" tabindex="7"/></div></td>
<td width="399"><div class="reported"><input type="text" name="user_c" id="reported" tabindex="8"/></div></td>
<td width="10"><input name="button" type="button" value="+" onclick="addRow(this.parentNode.parentNode)"></td> </tr> </table> </form>
You have to use just name of the text box which is added by dynamically.
$('form').submit(function() {
var data=($(this).serialize());
return false;
});
This function get all the elements value and create one string which is store in data, now data will pass in ajax call.
$('form').submit(function() {
var data=($(this).serialize());
$.ajax({
type: "POST",
url: "your_some.php",
data: data,
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
<html>
<head>
<title>Dynamic Form</title>
<script language="javascript">
<?php $i = 1; ?>
function changeIt()
{
//alert(i);
//var i = 1;
my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext[<?php echo $i;?>]'><input type='text' name='mytext[<?php echo $i+1;?>]'><input type='text' name='mytext[<?php echo $i+2;?>]'><br>";
<?php $i = $i+3; ?>
}
</script>
</head>
<body>
<form name="form" action="http://localhost/try.php" method="post">
<!--<input type="text" name=t1>-->
<input type="button" value="test" onClick="changeIt()">
<div id="my_div"></div>
<p class="submit"><button type="submit">Register</button></p>
</body>
try.php(this is the file where you will be catching values and then inserting into sql
)
<?php
$var = $_POST['mytext'];
echo $var[1].$var[2];
?>

PHP post using ajax and appending response inside DIV

I'm playing around with Ajax, jQuery and PHP in an attempt to get familiar with the combination of them and how they integrate with each other. Here's my 1st attempt, it's a very simple form submission that does nothing special, just trying to see how ajax handles requests and responses.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-7">
<title>My 1st AJAX attempt</title>
<link href="http://www.ht-webcreations.com/test/styles.css" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#wait').hide();
$("#emailContactus").submit(function(){
$('#wait').show(),
$.ajax({
data: $(this).serialize(),
type: "POST",
url: 'includes/ajax.php?action=emailContactus',
success: function(data) {
console.log("Success posting emailContactus"),
$('#wait').hide(),
$('#notifications').html(data).addClass('ajaxsuccess').show();
},
error: function (xhr, textStatus, errorThrown) {
console.log("Success posting emailContactus: "+ textStatus, errorThrown);
},
complete: function(data){
$('#wait').hide(),
$('#notifications').html(data).addClass('ajaxsuccess').show();
}
});
return false;
});
});
</script>
</head>
<body>
<div id="wait"><img src="http://www.ht-webcreations.com/test/loading_ajax.gif" width="80" height="80"></div>
<div id="notifications"></div>
<form name="emailContactus" id="emailContactus" method="post">
<table width="500" border="0" align="center" cellpadding="5" cellspacing="0">
<tr>
<td>name</td>
<td><label for="name"></label>
<input type="text" name="name" id="name"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="button" id="button" value="Submit"></td>
</tr>
</table>
</form>
</body>
</html>
ajax.php:
<?
///////////////// AJAX REQUESTS /////////////////
switch($_REQUEST['action']){
case('emailContactus'): if($_POST['name']=='a') { echo $value = 'User is A'; } else { echo $value = 'User is NOT A'; }
break;
case('addContact'): echo 'Contact added!';
break;
default: break;
}
?>
The problem in this simple example (working demo here) is that though I expect the data response to be appended to the #notifications div, instead it's being outputted to the very top of the document, even before any HTML has been loaded. Please have a look and suggest what needs to be changed. Also, I will be glad to hear all your comments on my code as I would like to be pointed to the right direction from the start. Thanks!

jQuery .html() method does not update the HTML data

I am trying to update the database using jquery and ajax. A pop up window is opened for updating the fields. My problem is : the database is udapted fine but the values are not reflected on the web page without refreshing the page. I am using jquery .html() method to update the contents.
Please help me with the problem.
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>
<script type='text/javascript' src="js/jquery-1.5.1.min.js"></script>
<script type='text/javascript' src="js/jquery-ui-1.8.13.custom.min.js"></script>
<link rel='stylesheet' href="js/jquery-ui-1.8.13.custom.css" />
<script type='text/javascript'>
$(document).ready(function() {
$update_dialog = $("#update_dialog").dialog({
autoOpen:false,
title:"Update Sub Sub Section",
width: '600px',
modal:true,
buttons:[
{text: "Submit", click: function() { $('form',$(this)).submit(); }},
{text: "Cancel", click: function() { $(this).dialog("close"); }},
]
});
$("#update_dialog form").submit(function() {
var form = $(this);
alert($(this).serialize());
$.post($(this).attr('action'), $(this).serialize(),function(data) {
var getbook = $('#book_'+data.id);
$('.description',getbook).empty().html(data.description);
$("#update_dialog").dialog('close');
},'json');
return false;
});
function edit3_link_action() {
var getbook = $(this).closest('.book');
//get id from div
var id = getbook.attr('id').split('_');
id = id[id.length-1];
$('#update_dialog input[name="id"]').val(id);
$('#update_dialog textarea[name="description"]').val($('.description',getbook).html());
$update_dialog.dialog('open');
return false;
}
$(".edit3").click(edit3_link_action);
});
</script>
</head>
<body>
<div align="center">
<form name="userform" method="post">
<?php
$proposalid='P09-001';
$res=mysql_query("Select * from tblproposaldocsections where ProposalID='$proposalid' order by SortOrder;");
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_row($res);
if($row[1]!=$row[2])
{
$result=mysql_query("Select * from tblproposaldocsubsections where ProposalID='$proposalid' and InsertOrder='$row[1]' order by SortOrder;");
for($k=0;$k<mysql_num_rows($result);$k++)
{
$row1=mysql_fetch_row($result);
$exp=explode('.',$row1[2]);
$alter=$row[2].'.'.$exp[1].'.'.$exp[2];
$result1=mysql_query("Select * from tblproposaldocsubsections where ProposalID='$proposalid' and InsertOrder='$row1[2]' order by OrderID;");
$lastsortorder= mysql_query("SELECT Max(SortOrder) FROM tblproposaldocsubsections where ProposalID='$proposalid' and InsertOrder='$row1[1]';")or die(mysql_error());
$rr = mysql_fetch_row($lastsortorder);
$lastsortorder = $rr[0];
if(mysql_num_rows($result1)>0)
{
?>
<br>
<?php
for($j=0;$j<mysql_num_rows($result1);$j++)
{
$row2=mysql_fetch_row($result1);
$exp=explode('.',$row2[2]);
$alter=$row[2].'.'.$exp[1].'.'.$exp[2].'.'.$exp[3];
$lastsortorder= mysql_query("SELECT Max(SortOrder) FROM tblproposaldocsubsections where ProposalID='$proposalid' and InsertOrder='$row2[1]';")or die(mysql_error());
$rr = mysql_fetch_row($lastsortorder);
$lastsortorder = $rr[0];
?>
<div class='book' id='book_<?php echo $row2[2];?>'>
<h3 class="title"><?php echo $alter;?> subsubsection_<?php echo $row2[2];?></h3>
<p class='description'><?php echo $row2[3];?></p>
<a class="edit3" href="#">Edit</a>
</div>
<br>
<?php
}
?>
<br>
<?php
}
}
}
echo('<br>');
}
?>
</table>
</form>
</div>
<div id='update_dialog'>
<form action='edit.php' method='post'>
<table>
<tr>
<td align="left">Description:</td>
<td>
<textarea name='description' cols='60' rows='5'></textarea>
</td>
</tr>
</table>
<input type='hidden' name='id' />
<input type='hidden' name='proposalid' value="<?php echo $proposalid;?>" />
</form>
</div>
</body>
</html>
EDIT by blasteralfred
I used FireBug for debugging and the problem was the same as expected. DOM object is unable to read updated data. Is this declaration for getting the DOM element correct? This is the only problem !
var getbook = $('#book_'+data.id);
This is how the tag is declared:
<div class='book' id='book_<?php echo $row2[2];?>'>
<table width="80%" align="left">
<tr>
<td width="10%"><?php echo $alter;?></td>
<td width="70%" class="description"><?php echo $row2[3];?></td>
<td width="10%" align="center"><a class="edit" href="#">Edit</a></td>
</tr>
</table>
</div>
If your .html() isn't working, its either because the element you're using it on isn't there or the value you're trying to set isn't defined.
You can figure out what's up by checking if the given element and the value are defined prior to the .html() call. I'd recommend FireBug for debugging, but this can also be done simply by alert()ing the element and the value..

jQuery, update the right field

I am building an invoice system, where I will use jQuery, to update fields.
I was thinking to pull the price, and description for the number (if available), and put them into the textfields, thus making it easy to change, if there should be some 'at-the-counter' adjustments to the invoice.
The html code looks like this:
<table>
<tr class="item-row">
<td class="partNumber"><input type="text" name="partNo"></input></td>
<td class="description"><input type="text" name="description"></input></td>
<td class="price"><input type="text" name="price"></input></td>
</tr>
</table>
The jQuery code, which is the part I am not so familiar with, looks like this:
$(document).ready(function() {
$(".partNo").keyup(getInfo);
});
function getInfo(){
var row = $(this).parents('.item-row');
var partNo = row.find(".partNo").val();
row.find(".description input")
.load("script.php", {vorunr: $(".partNo").val(), type: "desc"});
row.find(".price input")
.load("script.php", {vorunr: $(".partNo").val(), type: "price"});
}
This code works fine, the file script.php returns the values from the database.
My problem is that, all my table rows are updated, when I edit the first partNumber input field.
Can someone help me out?
you are using the selector ".partNo" many times but I see no html dom element with a class of "partNo". I see a input field with the name "partNo".
so bind the keyup event to
$('input[name="partNo"]').keyup(getInfo);
Also, here is my suggested solution for your getInfo function...
function getInfo(){
var row = $(this).parents('.item-row');
var partNo = $(this).val();
row.find(".description input")
.load("script.php", {vorunr: partNo, type: "desc"});
row.find(".price input")
.load("script.php", {vorunr: partNo, type: "price"});
}
Try using .closest() instead of .parents(). Also, you don't have a class named "partNo", just an input under the td with class "partNumber" (maybe try $('.partNumber input').keyup(...);
Also, you may want to look into json_encode and populate the fields with a single query to script.php instead of a couple of loads. You could do:
script.php
<?php
$partNo = $_GET['vorunr'];
// perform query to gather the data and populate $dbrow
header('Content-Type: application/json'); // make sure browser knows what it is
echo json_encode(Array(
'desc' => $dbrow['description'],
'price' => $dbrow['price']
));
?>
then use something like
$('.partNumber input').keyup(function(){
var row = $(this).closest('.item-row');
var partNumber = $(this).val();
$.getJSON('<?php echo $_SERVER['PHP_SELF']; ?>',{vorunr:partNumber},function(data,textStatus,xhr){
$('.description input',row).val(data.desc);
$('.price input',row).val(data.price);
});
});
EDITv2
Here's a sample (Self-sufficient) file you can run and see what I mean.
<?php
// handle the ajax query
if (isset($_GET['vorunr'])) // make sure you validate this variable; I'm not doing so for the sake of demo.
{
header('Content-Type: application/json');
echo json_encode(Array(
'desc' => $_GET['vorunr'],
'price' => sprintf('%0.2f',rand(100,99999)/100)
));
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<title>Ajax Sample</title>
<!-- MAKE SURE YOU DON'T USE THIS REFERENCE IN PRODUCTION -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="Text/javascript">
$(document).ready(function(){
$('.partNumber input').keyup(function(){
var row = $(this).closest('.item-row');
var partNumber = $(this).val();
$.getJSON('<?php echo $_SERVER['PHP_SELF']; ?>',{vorunr:partNumber},function(data,textStatus,xhr){
$('.description input',row).val(data.desc);
$('.price input',row).val(data.price);
});
});
});
</script>
</head>
<body>
<table>
<tr class="item-row">
<td class="partNumber"><input type="text" name="partNo"></input></td>
<td class="description"><input type="text" name="description"></input></td>
<td class="price"><input type="text" name="price"></input></td>
</tr>
<tr class="item-row">
<td class="partNumber"><input type="text" name="partNo"></input></td>
<td class="description"><input type="text" name="description"></input></td>
<td class="price"><input type="text" name="price"></input></td>
</tr>
<tr class="item-row">
<td class="partNumber"><input type="text" name="partNo"></input></td>
<td class="description"><input type="text" name="description"></input></td>
<td class="price"><input type="text" name="price"></input></td>
</tr>
</table>
</body>
</html>

Categories