Ajax data - for each data - javascript

I have a problem with my ajax code... I have a list of checkbox, the idea is insert the data of the marked checkboxes into the database.
If I select only one check box, the insert is correct. But if I select for example 3, all data appears on the same field, as unique value.
This is the example:
HTML
<input type="checkbox" class="get_value" value="test1">test1</br>
<input type="checkbox" class="get_value" value="test2">test2</br>
<input type="checkbox" class="get_value" value="test3">test3</br>
<input type="checkbox" class="get_value" value="test4">test4</br>
<input type="checkbox" class="get_value" value="test5">test5</br>
<button type='button' name='submit' id="submit">Submit</button>
This is the ajax code
<script>
$(document).ready(function(){
$('#submit').click(function(){
var insert = [];
$('.get_value').each(function(){
if($(this).is(":checked")){
insert.push($(this).val());
}
});
insert = insert.toString();
$.ajax({
url: "./functions/add_list.php",
method: "POST",
data:{insert:insert},
}
});
});
});
</script>
And this one the PHP that do the insert into the database:
if(isset($_POST["insert"])){
$query = 'INSERT INTO music (name,username) VALUES ("'.$_POST["insert"].'","'.$username.'")';
$result = mysqli_query($conn, $query);
}
For example if I check "test1" and "test2", I will see in my MySQL "name" field "test1,test2". But I need see them in diferent fields, not in the same.
I have tested the "foreach ($_POST["insert"] as $value) { insert... } but it did not help me.
Someone have an idea about my error?
I appreciate your help so much.
Regards,

you need to loop on the server side too :
$arr = explode(',', $_POST["insert"]);
foreach ($arr as $val) {
$query = 'INSERT INTO music (name,username) VALUES ("'.$val.'","'.$username.'")';
$result = mysqli_query($conn, $query);
}

Related

Insert multiple selected checkbox value in database using php and angularjs

I have an html form with checkbox, textbox and radio buttons. When the save button is clicked the form data is to be inserted into to database. I am using an angularjs controller to get the form data and PHP to insert into mysql.
Question: How do I insert selected checkbox value in controller and PHP? Explain to me with code examples.
Below is my code:
html code :
<form class=rform align="center">
<b>Product Name:<input type="text" name="name" ng-model="newProduct.name" required=""/><br>
Product Category: <select name="catg" ng-model="newProduct.catg" ng-options="x for x in catg" ></select><br>
TAGS : <br>
<ul>
<li ng-repeat="tag in tags">
<input type="checkbox" name="tags" ng-model="newProduct.tags" value="tag" ng-true-value="tag"> {{tag}}
</li>
</ul>
<Status :<br><br>
<input type="radio" ng-model="newProduct.stat" value="Active">Active
<input type="radio" ng-model="newProduct.stat" value="Deactive">Deactive<br><br>
<input type="hidden" ng-model="newProduct.id" /></b>
<div class="btn"> <button type="submit" ng-disabled="rform.$invalid" ng-click="saveRecord(newProduct)">Save</button></div>
</form>
app.js
app.controller('ProductCtrl',function($scope,$http){
$scope.tags = ["Appliances","Electronics","Men&Women","Others"] ;
$scope.catg = ["mobile","Air Conditioner","Kitchen appliances","Footwear","SportsWear","clothes",
"watches","Lptops","Televisions","Camera","Furniture","Kitchen Dining","Music","Stationery"];
$scope.saveRecord = function (newProduct) {
$http.post("php/pinsert.php",{
'name' : $scope.newProduct.name,
'catg' : $scope.newProduct.catg,
'tags' : $scope.newProduct.tags,
'stat' : $scope.newProduct.stat
})
// data:$scope.products,
.success(function(data){
alert(data);
})
angular.forEach($scope.tags, function(tag){
if (tag.selected) $scope.albumNameArray.push(tag.name);
tag.selected= false ;
});
tag.selected= false ;
}
$http.get("php/pselect.php").then(function (response) {
$scope.myproducts = response.data.records;
});
});
PHP :
<?php
$connect = mysqli_connect("localhost", "root", "","user");
$data = json_decode(file_get_contents("php://input"));
$p_name = mysqli_real_escape_string($connect, $data->name);
$p_catg = mysqli_real_escape_string($connect, $data->catg);
$tags = mysqli_real_escape_string($connect, $data->tags);
$status = mysqli_real_escape_string($connect, $data->stat);
$query = "INSERT INTO products(pname,pcatg,tag,status) VALUES ('$p_name','$p_catg','$tags','$status')";
$result = mysqli_query($connect, $query) ;
if($result == TRUE)
{
echo "Data Inserted...";
}
else
{
echo 'Error';
}
?>
I would restructure your tags array likewise. The selected property will be set to true if the checkbox is selected. The name is simply for display.
$scope.tags = [
{"selected":false, "name":"Appliances"},
{"selected": false, "name":"Electronics"},
{"selected":false, "name":"Men&Women"},
{"selected":false, "name":"Others"}
];
The markup for the checkboxes should also be restructured. Notice the ng-model is using the .selected property of $scope.newProduct.tags. This will set allow you to see which tags properties are selected when saving to the DB.
<li ng-repeat="tag.name for tag in tags">
<input type="checkbox" name="tags" ng-model="tag.selected" value="tag" ng-true-value="tag"> {{tag.name}}
</li>
When assigning newProduct to scope it is not necessary to pass it as a parameter in $scope.saveRecord(). You can also pass the entire object in the post body. The ajax call is written without the shorthand $http.post either way is fine but I find this easier to read.
$scope.saveRecord = function(){
$http({
url: "php/pinsert.php",
method: "POST",
data: $scope.newProduct
}).success(function(data){
// process returned data
});
}
On the backend the data will be structured the same your the $scope.newProduct object was structured. You will need to:
Loop through this data
Find the selected tags
Save the checked (selected.true) tag values into the table
I don't know the exact structure of your products table but the 3 steps above are a guide for saving complex data into the DB.
$connect = mysqli_connect("localhost", "root", "","user");
$data = json_decode(file_get_contents("php://input"));
foreach($data['tags'] as $tag){
// Save only selected tags to products table
if($tag->selected){
$query = "
INSERT INTO products(tag)
VALUES('$p_name','$p_catg','$tags','$status')
";
$result = mysqli_query($connect, $query);
}
}
Hopefully this gets your started, cheers!

How can I interact with a javascript variable using PHP?

I have a really simple web app which allows a user to enter a first and last name and hit submit to insert the name into a sql database.
Below the form, there is a HTML table displaying the contents of the database table.
If a user clicks on any row of the database, the ID of the HTML element (which is set to the same value of the database ID) is saved to a javascript variable using the following function.
<!--JS Functions-->
<script>
//Determine which record is selected.
var id;
function TableSelect(el) {
id = el.id;
alert(id);
}
</script>
Here is the form:
<!--HTML Form -->
<form method="post" action="index.php">
First Name: <input type="text" name="FirstName" value="">
<br><br>
Last Name: <input type="text" name="LastName" value="<?php echo $LastName;?>">
<br><br>
<input type="submit" name="submit" value="Submit">
<input type="submit" name="delete" value="Delete" onclick="Delete()">
</form>
Here is the PHP processing of the data and the output of the SQL table:
//prepare query to insert data from form into DB
if (isset($_POST['submit'])){
$query = "INSERT INTO tbl_HR_Master (First_Name, Last_Name) VALUES ('{$FirstName}', '{$LastName}') ";
$result = mysqli_query($connection, $query);
//Test if there was a query error
querycheck($result);
}//end if
//prepare query to populate table from DB
$query2 = "Select id, First_Name as 'First Name', Last_Name as 'Last Name' from tbl_HR_Master";
$result2 = mysqli_query($connection, $query2);
//Test if there was a query error
querycheck($result2);
//display table
echo "</br>";
echo "<table id=\"tbl_HR_Master\" border='1'><tr class=\"nohover\"\">";
// printing table headers
$fields_num = mysqli_num_fields($result2);
for($i=0; $i<$fields_num; $i++) {
$field = mysqli_fetch_field($result2);
echo "<td>{$field->name}</td>";
} //end for
echo "</tr>\n";
// print table rows
while($row = mysqli_fetch_row($result2))
{
echo "<tr>";
$id = $row[0];
foreach($row as $cell){
echo "<td onclick=TableSelect(this) id=". $id .">".$cell."</td>";
}//end foreach
echo "</tr>\n";
}//end while
I want to run a PHP function which deletes the selected record from the database however, obviously PHP runs on the server, therefore, I need some way to tell PHP which record is selected. Once again, if you look at my Javascript function, var id = the last selected record. How can I parse this JS variable to the server for processing?
In a nutshell, want to do this in PHP:
//delete selected record
if (isset($_POST['delete'])){
$query3 = "Delete from tbl_HR_Master where id = ". JS VARIABLE HERE." ";
} //end if
Form-based
You could do this with an hidden form field which you give a specific id:
<input type="hidden" id="your-id" value="" />
and then in your TableSelect function you assign the value:
document.getElementById('your-id').value = id;
Then you can access the variable like the other request (post / get) parameters, in your case:
$_POST['id']
Ajax-based
With jQuery you could perform an ajax request like this in your TableSelect function:
$.ajax({
url: 'file.php',
type: 'post',
data: {'id': el.id},
success: function(data, status) {
// ...
}
});
Request parameter access is the same:
$_POST['id']
You can have a hidden variable inside your form and use javascript to set the value of that hidden variable onclick.
<!--JS Functions-->
<script>
//Determine which record is selected.
var id;
function TableSelect(el) {
document.getElementById('selectedRow').value = el.id;
}
</script>
And add the following within your form tag
<input type="hidden" name="selectedRow" id="selectedRow">
Then you can update your query to be something like
$query3 = "Delete from tbl_HR_Master where id = $_POST['selectedRow']";
Of course don't forget to add sanitization and validation and all that jazz.

jQuery serialize and insert in mysql

I have this code to insert some data that comes from a while, in a db. I'm trying to use jQuery serializearray and jQuery post together. But it seems I do some errors
$query= "SELECT * FROM barcode_prodotti";
$result = mysql_query($query) or die(mysql_error());
while($row=mysql_fetch_array($result)){
echo'
<input type="text" name="prodotto[]" class="prodotto" value="'.$row["prodotto"].'"></div>
<input type="text" name="prezzo[]" class="price" value="'.$row["prezzo"].'">
<input type="text" name="quantita[]" class="price" value="'.$row["quantita"].'">';
}
?>
<script src="js/mine.js"></script>
<button>Serialize form values</button>
</form>
<div id="results"></div>
This is my jQuery code I put in mine.js
$(document).ready(function(){
$('form').submit(function(msg) {
var mia =$(this).serialize();
$('#results').text(mia)
alert($(this).serialize()); // check to show that all form data is being submitted
$.post("testtest.php",$(this).serializeArray(),function(data){
alert(data);
});
return false; });
});
This is my php file (testtest.php)
mysql_connect("localhost","root","");
mysql_select_db("db");
$arr = $_POST;
$sql="INSERT INTO table VALUES(
'".$arr['prodotto']."',
'".$arr['quantita']."',
'".$arr['prezzo']."'
)";
$rssql = mysql_query($sql);
?>
So I the serialize is ok (i tried to assign in a div a value to see if it was ok), but I can't insert values in my db
Your INSERT query ends up looking like this after variable substitution.
INSERT INTO table VALUES( 'product', '123', '321')
If your table has exactly three columns this will work fine. Otherwise it will fail. You may wish to use this query instead.
INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')
which enumerates the columns where you want your data.
After doing an insert (and after any query) you should check for errors. This can be done with code like this.
$res = mysql_query($q);
if ($res === false) {
echo $mysql_error ();
}
Note well: The mysql_xxx() interface is being removed from PHP for a good reason: it is vulnerable to cybercriminals. Please adopt mysqli_xxx() or PDO as soon as possible.
The simplest way to do this:
<form id="myform" method="post">
<input type="text" name="prodotto" id="prodotto">
<input type="text" name="prezzo" id="prezzo">
<input type="text" name="quantita" id="quantita">
</form>
Jquery is pretty simple too:
var datastring = $("#myform").serialize();
$.ajax({
type: 'POST',
url: 'url/to/yourfile.php',
data: datastring
}).done(function(res){
var res = $.trim(res); //the ajax response. you can alert it or whatever...
});
You can parse the fields in the ajax file like that:
yourfile.php
<?php
$product = mysql_real_escape_string($_POST["prodotto"]);
$prezzo = mysql_real_escape_string($_POST["prezzo"]);
$quantity = mysql_real_escape_string($_POST["quantita"]);
//here you have the variables ready to add them as values to database
$ins = "INSERT INTO table (prodotto, prezzo, quantita ) VALUES( 'product', '123', '321')";
mysql_query($ins);
?>

Getting form data from both dependent drop down lists to php

I have a form on my page which includes 2 dependent drop down lists. When user selects value from 1st list, it populates the second list and user then selects value from 2nd list.
I want to submit form data to php page to insert into table in mysql, but when it submits, all data is passed EXCEPT value from 2nd list. Value from 1st list and other input fields are passed OK.
I've tried everything I know and I can't make this work. Any ideas how to implement this?
This is the form from index2.php (EDIT: simplified the form element):
<form name="part_add" method="post" action="../includes/insertpart.php" id="part_add">
<label for="parts">Choose part</label>
<select name="part_cat" id="part_cat">
<?php while($row = mysqli_fetch_array($query_parts)):?>
<option value="<?php echo $row['part_id'];?>">
<?php echo $row['part_name'];?>
</option>
<?php endwhile;?>
</select>
<br/>
<label>P/N</label>
<select name="pn_cat" id="pn_cat"></select>
<br/>
<input type="text" id="manufactured" name="manufactured" value="" placeholder="Manufactured" />
<input id="submit_data" type="submit" name="submit_data" value="Submit" />
</form>
And this is javascript:
$(document).ready(function() {
$("#part_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading part number" /></div>');
$.get('../includes/loadpn.php?part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
And this is php to load 2nd list:
<?php
include('db_connect.php');
// connects to db
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$part_cat = $_GET['part_cat'];
$query = mysqli_query($con, "SELECT * FROM pn WHERE pn_categoryID = {$part_cat}");
while($row = mysqli_fetch_array($query)) {
echo "<option value='$row[part_id]'>$row[pn_name]</option>";
}
?>
I am getting $part_cat from 1st list to insertpart.php, but $pn_cat.
EDIT: this is insertpart.php (simplified and it just echos resuls)
<?php
//Start session
session_start();
//Include database connection details
require_once('../includes/db_details.php');
//DB connect
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
// find part name based on ID
$part_typeID = mysqli_real_escape_string($con, $_POST['part_cat']);
$part_name_result = mysqli_query($con, "SELECT part_name FROM parts WHERE part_id = $part_typeID");
$part_row = mysqli_fetch_array($part_name_result, MYSQL_NUM);
$part_type = $part_row[0];
echo"part_type='$part_type'";
//find pn value based on id
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
$pn_name_result = mysqli_query($con, "SELECT pn_name FROM pn WHERE pn_id = $pn_typeID");
$pn_row = mysqli_fetch_array($pn_name_result, MYSQL_NUM);
$pn = $pn_row[0];
echo"pn='$pn'";
mysqli_close($con);
?>
It's still work in progress, so the code is ugly, and I know I'm mixing POST and GET that is being rectified. If I echo $pn_cat on this page there is no output, $part_type is OK.
Can you try swapping the $_GET in
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
with $_POST?
$pn_typeID = mysqli_real_escape_string($con, $_POST['pn_cat']);
EDIT: based on asker's feedback and idea for a work-around
NOTE: This edit is based on what you suggested, even though I tested your original code and received satisfactory results (after I removed the PHP and MySQL from the code and replaced them with suitable alternatives).
The Work-Around
Here's the HTML for the hidden field:
<input type="hidden" id="test" name="test" value="" placeholder="test" />
Here's a simple Javascript function:
function setHiddenTextFieldValue(initiator, target){
$(initiator).change(function() {
$(target).val($(this).val());
});
}
You can call the above function within the function(data) { of your original code with something like:
setHiddenTextFieldValue('#pn_cat', '#test'); // note the hashes (#)
I also recommend you to hard-code the following HTML into your HTML and PHP files, right before the looping of the <option>s begin:
<option value="" disabled selected="selected">Select</option>
The above line could improve user experience, depending on how you want your code to work. Note however, that this is entirely optional.
Solved it! It was just a stupid typo, can't believe I've lost 2 days over this!
In loadpn.php instead of:
$row[part_id]
it should read:
$row[pn_id]
For some reason drop down worked, but offcourse value of pn_cat wasn't being set.
Also this works in setting 2 field values (which now I don't need but if somebody wants to know):
$(document).ready(function() {
$("#part_cat").change(function() {
$('#pn_hidden').val($(this).val());
});
$("#pn_cat").change(function() {
$('#pn_hidden2').val($(this).val());
});
});
Also changed js to post:
$(document).ready(function() {
$("#part_cat").change(function() {
$.post('../includes/loadpn.php', 'part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
});
});
});
And thanks for the:
<option value="" disabled selected="selected">Select</option>
It really helps with user experience.

Run a PHP code to get a value from a database according to a value of a text element

All I;m building a web based system. Here I was thinking whether I can get Name according to the number I enter in a text box. What I've tried is as follows. I know it's not working. Will there be another workaround for that? Please help...
html code is
Item No:<input name="iNo" type="text" id="iNo" size="40" maxlength="6" onblur="namesrch()">
Item Name:<input name="na" type="text" id="na" size="40" maxlength="40" disabled>
Here's my javascript
function namesrch(){
iNumber = document.getElementById('iNo').value;
document.getElementById('na').value="<?php $SQL="SELECT iName FROM item Where iNo='iNumber'" ; $run=mySQL_Query($SQL,$con) or die ("SQL error"); while($rec=mySQL_fetch_array($run)){echo $rec{'iName'}}?>";
}
Hope you can understand what I'm trying to do. Thanks in advance..
JavaScript is a client side language, where as PHP is a server side language. You can't run PHP inside JavaScript like that. What you need is Ajax.
Here is a quick example:
Javascript
$('#iNo').on('update', function() {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { no: $(this).val() }
success: function(name) {
$('#na').val(name);
}
});
});
Ajax.php
$dbConn = new MySqli($host, $username, $passwd, $dbName);
$no= filter_input(INPUT_POST, "no", FILTER_VALIDATE_INT);
$query = "SELECT iName FROM item WHERE iNo = $no";
$result = $dbConn->query($query);
$name = '';
if($dbConn->errno) {
//An error occurred
} elseif($result->num_rows) {
$row = $result->fetch_assoc();
$name = $row['iNo'];
$result->free();
}
echo $name;
You will notice I used MySQLi, rather than MySQL. MySQL is depreciated and should no longer be used. It is worth your time learning to use either MySQLi or PDO.
I hope this helps.
You can't mix php and js. Assuming you want all the code in one file:
filename.php (Not tested)
<?php
if (isset($_GET['iNumber'])) {
$mysqli = new mysqli("localhost", "my_user", "my_password", "database_name");
// You need to check for sql injection here
$SQL = "SELECT iName FROM item Where iNo = '".$_GET['iNumber']."'' LIMIT 1";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
echo json_encode(array('iName' => $row['iName']));
exit();
}
?>
<html>
<head>
<title></title>
</head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<body>
Item No:<input name="iNo" type="text" id="iNo" size="40" maxlength="6" onblur="namesrch()">
Item Name:<input name="na" type="text" id="na" size="40" maxlength="40" disabled>
<script type="text/javascript">
function namesrch() {
iNumber = document.getElementById('iNo').value;
$.getJSON('filename.php?iNumber='+iNumber, function(response) {
$('#na').value(response.name);
});
}
</script>
</body>
</html>

Categories

Resources