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);
?>
Related
Sorry for disturbing again with my very basic question. First of all, sorry if my English is a little bit hard to understand. My current situation is I want to do a popup modal in my drag and drop boxes. In my popup modal, I can view and edit the details of the user based on what we click in the button in the box. The problem is, I cannot SELECT the data by id. But, when I SELECT all the data, the data appear in the modal boxes. But, it appears all the data. I just want the selected id. Back to my question for past few days, I've redo again to get more understanding on this popup modal part. I've done ajax and a little bit JavaScript, also, I tried to debug my code just what I've been told but I got an error saying "Parameter is missing" . What is causing by that ? I've done some reading about parameter but I still don't get the actual understanding about it. Can someone give an idea what is actually parameter is missing . And what I suppose to do by it?
Here what I've tried so far.
This is the button
<button data-id="<?php echo $row['userid'];?>" data-target="doubleClick-1" class='jobinfo' type='button' id='btnInfo' ondblclick="document.getElementById('doubleClick-1').style.display='block'">Info</button>
This is the modal popup
<div id="doubleClick-1" class="modal">
<label class="tabHeading">User Info</label>
<div class="contentTechJobInfo">
<div class="tech-details">
<div class="techClose" onclick="document.getElementById('doubleClick-1').style.display='none'" >×</div>
</div>
</div>
</div>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('.jobinfo').click(function() {
var userid = $(this).data('userid');
// AJAX request
$.ajax({
url: 'ajaxhome.php',
type: 'post',
data: {userid: userid},
success: function(response) {
// Add response in Modal body
$('.tech-details').html(response);
// Display Modal
$('#doubleClick-1').modal('show');
}
});
});
});
</script>
This my ajaxhome.php
<?php
$connection = mysqli_connect("", "", "");
$db = mysqli_select_db($connection, '');
if (!isset($_GET['userid'])) {
die("Parameter is missing!");
}
$userid = intval($_GET['userid']);
$query = "SELECT * FROM user WHERE userid ='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
while ($row = mysqli_fetch_array($query_run)) {
?>
<div class="input-box">
<label for="">Name</label>
<input type="text" id="username" name="username" value="<?php echo $row['username']?>">
</div>
<div class="input-box">
<label for="">Number</label>
<input type="text" id="usernumber" name="usernumber" value="<?php echo $row['usernumber']?>">
</div>
<div class="input-box">
<label for="">Class</label>
<input type="text" id="userclass" name="userclass" value="<?php echo $row['userclass']?>">
</div>
<button type="submit" id="submit" name="update" class="btn btn-primary"> Update Data </button>
<?php
if (isset($_POST['update'])) {
$username = $_POST['username'];
$usernumber = $_POST['usernumber'];
$userclass = $_POST['userclass'];
$query = "UPDATE user SET username='$username', usernumber='$usernumber', userclass='$userclass' WHERE userid='$userid'";
$query_run = mysqli_query($connection, $query);
if ($query_run) {
echo '<script> alert("Data Updated"); </script>';
header("location:homepage.php");
} else {
echo '<script> alert("Data Not Updated"); </script>';
}
}
} ?>
<?php
}
?>
In short, I think the problem comes from these lines of code in your modal:
var userid = $(this).data('userid');
you should replace it with
var userid = $(this).data('id'); // you should pass 'id' to .data() function instead of 'userid'
With your current code userid variable in your modal will always be undefined. It means it wont exist in $_GET when you send ajax request to PHP. And it causes your ajaxhome.php moves to die("Parameter is missing!");.
To get data-xxx attribute with jQuery, you should use pass 'xxx' to .data() function.
var xxx = $(this).data('xxx');
In your button, you are storing userid in data-id attribute
<button data-id="<?php echo $row['userid'];?>"
so if you need to get that userid you should pass 'id' into .data() function
Update:
In your ajax, you are using type: 'post', so in your php code you should check $_POST instead of $_GET
I don't think the value of user has been obtained
var userid = $(this).data('userid');
you can try
var userid = $(this).data('id');
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!
I have made a simple form through which i can search the keywords and find the related output from database dynamically. The code works perfect without AJAX . But now i have applied some AJAX code to get the response on same page within a div named coupon. I am unable to get the response. I don't know where am i doing wrong. Any suggestions please. Here is the complete code.
form
<form action="" id="search_form" method="POST">
<p><input name="query" autocomplete="off" id="list_search" type="search" required class="list_search" /></p>
<p align="center"><input type="submit" id="click" name="click" class="but" value=" search" /></p>
</form>
<div class="coupons"></div>
AJAX
$("document").ready(function(){
// $(".but").click(function(event){ // here
$("#search_form").submit(function (event) {
{
event.preventDefault();
var myData={ query: $( 'input[name="query"]' ).val() };
$.ajax({
url: 'result.php',
data: myData,
type: 'post',
dataType: "html",
success: function(result){
//console.log(result);
$('.coupons').html(result);
},
error: function() {
alert('Not OKay');
}
});
});
});
result.php
$keyword = mysqli_real_escape_string($con,$_REQUEST['query']); // always escape
$keys = explode(" ", $keyword);
$sql="SELECT c.* , sc.* , sm.* ,ca.* from store_category sc INNER JOIN store_manufacture sm ON sm.sm_id=sc.store_id INNER JOIN categories ca ON ca.cat_id=sc.cat_id INNER JOIN coupons c on c.c_sc_id=sc.sc_id WHERE c.c_name LIKE '%$keyword%' OR sm.sm_brand_name LIKE '%$keyword%' OR ca.cat_name LIKE '%$keyword%' OR c.c_description LIKE '%$keyword%'";
foreach ($keys as $k) {
$sql.="OR c.c_name LIKE '%$k%' OR sm.sm_brand_name LIKE '%$k%' OR ca.cat_name LIKE '%$k%' OR c.c_description LIKE '%$k%'";
}
$result = mysqli_query($con, $sql);
$count=mysqli_num_rows($result);
if($count!=0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$res=$row['c_name'].$row['c_description'];
echo json_encode($res);
}
}
else
{
echo "no result";
}
Do not use a click event and a button does not have a submit event - use the form's submit event instead
$("#search_form").on("submit",function(e) {
e.preventDefault();
$.post("result.php?query="+encodeURIComponent($("#list_search").val()),function(data) {
$('.coupons').html(data); // you likely need to render the JSON instead here or send HTML from server
});
});
You should try with:
var myData={ query: $( 'input[name="query"]' ).val() };
So you can get back a query field on the server.
The Problem is your ajax request does have your value as key in $_REQUEST. There might be some way to handle this but it is not very intuitive.
And right you should register the submit handler on your form not your button.
$("#search_form").submit(function(event){ ... }
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.
I was trying to pass the variable thecode, which is in the table using jquery into the function named getComments(). My code has as following. First I have my jquery script which is this:
$(document).ready(function(){
$("#comment_process").click(function(){
if($("#comment_text").val() != ""){
$('.post_loader').show();
$.post("comments_business.php?action=post", {
comment: $("#comment_text").val()
}, function(data) {
$(".comments").hide().html(data).fadeIn('slow');
$("#comment_text").val("");
$('.post_loader').hide();
});
}
});
});
Next I have the following script with html and php:
<!--- more code at the top---->
<?php $auto = $profile_data_business['business_code']; ?>
<table>
<textarea rows="3" id="comment_text" placeholder="share an update."></textarea>
<input type="" id="comment_code" name="thecode" value="<?php echo $auto; ?>" />
<input type="button" id="comment_process" />
</table>
<div class="comments"><?php include_once("comments_business.php");?> </div>
the page named comments_business.php includes a function which is the following:
<?php
function getComments(){
$session_user_id = $_SESSION['user_id'];
$comments = "";
// can't get variable $thisemail
$thisemail = mysql_real_escape_string($_POST['thecode']);
$sql = mysql_query("SELECT * FROM comments_business WHERE ( `flag`=0 and `user`='$thisemail' and `comments_id` NOT IN (SELECT `comments_id` FROM `hide_comment_business` where `user`='$session_user_id') ) ORDER BY comment_date DESC LIMIT 40") or die (mysql_error());
//more code here
return $comments;
}
?>
Any idea how should I change my jquery code so that I will be able to pass $thisemail variable successfully into getComments() function?
When you use $.post don't need to write GET parameter in URL (action=post).
When you post data by comment name, you must get data by some name
in php ($_POST['comment']).
When you use ajax shouldn't use function in php or call function
after defintion.
When you use ajax must print or echo data in php file to display in
post result.