Jquery Post doesn't work taking form class - javascript

Ive this php code in global.php to generate a table
<table>
<tbody>
<?php
for($i=1; $i<=30; $i++)
{
echo '
<tr class="adding">
<td>'.$i.'</td>
<td><input type="text" class="barcode" name="barcode[]" size="13" maxlength="13"></td>
<td><input type="text" class="prodotto" name="prodotto[]"></td>
<td><input type="text" class="prezzo" name="prezzo[]"></td>
</tr>';
}
?>
</tbody>
</table>
<script src="js/global.js"></script>
and this is my global.js file
$(document).on("blur", ".barcode", function(){
var barcode =$(this).find('input.barcode').val();
if(barcode!='')
{
$.post('ajax/barcode_prodotto.php', {name: barcode}, function(data){
$(this).find('input.prodotto').val(data);
});
}
});
and this is barcode_prodotto.php that I'm using to retrive data from DB using jquery post function as described:
<?php
mysql_connect("localhost","root","");
mysql_select_db('test');
if(isset( $_POST['name'])===true && empty($_POST['name'])===false){
$query=mysql_query("
SELECT prodotto as prodotto
FROM barcode_prodotto
WHERE barcode_prodotto='".mysql_real_escape_string(trim($_POST['name']))."'");
echo (mysql_num_rows($query)!==0)? mysql_result($query, 0, 'prodotto') : 'prodotto not found';
}
?>
It doesnt work but I'm sure that the problem is on global.js file because I the others 2 php files with id and not class and everything were ok.

Change your global js to this:get the current object in some other variable to use inside post ajax call and find the td input to place the value inside.
$(document).on("blur", ".barcode", function(){
var that=this;
var barcode =$(this).val();
// console.log(barcode);
if(barcode!='')
{
$.post('testing.php', {name: barcode}, function(data){
$(that).closest("tr").children('td').slice(2,3).find("input").val(data);
});
}
});
demo

Related

How can checkbox calls php code then get back the results to be printed in textarea?

I am developing SMS sender form. The form has three components:
Textarea for receiver numbers.
Textarea for the massage content.
checkbox which includes subscriber as receivers.
Then I was thinking that I need to go in three steps:
1- Check if the checkbox is checked.
2- Read the database for the subscriber numbers.
3- write the subscribers into receiver textarea.
What I had done was creating JavaScript function which called by the checkbox when change, then calling the php code by JavaScript function and lastly, using JavaScript inside php to append numbers into the textarea. unfortunately it didn't work. I had to research and I found that I have to use ajax to call php code.
I didn't use ajax before and I think it is difficult, I am a beginner in scripting. Also, I prefer to use this way of implementing instead of reading database after submitting the form.
I am really confused what to do. This is the first time that I need to use scripts and php inside eachothers! I need your help what is the easiest way of implementing.
New ideas and ways are welcome.
updates:
I decided to use ajax since most of you suggest.
this is form.php code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var checkbox = document.getElementById('subscribers').checked;
//Check if checkbox is checked
if (checkbox === true) {
//Read databank for Results
document.getElementById("to").value = "result should be here.";
$.ajax({
type: 'POST',
url: 'sms/readSubscriber.php',
data: {'variable': dataPhp},
complete: function(r){
var subscriberNumbers = r.responseText;
document.getElementById('to').innerHTML = subscriberNumbers;
}
});
} else {
document.getElementById("to").value = "";
}
});
function doalert() {
//Check if checkbox is checked
var checkboxElem = document.getElementById("subscribers").checked;
if (checkboxElem === true) {
//Read databank for Results
document.getElementById("to").value = "result should be here.";
$.ajax({
type: 'POST',
url: 'sms/readSubscriber.php',
data: {'variable': dataPhp},
complete: function(r){
var subscriberNumbers = r.responseText;
document.getElementById('to').innerHTML = subscriberNumbers;
}
});
} else {
document.getElementById("to").value = "";
}
}
</script>
</head>
<body>
<fieldset style="width:50%;margin:auto" dir=ltr>
<form action="" method="POST">
<table border="0" cellspacing="3" cellpadding="3">
<tr>
<td>Your Balance</td>
<td><input type="text" class="form-control" name="Balance" size="20" disabled="disabled" value="<?php
echo $Credits;
?>"></td>
</tr>
<tr>
<td>Mobile No.</td>
<td><textarea textarea class="form-control" id="to" name="Mobile" cols="30" rows="5"></textarea><br></td>
<td>
<div class="checkbox">
<label><input type="checkbox" value="subscribers" onchange="doalert()" id="subscribers" checked>Subscribers</label>
</div>
</td>
</tr>
<tr>
<td>Message</td>
<td><textarea class="form-control" name="Text" cols="30" rows="5" required></textarea></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Go" value="Send SMS" /></td>
</tr>
</table>
</form>
</fieldset>
</body>
</html>
and this is the readSubscriber.php
<?php
require_once('../db_functions.php');
// Connect to the database
$connection = db_connect();
//if connection fails, stop script execution
if (mysqli_connect_errno()) {
echo "Error: " . $sql . "Connect failed: " . mysqli_connect_error();
} else {
$query = "SELECT * FROM phoneSubscribers";
// Query the database
$result = db_isExist($query);
if ($result) {
$result = db_fetch($query);
echo json_encode($result);
} else {
echo "No result";
}
}
?>
Please update your Question with code, otherwise its hard to help.
For this you have to use Ajax & jquery.
Make sure you have jquery installed.
var checkbox = document.getElementById('checkboxInput').checked;
//Maybe you want to pass something to the PHP file?
var dataPhp = "";
//Check if checkbox is checked
if (checkbox === true) {
//Read databank for Results
$.ajax({
type: 'POST',
url: 'yourFile.php',
data: {'variable': dataPhp},
complete: function(r){
var subscriberNumbers = r.responseText;
document.getElementById('receivers').innerHTML = subscriberNumbers;
}
});
}
to get the variable you send to the php file, you just have to use
$dataFromScript = $_POST['variable'];
In yourFile.php you have to get the wanted values of the MySQL databank.
If its an array make sure to encode it with JSON.
echo json_encode($resultArray);
After that, the $resultArray variable will be displayed in your
<div id="receivers"></div>

How to update row status with jquery change() and display in respective table

I'm facing major issue in changing status of a particular row in table with <select> tag .
I'm using jquery-Ajax so, here go functionality by this when is click on <select on any particular row for Example: Lets say i have changed the status of table row of id 2 from Pending to Delivered. On this jquery change() event triggers and it fetchs the value from 'tag' and sends the value to other file through ajax. Till here everything goes right the data goes through ajax and row with particular id's status is getting updated successfully.
But on Front end it does not change the status of the particular row. but it changes status of only first row .
Here i need it to change status of the particular row.
Note : I have searched in stackoverflow for this question. but those answere not come close to my question. Here are those links below Link 1link2link3
THANK YOU IN ADVANCE
Here is the Output and i have explained details in images also
There is the full code
HTML page : index.php
<?php
include('processing.php');
$newobj = new processing();
?>
<html>
<head>
<title>Jquery Ajax select <tag> with PHP Mysql</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<table border="1">
<tr>
<th>Id</th>
<th>Product name</th>
<th>Status</th>
<th>Action</th>
</tr>
<?php echo $newobj->display();?>
</table>
<script>
$(document).ready(function(){
$(".selectstatus").change(function(){
var statusname = $(this).val();
var getid = $(this).attr("status-id");
//alert(displid);
$.ajax({
type:'POST',
url:'ajaxreceiver.php',
data:{statusname:statusname,getid:getid},
success:function(result){
$("#display").html(result);
}
});
});
});
</script>
</body>
</html>
AJAX HANDLER PAGE : ajaxreceiver.php
<?php
include('processing.php');
$newobj = new processing();
if(isset($_POST['statusname'],$_POST['getid'])){
$statusid = $_POST['statusname'];
$id = $_POST['getid'];
$newobj->getdata($statusid,$id);
}
?>
PHP CLASSES FILE : processing.php
<?php
class processing{
private $link;
function __construct(){
$this->link= new mysqli('localhost','root','','example');
if(mysqli_connect_errno()){
die ("connection failed".mysqli_connect_errno());
}
}
function display(){
$sql = $this->link->stmt_init();
$id=1;
if($sql->prepare("SELECT id,productname,status FROM ajaxselect")){
$sql->bind_result($id,$productname,$status);
if($sql->execute()){
while($sql->fetch()){
?>
<tr>
<td><?php echo $id;?></td>
<td><?php echo $productname;?></td>
<td><p id="display"><?php echo $status;?></p></td>
<td>
<select status-id=<?php echo $id;?> id="selectstatus" class="selectstatus">
<option>Pending</option>
<option>Delivered</option>
<option>Cancelled</option>
<option>Amount Paid</option>
</select>
</td>
</tr>
<?php
}
}
}
}
function getdata($statusid,$id){
$sql = $this->link->stmt_init();
if($sql->prepare("UPDATE ajaxselect SET status=? WHERE id=?")){
$sql->bind_param('si',$statusid,$id);
if($sql->execute()){
echo $statusid;
}
else
{
echo "Update Failed";
}
}
}
}
?>
the problem is in this line :
$("#display").html(result);
so what's going here ?
you are creating display id for every row, which is not good practice to do , specially in your particular .
there are various solutions for this problem ,
1)
("#display", $(this).parent().parent()).html(result);
here you are going to apply the action to particular ID which is belongs to the parent of the parent of the particular class which had received the change action
2)
giving the display row unique id for each row
for example like follows :-
<td><p id="display_<?php echo $id; ?>"><?php echo $status;?></p></td>
and then apply your action to it directly ,
$("#display_" + getid).html(result);
3)
and this solution is similar to the past one , by giving the parent <tr> a unique id
for example :-
<tr id='parent_<?php echo $id; ?>'>
and then apply your action it from your ajax like this
$("#display", $('#parent_' + getid)).html(result);
or even :
$('#parent_' + getid + ' #display').html(result);
Yes there is problem in $("#display").html(result); line because id ($("#display")) always select first element found in the DOM you can fix it by - following code-
<script>
$(document).ready(function(){
$(".selectstatus").change(function(){
// make jquery object that make reference to select in which click event is clicked
$this = $(this);
var statusname = $(this).val();
var getid = $(this).attr("status-id");
//alert(displid);
$.ajax({
type:'POST',
url:'ajaxreceiver.php',
data:{statusname:statusname,getid:getid},
success:function(result){
// this refer to the ajax callback function so we have to use $this which is initialized before ajax call
$($this).parents('tr').find("#display").html(result);
}
});
});
});
</script>

How to save html values to MySQL using ajax?

I'm trying to make an HTML table dynamically. I'm just testing with sample, but It's not working as well as I expected. So, I'm asking this question. Let me show you this simple table, it is MySQL database. and I create HTML table.
What I want to do is when I click some node, like a '250', this number will be editable. Edited data will be saved to the MySQL database. So I use the contenteditable="true" attribute value, and when this node loses focus, run some JavaScript function that new data will be saved.
But... It's not working well. Honestly I don't know what the problem is exactly. Google chrome spit up "Uncaught Syntax Error, Unexpected token } ", But I couldn't find what the actual problem is. I'm newbie on this... Could you some guys help me?
sample.html
<body>
<?php
require_once("db_connect.php");
$sql = "SELECT * FROM test";
$result = $conn->query($sql);
?>
<table border="1" style="border-collapse:collapse;">
<thead>
<tr><th>name</th><th>price</th></tr>
</thead>
<tbody>
<?php
while($row = $result->fetch_assoc()){
echo
"<tr>
<td contenteditable='true' onBlur='saveToDatabase(this,'name','$id')'>{$row['name']}</td>
<td contenteditable='true' onBlur='saveToDatabase(this,'price','$id')'>{$row['price']}</td>
</tr>\n";
}
?>
</tbody>
</table>
<script>
function saveToDatabase(editableObj, column, id) {
$.ajax({
url: "saveedit.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
</script>
</body>
</html>
saveedit.php
<?php
require_once("db_connect.php");
$result = mysql_query("UPDATE test SET ". $_POST["column"]. " = '".$_POST["editval"]."' WHERE id=".$_POST["id"]);
?>
You made it contenteditable but PHP needs an parameter. For example
<input type="text" name="parameter">
will send as $_POST['parameter'] but in your code <td> elements don't have a name. So PHP doesn't know if there is a parameter or what name is.
Maybe you can write your own editable function in Javascript like this:
function doTextArea(i) {
document.getElementById(i).innerHTML="<input type='text' name='table_value'>ssss.";
}
and your php loop can be like this ( I assume it is for loop):
for ($i = 1; $i <= 10; $i++) {
echo
"<tr>
<td><p id=$i ondblclick='doTextArea($i)'> sadasdasdasd</p></td>
</tr>\n";
}

Collecting AJAX generated text box values with JavaScript

My script’s AJAX calls the following PHP file and prints a table with $attrib and text boxes.
Can somebody tell me how to collect the $attrib and text box in an array or something like that?
Code tried is giving values like "assetattrib%5B%5D=model". So please help me to correct this or show me a new way to do the same.
echo "<table border='1' cellspacing='12' cellpadding='4' style='border-collapse: collapse' width='700' id=addattrib >";
while ($row = mysql_fetch_assoc($results)) {
$attrib = $row['attrib'];
echo "<tr bgcolor='white'>
<td class='value'>$attrib</td>
<td class='value'><input type=text name=assetattrib[] value = '' </td>
</tr>";
}
echo "</table>";
echo "<input type=submit name='btnSaveAsset' id = 'btnSaveAsset' value='Save' >";
I tried the code below.
$(document).on("click", "#btnSaveAsset", function() {
$(document.getElementsByName('assetattrib[]')).each(function() {
var x = $(this).serialize();
alert(x);
});
});
IMPORTANT:
PHP mysql_ extension is deprecated and using it represents a major security issue. According to php.net
This extension is deprecated as of PHP 5.5.0, and has been removed as of PHP 7.0.0. Instead, either the mysqli or PDO_MySQL extension should be used.
Now the actual answer:
I suggest some changes in your HTML, if you can make them:
Wrap the table where the <input>s are into a <form> element
Give the generated <input>s the name attribute given by $attrib, for example <input name="user" />
If you cannot modify the PHP/HTML code let me know and we'll find a workaround
I updated your jsfiddle using this changes. Your PHP code should end up like this:
<form id="btnSaveAsset" onsubmit="return false;">
<table border='1' cellspacing='12' cellpadding='4' style='border-collapse: collapse' width='700' id='addattrib'>
<?php while ($row = mysql_fetch_assoc($results)) {
$attrib = $row['attrib']; ?>
<tr bgcolor='white'>
<td class='value'><?php echo $attrib; ?></td>
<td class='value'><input type='text' name='<?php echo $attrib; ?>' /> </td>
</tr>
<?php } ?>
</table>
<input type=submit name='btnSaveAsset' id='btnSaveAsset' value='Save' />
</form>
Then, you collect your data with one of this options:
$(document).on("click", "#btnSaveAsset", function () {
var data = $("#myForm").serializeArray();
console.log(data); // Array of objects
});
OR
$(document).on("click", "#btnSaveAsset2", function () {
var tempData = $("#myForm").serializeArray();
var data = {};
$.each(tempData, function () {
data[this.name] = this.value;
});
console.log(data); // Just an object
});
Here is the jsfiddle updated: http://jsfiddle.net/jormaechea/sy0wx8gb/1/
Check your JS console (Press F12 and go to Console tab) to see the results.

How to auto fill a form with data from database based on drop menu selection

I'm working on a MySQL update form and struggle to make a drop down selectbox that will autofill the rest of the form with data from mysql. Basically its a table that consist of users and their credentials. When updating a second table with this form i want to be able to select the username from a drop menu and let that selection autofill the rest of the credentials before moving on to the rest of the form.
Here is some of the code for setting up the select and input:
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" />
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" /> </td>
</tr>
And then some javascript
<script>
function populateData()
{
//alert('in populateData');
y = document.getElementById("selectbox");
document.getElementById("klasse").value = [y.selectedIndex];
document.getElementById("klubb").value = [y.selectedIndex];
}
</script>
The result here is a number in the <td>klubb and <td>klasse based on my selection in the drop menu.
How can i connect the arrays with that index number in the javascript so that it will show the actual data from the array ?
I've been seeking an answers for a few days now but can't find anything that answers my question.
Thanks for any help!
Well you can use AJAX for that.
For a tutorial on how to use AJAX and PHP script with Mysql This can help you.
First you need to create a PHP script that will gather the data you need for filling up the forms.
Setup the AJAX to be triggered everytime you choose something in your Drop Down List and pass its value on the PHP script you created.
On your AJAX script configure it to call the PHP script you created for retrieving the data (a value will be thrown in this script based on your drop down list).
Once you receive a response from your AJAX call just use a simple Javascript to fill up the forms based on the data your received.
Another tip is to use JQuery since it is easier for you to setup your AJAX request.
Use AJAX here.
In the populateData() function, use ajax to send the request to retrieve the user credentials & through Javascript, populate your textboxes with the retrieved values.
You could echo the two php arrays as javascript objects, and then access those in your populate function (this is the quick solution). But a better way is to ajax in the actual data
<script>
var klasse = <?=json_encode($klasse)?>
var klubb = <?=json_encode($klubb)?>
</script>
Well you can use Ajax. Make this as your form.
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<div id="some_container">
</div>
Your AJAX request :-
<script type="text/javascript">
$('select').on('change', function() {
var selectedVal = this.value; // or $(this).val()
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?selectedVal="+selectedVal,
dataType: "html", //expect html to be returned
success: function(response){
$("#some_container").html(response);
}
});
});
});
</script>
file.php
<?php
echo '
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" value="$phpValueHere"/>
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" value="$phpValueHere> </td>
</tr>';
?>
In your file.php, get the value of selectedVal via $_GET['selectedVal'] and then extract data from table, after extracting echo the data in those input boxes.

Categories

Resources