Display search bar query results in modal - javascript

I have a search bar for users to enter a query. Upon clicking 'Search', a modal should appear with the query results.
My output from index.php is still not showing in the modal. When I click 'Search', the modal pops up with an empty body. How do I get my output from index.php to show in the modal's body?
Is there something wrong with my script? Do I need to add something to modal-body?
index.php
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<form method="POST" action="#">
<input type="text" name="q" placeholder="Enter query"/>
<input type="button" name="search" value="Search" data-toggle="modal" data-target="#mymodal">
</form>
</body>
<script>
$.ajax({ type: "GET",
url: 'search.php',
success: function(data){ debugger $('#mymodal').modal('show');
$('#mymodal:visible .modal-content .modal-body').html(e); } });
</script>
<!-- The Modal -->
<div class="modal" id="mymodal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Modal Heading</h4>
<button type="button" class="close" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
search.php
<?php
include_once('db.php'); //Connect to database
if(isset($_REQUEST['q'])){
$q = $_REQUEST['q'];
//get required columns
$query = mysqli_query($conn, "SELECT * FROM `words` WHERE `englishWord` LIKE '%".$q."%' OR `yupikWord` LIKE '%".$q."%') or die(mysqli_error($conn)); //check for query error
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<h2>No result found</h2>';
}else{
while($row = mysqli_fetch_assoc($query)){
$output .= '<h2>'.$row['yupikWord'].'</h2><br>';
$output .= '<h2>'.$row['englishWord'].'</h2><br>';
$output .= '<h2>'.$row['audio'].'</h2><br>';
$audio_name = $row['audio'];
$output .= '<td><audio src="audio/'.$audio_name.'" controls="control">'.$audio_name.'</audio></td>';
}
}
echo $output;
}else{
"Please add search parameter";
}
mysqli_close($conn);
?>

use these code of search.php
<?php
include_once('db.php'); //Connect to database
if(isset($_REQUEST['q']))
{
$q = $_REQUEST['q'];
$query = mysqli_query($conn, "SELECT * FROM `words` WHERE `englishWord` LIKE '%".$q."%' OR `yupikWord` LIKE '%".$q."%'") or die(mysqli_error($conn));
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<h2>No result found</h2>';
}else{
while($row = mysqli_fetch_assoc($query)){
$output .= '<h2>'.$row['yupikWord'].'</h2><br>';
$output .= '<h2>'.$row['englishWord'].'</h2><br>';
$output .= '<h2>'.$row['audio'].'</h2><br>';
$audio_name = $row['audio'];
$output .= '<td><audio src="audio/'.$audio_name.'" controls="control">'.$audio_name.'</audio></td>';
}
}
echo $output;
}else{
"Please add search parameter";
}
mysqli_close($conn);
?>

Related

Button click not returning data or initializing modal

I have created a form to display all records from my database with the ability to add a new user, edit, and delete. The delete works fine. However, the add and edit functions are supposed to show a bootstrap modal with either blank fields for the add user, or all the information to edit a user. The modal isn't appearing and I can't understand why. There are no errors displayed in the console. I know I have the correct database configuration since the delete function works.
Driving me crazy :)
I've attached my code to see if anyone knows what I'm missing.
Thanks!!
profile.php
<!DOCTYPE html>
<html lang="en">
<head>
<title>Staff Profile Form</title>
<meta charset="utf-8">
<link rel="stylesheet" href="bootstrap/css/bootstrap.min.css">
<script src = "jquery/jquery-3.3.1.js"></script>
<script>
// Update the users data list
function getUsers(){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: 'action_type=view',
success:function(html){
$('#userData').html(html);
}
});
}
// Send CRUD requests to the server-side script
function userAction(type, id){
id = (typeof id == "undefined")?'':id;
var userData = '', frmElement = '';
if(type == 'add'){
frmElement = $("#modalUserAddEdit");
userData =
frmElement.find('form').serialize()+'&action_type='+type+'&id='+id;
}else if (type == 'edit'){
frmElement = $("#modalUserAddEdit");
userData = frmElement.find('form').serialize()+'&action_type='+type;
}else{
frmElement = $(".row");
userData = 'action_type='+type+'&id='+id;
}
frmElement.find('.statusMsg').html('');
$.ajax({
type: 'POST',
url: 'userAction.php',
dataType: 'JSON',
data: userData,
beforeSend: function(){
frmElement.find('form').css("opacity", "0.5");
},
success:function(resp){
frmElement.find('.statusMsg').html(resp.msg);
if(resp.status == 1){
if(type == 'add'){
frmElement.find('form')[0].reset();
}
getUsers();
}
frmElement.find('form').css("opacity", "");
}
});
}
// Fill the user's data in the edit form
function editUser(id){
$.ajax({
type: 'POST',
url: 'userAction.php',
dataType: 'JSON',
data: 'action_type=data&id='+id,
success:function(data){
$('#id').val(data.id);
$('#name').val(data.name);
$('#location').val(data.location);
$('#specialty').val(data.specialty);
}
});
}
// Actions on modal show and hidden events
$(function(){
$('#modalUserAddEdit').on('show.bs.modal', function(e){
var type = $(e.relatedTarget).attr('data-type');
var userFunc = "userAction('add');";
if(type == 'edit'){
userFunc = "userAction('edit');";
var rowId = $(e.relatedTarget).attr('rowID');
editUser(rowId);
}
$('#userSubmit').attr("onclick", userFunc);
});
$('#modalUserAddEdit').on('hidden.bs.modal', function(){
$('#userSubmit').attr("onclick", "");
$(this).find('form')[0].reset();
$(this).find('.statusMsg').html('');
});
});
</script>
</head>
<body>
<?php
// Include and initialize DB class
require_once 'db.php';
$db = new DB();
// Fetch the users data
$users = $db->getRows('monctonfir');
?>
<div class="container">
<div class="row">
<div class="col-md-12 head">
<h5>Users</h5>
<!-- Add link -->
<div class="float-right">
<a href="javascript:void(0);" class="btn btn-success" data-
type="add" data-toggle="modal" data-target="#modalUserAddEdit"><i
class="plus"></i> New User</a>
</div>
</div>
<div class="statusMsg"></div>
<!-- List the users -->
<table class="table table-striped table-bordered">
<thead class="thead-dark">
<tr>
<th>ID</th>
<th>Name</th>
<th>Location</th>
<th>Specialty</th>
<th>Profile Image</th>
<th>Action</th>
</tr>
</thead>
<tbody id="userData">
<?php if(!empty($users)){ foreach($users as $row){ ?>
<tr>
<td><?php echo '#'.$row['id']; ?></td>
<td><?php echo $row['name']; ?></td>
<td><?php echo $row['location']; ?></td>
<td><?php echo $row['specialty']; ?></td>
<td><?php echo $row['file']; ?></td>
<td>
UPDATE
DELETE
</td>
</tr>
<?php } }else{ ?>
<tr><td colspan="5">No user(s) found...</td></tr>
<?php } ?>
</tbody>
</table>
</div>
</div>
<!-- Modal Add and Edit Form -->
<div class="modal fade" id="modalUserAddEdit" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add New User</h4>
<button type="button" class="close" data-dismiss="modal">×
</button>
</div>
<!-- Modal Body -->
<div class="modal-body">
<div class="statusMsg"></div>
<form role="form">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name" placeholder="Enter your name">
</div>
<div class="form-group">
<label for="location">Location</label>
<input type="text" class="form-control" name="location" id="location" placeholder="Enter your work site">
</div>
<div class="form-group">
<label for="specialty">Specialty</label>
<input type="text" class="form-control" name="specialty" id="specialty" placeholder="Enter your specialty">
</div>
<input type="hidden" class="form-control" name="id" id="id"/>
</form>
</div>
<!-- Modal Footer -->
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-success" id="userSubmit">SUBMIT</button>
</div>
</div>
</div>
</div>
</body>
</html>
userAction.php
<?php
// Include and initialize DB class
require_once 'DB.php';
$db = new DB();
// Database table name
$tblName = 'monctonfir';
// If the form is submitted
if(!empty($_POST['action_type'])){
if($_POST['action_type'] == 'data'){
// Fetch data based on row ID
$conditions['where'] = array('id' => $_POST['id']);
$conditions['return_type'] = 'single';
$user = $db->getRows($tblName, $conditions);
// Return data as JSON format
echo json_encode($user);
}elseif($_POST['action_type'] == 'view'){
// Fetch all records
$users = $db->getRows($tblName);
// Render data as HTML format
if(!empty($users)){
foreach($users as $row){
echo '<tr>';
echo '<td>#'.$row['id'].'</td>';
echo '<td>'.$row['name'].'</td>';
echo '<td>'.$row['location'].'</td>';
echo '<td>'.$row['specialty'].'</td>';
echo '<td>edit
delete</td>';
echo '</tr>';
}
}else{
echo '<tr><td colspan="5">No user(s) found...</td></tr>';
}
}elseif($_POST['action_type'] == 'add'){
$msg = '';
$status = $verr = 0;
// Get user's input
$name = $_POST['name'];
$location = $_POST['location'];
$specialty = $_POST['specialty'];
// Validate form fields
if(empty($name)){
$verr = 1;
$msg .= 'Please enter your name.<br/>';
}
if(empty($location) || !filter_var($email, FILTER_VALIDATE_EMAIL)){
$verr = 1;
$msg .= 'Please enter your work site.<br/>';
}
if(empty($specialty)){
$verr = 1;
$msg .= 'Please enter your specialty.<br/>';
}
if($verr == 0){
// Insert data in the database
$userData = array(
'name' => $name,
'location' => $location,
'specialty' => $specialty,
);
$insert = $db->insert($tblName, $userData);
if($insert){
$status = 1;
$msg .= 'User data has been inserted successfully.';
}else{
$msg .= 'Some problem occurred, please try again.';
}
}
// Return response as JSON format
$alertType = ($status == 1)?'alert-success':'alert-danger';
$statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
$response = array(
'status' => $status,
'msg' => $statusMsg
);
echo json_encode($response);
}elseif($_POST['action_type'] == 'edit'){
$msg = '';
$status = $verr = 0;
if(!empty($_POST['id'])){
// Get user's input
$name = $_POST['name'];
$location = $_POST['location'];
$specialty = $_POST['specialty'];
$location = $_POST['location'];
// Validate form fields
if(empty($name)){
$verr = 1;
$msg .= 'Please enter your name.<br/>';
}
if(empty($location)){
$verr = 1;
$msg .= 'Please enter a your work site.<br/>';
}
if(empty($specialty)){
$verr = 1;
$msg .= 'Please enter your specialty<br/>';
}
if($verr == 0){
// Update data in the database
$userData = array(
'name' => $name,
'location' => $location,
'specialty' => $specialty,
);
$condition = array('id' => $_POST['id']);
$update = $db->update($tblName, $userData, $condition);
if($update){
$status = 1;
$msg .= 'User data has been updated successfully.';
}else{
$msg .= 'Some problem occurred, please try again.';
}
}
}else{
$msg .= 'Some problem occurred, please try again.';
}
// Return response as JSON format
$alertType = ($status == 1)?'alert-success':'alert-danger';
$statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
$response = array(
'status' => $status,
'msg' => $statusMsg
);
echo json_encode($response);
}elseif($_POST['action_type'] == 'delete'){
$msg = '';
$status = 0;
if(!empty($_POST['id'])){
// Delate data from the database
$condition = array('id' => $_POST['id']);
$delete = $db->delete($tblName, $condition);
if($delete){
$status = 1;
$msg .= 'User data has been deleted successfully.';
}else{
$msg .= 'Some problem occurred, please try again.';
}
}else{
$msg .= 'Some problem occurred, please try again.';
}
// Return response as JSON format
$alertType = ($status == 1)?'alert-success':'alert-danger';
$statusMsg = '<p class="alert '.$alertType.'">'.$msg.'</p>';
$response = array(
'status' => $status,
'msg' => $statusMsg
);
echo json_encode($response);
}
}
exit;
?>
Bootstrap lists modals under components requiring JavaScript (i.e. bootstrap.min.js)
take a look at the docs: https://getbootstrap.com/docs/4.0/getting-started/introduction/
Try adding this before the closing body tag:
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

The result of a database query is not getting displayed on my page

I am trying to get details of products to be displayed on my webpage in a specific format by submitting an id number through a form. But no data is being displayed on submitting the query. I want the latest retrieved data to be appended below the already existing data on the same page from where the form was submitted.
This is my home.php :
<?php
ob_start();
session_start();
require_once 'dbconnect.php';
// if session is not set this will redirect to login page
if( !isset($_SESSION['user']) )
{
header("Location: index.php");
exit;
}
// select loggedin users detail
$res=mysqli_query($conn, "SELECT * FROM users WHERE userId=".$_SESSION['user']);
$userRow=mysqli_fetch_array($res);
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title> ShopNGo </title>
<link rel="stylesheet" type="text/css" href="style.css">
<link rel="stylesheet" href="assets/css/bootstrap.min.css" type="text/css" />
<link rel="stylesheet" href="style.css" type="text/css" />
<script src="ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#scan").on('click',function()
{
var id =$("#id").val();
$.ajax(
{
type: "POST",
url: "getdata.php",
data: {id: id},
success: function(data)
{
$('.results').append(data);
}
});
});
});
</script>
</head>
<body>
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
<span class="glyphicon glyphicon-user"></span> Hi' <?php echo $userRow['userEmail']; ?> <span class="caret"></span></a>
<span class="glyphicon glyphicon-log-out"></span> Sign Out
<header id="header">
<div class="container">
<form name="products" method="POST" action="">
<br><br>
<input type="submit" name="scan" id="scan" value="SCAN">
<br><br><br>
<input type="text" name="id" id="id">
</form>
</div>
</header>
<div class="main">
<table border="0">
<div class="results" id="results">
</div>
</table>
</div>
</body>
</html>
<?php ob_end_flush(); ?>
This is my getdata.php :
$query = "SELECT name, price, img FROM product WHERE id = $_POST[id]";
$result = mysqli_query($conn, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$element = "<tr> <table border='0'> <tr>";
$element .= "<img src='$row[img]'>";
$element .= "<br>";
$element .= $row["name"];
$element .= "<br>";
$element .= $row["price"];
$element .= "</tr> </table> </tr>";
}
}
echo $element;
This is dbconnect.php
<?php
// this will avoid mysql_connect() deprecation error.
error_reporting( ~E_DEPRECATED & ~E_NOTICE );
// but I strongly suggest you to use PDO or MySQLi.
$servername = "localhost";
$username = "#usernasme";
$password = "#password";
$dbname = "#dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if ( !$conn )
{
die("Connection failed : " . mysqli_error());
}
?>
FYI - I am using a php script that maintains a user login session that connects to a database and keeps a user logged in until he signs out. Is there by any an interference between the two scripts: one that maintains user sessions and another that accesses database for getting product details. Thanks in advance.
You are not sending any data via ajax; I'm supposing that you'have included jquery correctly; Then try this
$(document).ready(function(){
$("#scan").on('click',function(){
var id =$("#id").val();
$.ajax({
type: "POST",
url: "getdata.php",
data: {id: id},
success: function(data){
$('.results').append(data);
}
});
});
});
Good luck

how to restrict the user not to post again on the same page if already posted

I have the below code for User Rating & Comment system which is working fine, but user can post and rate again and again.
I want that if a user posted comment already he/she should not see the comment box but a message that " You have already posted comment on this page".
I tried by using the query in the Add-Comment.php but did not worked.
Need help to solve this issue. Thanks
URL: index.php?id=1
Add-Comment.php
<?php
session_start();
$ipaddress = $_SERVER["REMOTE_ADDR"];
$users = session_id();
if(!empty($_POST)){
extract($_POST);
if($_POST['act'] == 'add-com'):
$comment = htmlentities($comment);
$rating = htmlentities($rating);
// Connect to the database
require_once '../../inc/db.php';
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . "?d=" . $default . "&s=" . $size;
$sql = "INSERT INTO rest_rating (rate, comment, sr_id, ip, user)
VALUES ('$rating', '$comment', '$id_post', '$ipaddress', '$users')";
$sqls = "select user from rest_rating
where sr_id = '$id_post' and user ='$users' )";
$tt = $db->query($sqls);
if ( $tt['user'] == $users ) {
echo '<font size="3" color="red">You Have Already Rated For This Restaurant</font>';
}elseif ( $db->query($sql)==true) {
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" alt="" />
<div class="thecom">
<!--<h5><?php echo $name; ?></h5>-->
<b>Rating : </b><?php echo $rating; ?>
<span class="com-dt"><?php echo date('d-m-Y H:i'); ?></span>
<br/>
<p><?php echo $comment; ?></p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<?php endif; ?>
<?php } ?>
index.php
<?php
require_once '../../inc/db.php';
$id=$_GET['id'];
?>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="//netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.1.0/js/bootstrap.min.js"></script>
<link type="text/css" rel="stylesheet" href="css/example.css">
<link href="css/star-rating.css" media="all" rel="stylesheet" type="text/css"/>
<script src="js/star-rating.js" type="text/javascript"></script>
<div class="container">
<h3>Comments</h3>
<?php
$id_post = $id;
?>
<div class="cmt-container" >
<?php
session_start();
$users = session_id();
$results = $db->query("SELECT * FROM rest_rating WHERE sr_id = $id_post");
foreach ($results as $affcom) {
$comment = $affcom['comment'];
$rating = $affcom['rate'];
$date = $affcom['date'];
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/" . "?d=" . $default . "&s=" . $size;
?>
<div class="cmt-cnt">
<div class="thecom">
<input id="input-5a" class="rating" value="<?php echo $rating; ?>" data-size="xs" data-show-clear="false" data-show-caption="false" data-readonly="true">
<span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input name="starrating" id="starrating" value="1" type="number" class="rating" min=0 max=5 step=1 data-size="xs2" >
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clear"></div>
</div><!-- end of comments container "cmt-container" -->
<?php
$sqls = "select user from rest_rating
where sr_id = '$id_post' and user ='$users' )";
$tt=$db->query($sqls);
$userT=$tt['user'];
?>
<script type="text/javascript">
$(function(){
//alert(event.timeStamp);
$('.new-com-bt').click(function(event){
$(this).hide();
$('.new-com-cnt').show();
$('#name-com').focus();
});
/* when start writing the comment activate the "add" button */
$('.the-new-com').bind('input propertychange', function() {
$(".bt-add-com").css({opacity:0.6});
var checklength = $(this).val().length;
if(checklength){ $(".bt-add-com").css({opacity:1}); }
});
/* on clic on the cancel button */
$('.bt-cancel-com').click(function(){
$('.the-new-com').val('');
$('.new-com-cnt').fadeOut('fast', function(){
$('.new-com-bt').fadeIn('fast');
});
});
// on post comment click
$('.bt-add-com').click(function(){
var theCom = $('.the-new-com');
var starrating = $('#starrating');
if( !theCom.val()){
alert('You need to write a comment!');
}else{
$.ajax({
type: "POST",
url: "add-comment.php",
data: 'act=add-com&id_post='+<?php echo $id_post; ?>+'&rating='+starrating.val()+'&comment='+theCom.val(),
success: function(html){
theCom.val('');
starrating.val('');
$('.new-com-cnt').hide('fast', function(){
$('.new-com-bt').show('fast');
$('.new-com-bt').before(html);
})
}
});
}
});
});
</script>
</div>
You can construct a query to check whether the user has already posted a comment on that particular page or not, and display the rating and comment box accordingly. Here's the code snippet,
// your code
$results = $db->query("SELECT * FROM rest_rating WHERE sr_id = '". $id_post . "' AND user ='". $users . "'");
if($results->num_rows){
// user has already posted a comment
echo '<p>You have already posted comment on this page</p>';
}else{
// user hasn't posted any comment on this page yet
// display rating and comment box
?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<input name="starrating" id="starrating" value="1" type="number" class="rating" min=0 max=5 step=1 data-size="xs2" >
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clear"></div>
</div><!-- end of comments container "cmt-container" -->
<?php
}
// your code

Script not working in a Form

I have been dealing with this issue and is a very stupid question but I really don't understand why my JavaScript functions never execute when I press the buttons I have tried everything please help thanks!!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript">
function validateForm()
{
var jArray= <?php echo json_encode($arr ); ?>;
var counter= <?php echo json_encode($i ); ?>;
var productId;
var productQty;
confirm(productId + " can not be empty");
for (i = 0; i < counter; i++) {
productQty = jArray[1][i];
productId= jArray[0][i];
if (document.getElementById("register").elements.namedItem("productId").value !== productQty) {
confirm(productId + " can not be empty");
}
}
}
</script>
<script type="text/javascript">
function myFunction1() {
alert("Hello! I am an alert box!");
}
</script>
</head>
>
<body>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<?php
$code1 ="";
$exeption="";
$s="";
session_start();
$arr=array();
$con = mysqli_connect('localhost','root','','customer_service_experts');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$empId= $_SESSION['eId'];
$sql2= "SELECT locationId FROM location_user where empId='".$empId."' and active ='1'";
$result2 = mysqli_query($con,$sql2);
while($row = mysqli_fetch_array($result2)){
$code1 = $row["locationId"];
}
mysqli_select_db($con,"customer_service_experts");
$sql="SELECT * FROM location_product where productLocation=$code1";
$result = mysqli_query($con,$sql);
echo "
<form action='productInventoryEmp.php' method='POST' id='register'>
<div class='form-group col-md-5'>
";
$i=0;
while($row = mysqli_fetch_array($result)) {
$arr[1][$i]=$row['productQty'];
$arr[0][$i]=$row['productId'];
$sql1="SELECT productName FROM product where productId='".$row['productId'] ."' limit 1 ";
$result1 = mysqli_query($con,$sql1);
if($result1!=false){
while($row = mysqli_fetch_array($result1)){
$code = $row["productName"];
echo " <div class='input-prepend'>";
echo "<span class='add-on' >".$code."</span>";
}
echo "<input type='number' min='0' step='1' data-bind='value:replyNumber' class='span2' id=" . $row['productId'] . "/>";
echo "</div>";
}else {
$s="1";
$exeption="There are no Products for in this location!";
}
echo "<br>";
echo "<br>";
$i++;
}
$_SESSION['ArrayCount']=$i; //counter
$_SESSION['ArrayProduct']=$arr; // ID Product y Qty
if ($s=="1") {
echo $exeption;
}
?>
</div>
<div class="col-md-6">
<div class="form-group">
<label for="comment">Note:</label>
<textarea class="form-control" rows="5" id="comment"></textarea>
</div>
<button type="submit" class="btn btn-default" onclick="validateForm()">Cancel</button>
<button type="submit" class="btn btn-default" onsubmit="myFunction1()">Save and Start Shift</button>
</div>
</form>
<?php
mysqli_close($con);
?>
</body>
</html>
Your buttons submit the form. That's why your functions never execute.
<button type="button" class="btn btn-default" onclick="validateForm()">Cancel</button>
<button type="button" class="btn btn-default" onclick="myFunction1()">Save and Start Shift</button>
Then set id to your form
<form id="myform" action="..">
And in the end of your functions, if you want to submit the form, set
$('#myform').submit();
And don't forget to include jquery library.
Hope it works!
Change this:
<button type="submit" class="btn btn-default" onclick="validateForm()">Cancel</button
<button type="submit" class="btn btn-default" onsubmit="myFunction1()">Save and Start Shift</button>
To this:
<input type="submit" class="btn btn-default" onclick="validateForm()" >Cancel
<input type="submit" class="btn btn-default" id="Save">Save and Start Shift
In your script:
$('#Save').on('click', function(){
myFunction1(); //your function
});

Jquery ajax add to mysql database

I want to save data from input fields to mysql database so first I create a modal window and input fields:
<!-- Button trigger modal -->
<button class="btn btn-success" data-toggle="modal" data-target="#myModal">
Add new</button>
<div id="output"></div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add new row</h4>
</div>
<div class="modal-body">
......
<div class="input-group">
<span class="input-group-addon">Ime</span>
<input type="text" id="Ime" class="form-control" placeholder="Upisi ime">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Pol</span>
<input type="text" id="pol" class="form-control" placeholder="Pol (male/female)">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Godine</span>
<input type="text" id="godine" class="form-control" placeholder="Godine starosti">
</div>
</br>
<div class="input-group">
<span class="input-group-addon">Broj pojedenih krofni</span>
<input type="text" id="krofne" class="form-control" placeholder="Pojedene krofne">
</div>
</br>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="newData" class="btn btn-primary">Add new data</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
Now I write jQuery AJAX code to add data to database:
<script>
//add data to database using jquery ajax
$("#newData").click(function() {
//in here we can do the ajax after validating the field isn't empty.
if($("#ime").val()!="") {
$.ajax({
url: "add.php",
type: "POST",
async: true,
data: { Name:$("#ime").val(), Gender:$("#pol").val(), Age:$("#godine").val(), Donuts_eaten:$("#krofne").val()}, //your form data to post goes here as a json object
dataType: "html",
success: function(data) {
$('#output').html(data);
drawVisualization();
},
});
} else {
//notify the user they need to enter data
}
});
</script>
and finally I create a php file (add.php)
<?php
$con = mysql_connect('localhost', 'gmaestro_agro', 'pass') or die('Error connecting to server');
mysql_select_db('gmaestro_agro', $con);
mysql_select_db('gmaestro_agro', $con);
$query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
$query .= mysql_real_escape_string($_POST['Name']) . ", ";
$query .= mysql_real_escape_string($_POST['Gender']) . ", ";
$query .= mysql_real_escape_string($_POST['Age']) . ", ";
$query .= mysql_real_escape_string($_POST['Donuts_eaten']);
$query .= ")";
$result = mysql_query($query);
if($result != false) {
echo "success!";
} else {
echo "an error occured saving your data!";
}
?>
Now, when I try to add data I just get this error: an error occurred saving your data!.
What is the problem here exactly? I try to find the error whole day...
You are not quoting your strings:
$query .= mysql_real_escape_string($_POST['Name']) . ", ";
should be:
$query .= "'" . mysql_real_escape_string($_POST['Name']) . "', ";
(for all string values)
By the way, it would probably make your life easier if you switched to PDO or mysqli and prepared statements. Then you would not have to escape and quote your variables and the mysql_* functions are deprecated anyway.
$query = "INSERT INTO `stat` (`Name`, `Gender`, `Age`, `Donuts eaten`) VALUES (";
$query .= "'".mysql_real_escape_string($_POST['Name']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Gender']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Age']) . "', ";
$query .= "'".mysql_real_escape_string($_POST['Donuts_eaten']);
$query .= "')";
Put all the values in single quotes.

Categories