I'm trying to submit values to a database using jquery. I'm new to ajax but I'm required to do it with ajax.
This is what I've done so far my php code is
function insertSeries()
{
$options = array(
'user' => $_POST['user'],
'email' => $_POST['email'],
'summary' => $_POST['summary'],
'due_date' => $_POST['due_date'],
'problem_type' => $_POST['problem_type'],
'status' => $_POST['status']
);
$sql = "insert into ticket_summary('user','email','summary','due_date','problem_type','status') Values (?,?,?,?,?,?)";
$result = mysql_query($sql, $options) or die('Could not insert data');
}
My html code is
<?php
include 'eric_api.php';
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="js/jquery.js"></script>
<script src="js/api_calls.js"></script>
<link rel="stylesheet" href="css/normalizer.css" />
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<div class="wrapper">
<h1>Ticketing System</h1>
<div>
<div id="ticket_form_wrapper">
<form id="insert_ticket" method="post" action="">
<p>
<label for="user">User</label>
<br />
<input type="user" id="user" class="post_fields" />
</p>
<p>
<label for="email">Email</label>
<br />
<input type="email" id="email" class="post_fields" />
</p>
<p>
<label for="summary">Summary</label>
<br />
<input type="summary" id="summary" class="post_fields" />
</p>
<p>
<label for="due_date">Due Date</label>
<br />
<input type="due_date" id="due_date" class="post_fields" />
</p>
<p>
<label for="problem_type">Problem Type</label>
<br />
<input type="problem_type" id="problem_type" class="post_fields" />
</p>
<p>
<label for="status">Status</label>
<br />
<input type="status" id="status" class="post_fields" />
</p>
<p>
<input type="submit" id="submit" value="Submit" />
<input type="button" onclick="window.location='index.php'" value="Go to List"/>
<div class="form_result"> </div>
</p>
</form>
</div>
</div>
</body>
</html>
And here's my ajax using jquery
$('#insert_ticket').submit(function(e){
var postData = $(this).serialize();
alert(postData);
$.ajax({
type: 'POST',
url: 'http://localhost/api/eric_api.php?q=insertseries',
data: postData,
success: function(response){
$('#insert_ticket').find('.form_result').html(response);
},
error: function(){
alert('error');
}
});
e.preventDefault();
});
I don't know what I'm doing wrong. Any help would be greatly appreciated
Instead of interfering with the form's submit event, interfere with a click event instead. To make minimal changes to your existing setup, just add the click handler to the form submit button. First thing inside of the handler, call e.preventDefault(). You'll have to explicitly select the form inside the handler to serialize the data. Then, move your existing ajax call into that handler, and it should work fine. Also, make sure that you are actually calling insertSeries() somewhere in your PHP code.
Cheers
Please reply to some of the comments so we can help figure out what the issues is. This is how your function would look with proper mysqli syntax.
How to make the connection:
$mysql = new mysqli(...)
How to prepare the statement: $stmt = $mysqi->prepare(....)
How to bind the parameters: $stmt->bind_param(...)
Execution: $stmt->execute()
Note: you were making your insert string like it was to be used for mysqli but your parameter binding was more similiar to pdo. I wasn't sure which one you were wanting to use so I chose mysqli. I personally prefer PDO, though... so I can re-write this using that if you want. Link to the PDO Prepare Function that also shows some binding.
// this is your database connection for mysqli
$mysqli = new mysqli('localhost', 'my_user', 'my_password', 'world');
function insertSeries($mysqli)
{
$options = array(
'user' => $_POST['user'],
'email' => $_POST['email'],
'summary' => $_POST['summary'],
'due_date' => $_POST['due_date'],
'problem_type' => $_POST['problem_type'],
'status' => $_POST['status']
);
$sql = "insert into ticket_summary('user','email','summary','due_date','problem_type','status')
Values (?, ?, ?, ?, ?, ?)";
if ( $stmt = $mysqli->prepare($sql) )
{
$stmt->bind_param("ssssss", $options['user'], $options['email'],
$options['summary'], $options['due_date'],
$options['problem_type'], $options['status']);
$success = $stmt->execute();
if ($success) { print "query worked"; }
else { print "query failed"; }
}
}
Related
I have this code with multiple forms within the same page:
test1 page:
<select id="mudar_produto">
<option value="#produto_1">Novo Produto Higiene</option>
<option value="#produto_2">Entrada de Produtos Higiene</option>
<option value="#produto_3">Novo Produto Nutricia</option>
</select>
<section class="hide-section" id="produto_1">
<form id="form3" action="./teste2" method="POST" onsubmit="return form_validation()">
<fieldset>
<h1>
<legend>
<center>
<strong>Produtos de Higiene</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Nome do Produto">Nome do Produto</label></strong>
<input type="text" id="DescricaoProd" name="DescricaoProd" required="" style="width:350px">
</div>
<div class="campo">
<strong><label for="Unidade">Unidade</label></strong>
<input type="text" id="DescricaoUnid" name="DescricaoUnid" style="width:160px" required="" size="120">
</div>
</fieldset>
<button type="submit" name="submit" class="botao submit">Registo</button>
</form>
</section>
<section class="hide-section" id="produto_2">
<form name="form4" action="./teste2" method="POST" onsubmit="return form_validation()">
<fieldset>
<h1>
<legend>
<center>
<strong>Entrada de Produtos de Higiene</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Data Entrada">Data Entrada</label></strong>
<input id="DataEntrada" type="date" name="DataEntrada" required="" style="width:180px" value="<?php echo date("Y-m-d");?>">
</div>
</fieldset>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Produto">Produto</label></strong>
<select id="first_dd" name="Produto" style="width:250px" required>
<option></option>
<?php
$sql = "SELECT * FROM centrodb.ProdHigieneteste WHERE Ativo = 1 ORDER BY DescricaoProd ASC";
$qr = mysqli_query($conn, $sql);
while($ln = mysqli_fetch_assoc($qr)){
echo '<option value="'.$ln['IDProd'].'"> '.$ln['DescricaoProd'].'</option>';
$valencia[$ln['IDProd']]=array('DescricaoUnid'=>$ln['DescricaoUnid'],'DescricaoUnid'=>$ln['DescricaoUnid']);
}
?>
</select>
</div>
<div class="campo">
<strong><label for="Unidade">Unidade</label></strong>
<select id="second_dd" name="Unid" style="width:150px" required>
<option></option>
<?php
foreach ($valencia as $key => $value) {
echo '<option data-id="'.$key.'" value="'.$value['DescricaoUnid'].'">'.$value['DescricaoUnid'].'</option>';
}
?>
</select><br>
</div>
</fieldset>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Quantidade">Quantidade</label></strong>
<input type="text" id="Quantidade" name="Quantidade" style="width:80px" required="" size="40">
</div>
<div class="campo">
<strong><label for="Preço">Preço</label></strong>
<input type="text" id="Preco" name="Preco" style="width:100px" value="0.00">
</div>
</fieldset>
<button type="submit" name="submit1" class="botao submit">Registo</button>
</form>
</section>
<section class="hide-section" id="produto_3">
<form id="form3" name="form3" action="./teste2" method="POST" onsubmit="return form_validation()" >
<fieldset>
<h1>
<legend>
<center>
<strong>Produtos de Nutricia</strong>
</center>
</h1><br>
<fieldset class="grupo">
<div class="campo">
<strong><label for="Nome do Produto">Nome do Produto</label></strong>
<input type="text" id="ProdNutricia" name="ProdNutricia" style="width:350px" required="" size="120" />
</div>
</fieldset>
<button type="submit" name="submit2" class="botao submit">Registo</button>
</form>
</section>
In the page teste2 I make the insertion of the data in the table of the database:
<script language="javascript" type="text/javascript">
document.location = "teste1";
</script>
<?php
if(isset($_POST['submit'])){
$name = $_POST['DescricaoProd'];
$unid = $_POST['DescricaoUnid'];
$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid)
VALUES ('$name','$unid')";
if ($conn->query($sql) === TRUE);
$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid)
VALUES ('$name','$unid')";
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
<?php
if(isset($_POST['submit1'])){
$data = $_POST['DataEntrada'];
$produto = $_POST['Produto'];
$unidade = $_POST['Unid'];
$quantidade = $_POST['Quantidade'];
$preco = $_POST['Preco'];
$sql = "INSERT INTO regEntradahigieneteste (DataEntrada,Produto,Unid,Quantidade,Preco)
VALUES ('$data','$produto','$unidade','$quantidade','$preco')";
if ($conn->query($sql) === TRUE);
$sql1 = "UPDATE StockHigieneteste SET Quantidade = Quantidade +" . $quantidade . " WHERE StockHigieneteste.IDProd =" . $produto;
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
<?php
if(isset($_POST['submit2'])){
$name = $_POST['ProdNutricia'];
$sql = "INSERT INTO ProdNutriciateste (ProdNutricia)
VALUES ('$name')";
if ($conn->query($sql) === TRUE);
$sql1 = "INSERT INTO StockNutriciateste (ProdNutricia)
VALUES ('$name')";
if ($conn->query($sql1) === TRUE);
//Count total number of rows
$rowCount = $query->num_rows;
header("Location: teste1");
$conn->close();
}
?>
Everything is working correctly with the insertion of data in the table, but when I do the insertion and does the header ("Location: teste1"); closes the form I was filling out and I want to keep it open, since I may have to insert several types of products on the same form.
Some explanation to start with:
I have cleaned up your HTML markup. You may have gotten the look you desired, but the markup is badly broken. A good editor will help you with making a well-formed document that validates.
I've used Bootstrap for styling. Foundation is another good choice.
JQuery is used as the basis for Javascript event monitoring and AJAX
This is not copy and paste code. It's untested; it's purpose is to point you in the right direction.
The code is commented to help you understand what it's doing.
Since this is how SO is showing the code, we start off with the javascript and the HTML:
// this delays execution until after the page has loaded
$( document ).ready(function() {
// this monitors the button, id=submit-form-1, for a click event
// and then runs the function, submitForm1()
$('#submit-form-1').on('click', function() {
submitForm('#form1');
});
// could be repeated for another form...
$('#submit-form-2').on('click', function() {
submitForm('#form2');
});
});
// this function does an AJAX call to "insert.php".
// it expects a reply in JSON.
function submitForm(whichForm) {
var datastring = $(whichForm).serialize();
// see what you're sending:
alert('You would be sending: ' + datastring);
$.ajax({
type: "POST",
url: "insert.php",
data: datastring,
dataType: "json",
success: function(data) {
if(data.status=='success') {
alert('successfully uploaded');
} else {
alert('failed to insert');
}
},
error: function() {
alert("This example can't actually connect to the PHP script, so this error appears.");
}
});
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="produto_1">
<!--
note that the form is identified with id="form1".
"id" has to be unique. Nothing else can have id="form1".
There are no action nor method attributes,
since AJAX is submitting the form contents.
-->
<form class="form-horizontal" id="form1">
<!--
field named "action" will be used in PHP script
-->
<input type="hidden" name="action" value="insert_form_1" />
<!-- use CSS for styling, not <center>, <strong>, etc. -->
<h1 class="text-center">Produtos de Higiene</h1>
<div class="form-group">
<label for="DescricaoProd" class="col-sm-2 control-label">Nome do Produto</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="DescricaoProd" name="DescricaoProd" required />
</div>
</div>
<div class="form-group">
<label for="DescricaoUnid" class="col-sm-2 control-label">Unidade</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="DescricaoUnid" name="DescricaoUnid" required />
</div>
</div>
<div class="form-group">
<div class="col-sm-2">
<!--
button type is button, not submit.
Otherwise the form will try to submit.
We want the javascript to submit, not the form.
-->
<button type="button" id="submit-form-1" class="btn btn-success">Registo</button>
</div>
</div>
</form>
</section>
<!-- set up another form in the same way... -->
<form id="form2">
<input type="hidden" name="action" value="insert_form_2" />
...
<button type="button" id="submit-form-2">submit form 2</button>
</form>
The above markup and javascript should make an AJAX POST request to insert.php, and listen for a reply.
insert.php
<?php
/**
* note: It is a good practice to NEVER have anything before the <?php tag.
*
* Always try to separate logic from presentation. This is why you should
* start with PHP on the top, and never do any output until you are done
* with processing. Better yet, have separate files for logic and presentation
*
*/
// if $_POST doesn't have ['action'] key, stop the script. Every request will have
// an action.
if(!array_key_exists('action', $_POST)) {
die("Sorry, I don't know what I'm supposed to do.");
}
// database initialization could (should) go on another page so it can be reused!
// set up PDO connection
// this section credit to https://phpdelusions.net/pdo
// use your credentials here...
$host = '127.0.0.1';
$db = 'your_db_name';
$user = 'root';
$pass = '';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
// helpful initializations, such as default fetch is associative array
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
// instantiate database
$pdo = new PDO($dsn, $user, $pass, $opt);
// end database initialization
// whenever you have to do something over again, break it out into a function
// this function prevents warnings if the variable is not present in $_POST
function get_post($var_name) {
$out = '';
if(array_key_exists($var_name,$_POST)) {
$out = $_POST[$var_name];
}
return $out;
}
// assign variables
$action = get_post('action');
$name = get_post('DescricaoProd');
$unid = get_post('DescricaoUnid');
// All output of this script is JSON, so set the header to make it so.
// There can be NO output before this!
// Not even a blank line before the <?php start tag.
header('Content-Type: application/json');
// take action based on value of "action".
if($action=='insert_form_1') {
$error = false;
$output = array('message' => 'success');
// Use placeholders, never (NEVER NEVER NEVER) php variables!
$sql = "INSERT INTO ProdHigieneteste (DescricaoProd,DescricaoUnid) VALUES (?,?)";
$pdo->prepare($query);
$result = $pdo->execute([$name, $unid]); // don't miss the [] which is a shortcut for array()
if(!$result) { $error = true; }
$sql1 = "INSERT INTO StockHigieneteste (DescricaoProd,DescricaoUnid) VALUES (?,?)";
$pdo->prepare($query);
$result = $pdo->execute([$name, $unid]); // don't miss the [] which is a shortcut for array()
if(!$result) { $error = true; }
// note, I just repeated myself, so this probably should be refactored...
// send a message back to the calling AJAX:
if($error) {
$output = array('status' => 'failed');
} else {
$output = array('status' => 'success');
}
print json_encode($output);
die; // nothing more to do
}
// you could have additional actions to perform in the same script.
// or, you could use different files...
if($action=='insert_form_2') {
// do insert for form 2
}
// etc.
I am using PHP 5.6.30 version..when I try to execute the following code data is inserted twice.i am using register.php as view and app.js for http post service.
insert.php (database connection)
<?php
$connect = mysqli_connect("localhost", "root", "","user");
$data = json_decode(file_get_contents("php://input"));
$first_name = mysqli_real_escape_string($connect, $data->firstname);
$last_name = mysqli_real_escape_string($connect, $data->lastname);
$user_name = mysqli_real_escape_string($connect, $data->username);
$emailid = mysqli_real_escape_string($connect,$data->emailid);
$password = mysqli_real_escape_string($connect,$data->password);
$mobile = mysqli_real_escape_string($connect,$data->mobile);
$query = "INSERT INTO register(fname,lname,uname,email,pass,mobile)
VALUES ('$first_name','$last_name','$user_name','$emailid','$password','$mobile')";
$result = mysqli_query($connect, $query) ;
if($result == TRUE)
{
echo "Data Inserted...";
}
else
{
echo 'Error';
}
?>
register.php:
enter code here
<html>
<head><title>Nav</title>
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-
route.js"></script>
<link rel="stylesheet" type="text/css" href="css/header.css"/>
<script src="app.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="RegisterController">
<form ng-submit="rsubmit()" class="rform">REGISTER
<input type="text" class="form-control" name="firstname" ng-
model="firstname" placeholder="firstnamesss" ><br>
<input type="text" class="form-control" name="lastname" ng-
model="lastname" placeholder="lastname" ><br>
<input type="text" class="form-control" name="username" ng-model="username" placeholder="username"><br>
<input type="text" class="form-control" name="emailid" ng-model="emailid" placeholder="emailid" ><br>
<input type="text" class="form-control" name="password" ng-model="password" placeholder="password" required=""/><br>
<input type="text" class="form-control" name="mobile" ng-model="mobile" placeholder="mobileno" ><br>
<button ng-click="rsubmit()" >Register</button>
Cancel
<br></h2>
</form>
</div>
</body>
</html>
app.js:
var app = angular.module('myApp', ['ngRoute']);
app.controller('RegisterController',function($scope,$http){
$scope.rsubmit=function(){
$http.post("insert.php" ,{
'firstname':$scope.firstname,
'lastname':$scope.lastname,
'username':$scope.username,
'emailid':$scope.emailid,
'password':$scope.password,
'mobile':$scope.mobile,
} )
.success(function(data){
alert(data);
$scope.firstname = null;
// $scope.lastname = null;
});
}
});
From the documentation:
Warning: Be careful not to cause "double-submission" by using both the ngClick and ngSubmit handlers together. See the form directive documentation for a detailed discussion of when ngSubmit may be triggered.
In your code you use both ng-submit and ng-click, so you trigger the controller (the request) twice. Just remove the ngClick attribute on the button/ input field and it should work.
Just remove the ng-click from the button..Button used inside the form always submit the form..So you call the rsubmit function when click the button at same time when you click the button the form is going to submission.The form submission call again the rsubmit function..
Two types of ways for it
1.<button type="button" ng-click="rsubmit()" >Register</button> - It disable the form submission power of button when you use type="button"
(or)
2.Skip the action attribute from the form.
I am making a helpdesk page where i have page to raise a ticket. I have form where i want Issue Type & Query field to be filled mandatory & validate data for extension no. i.e it should be in no. only.
I have tried code to get it via ajax & form validation but not able to execute the code & values are not getting inserted into the mysql db.
Please Help !
Ticket.php
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Raise Ticket</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
// Form validation.
if ($('.validate-issue').val() === '') { $('.issue-error').fadeIn(); }
if ($('.validate-query').val() === '') { $('.query-error').fadeIn(); }
// Grab form values
var formData = {
'ename' : $('input[name=ename]').val(),
'date' : $('input[name=date]').val(),
'ext' : $('input[name=ext]').val(),
'issue' : $('select[name=issue]').val(),
'query' : $('input[name=query]').val(),
'upload' : $('input[name=upload]').val()
};
if($('.validate-issue').val().trim()) &&($('.validate-query').val().trim()){
// Ajax form submit.
$.ajax({
type: "POST",
url: "insertticket.php",
data: formData,
success: function()
{
alert('Ticket has been raised');
}
});
} else { alert('Please enter the mandatory fields'); } });
});
</script>
</head>
<body>
<div class="container">
<div class="panel panel-default">
<div class="panel-heading"><h1 align="center">Helpdesk-Support</h1></div>
<hr>
<div class="panel-body" align="center">
<h2>Raise Ticket!</h2>
<form class="form-horizontal" role="form" enctype="multipart/form-data" method="post">
<div class="form-group">
<label class="control-label col-sm-2" for="text">Name:</label>
<div class="col-sm-10">
<input type="text" disabled class="form-control" id="text" name="ename" value="<?php echo ucwords($_SESSION['usr_name']); ?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="date">Date:</label>
<div class="col-sm-10">
<input type="text" class="form-control" disabled id="date" name="date" value="<?php date_default_timezone_set("Asia/Calcutta"); echo date('Y-m-d H:i:s')?>">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="ext">Extension No.:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="ext" name="ext" placeholder="Enter Extension No.">
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="issue">Issue Type:</label>
<div class="col-sm-10">
<select class="form-control" id="validate-issue" name="issue"><span class="issue-error">Enter Issue Type</span>
<option>Select an option</option>
<option>Hardware Issue</option>
<option>Network Issue</option>
<option>Software Issue</option>
<option>ERP</option>
<option>CRM</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="query">Query:</label>
<div class="col-sm-10">
<textarea rows="5" class="form-control" id="validate-query" name="query" placeholder=" Enter Query here"></textarea><span class="query-error">Enter Detailed Query</span>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="text">Upload File:</label>
<div class="col-sm-10">
<input type="file" class="form-control" id="filetoupload" name="upload" >
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
<button type="reset" class="btn btn-default">Reset</button>
</div>
</div>
</form>
</div>
<hr>
<div class="panel-footer" align="center">© Copyright <?php echo date("Y");?></div>
</div>
</div>
</body>
</html>
insertticket.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="helpdesk"; // Database name
// Connect to server and select database.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$emp_name = mysqli_real_escape_string($conn, $_POST['ename']);
$date = mysqli_real_escape_string($conn, $_POST['date']);
$issue_type = mysqli_real_escape_string($conn, $_POST['issue']);
$query = mysqli_real_escape_string($conn, $_POST['query']);
$ext_no. = mysqli_real_escape_string($conn, $_POST['ext']);
$attachment = mysqli_real_escape_string($conn, $_POST['upload']);
$sqli="select * from user where name='$emp_name'";
$result=mysqli_query($conn,$sqli);
while($row=mysqli_fetch_array($result))
{
$emp_code=$row['emp_code'];
$dept=$row['dept'];
$location=$row['location'];
$emailid=$row['emailid'];
$contact_no.=$row['contact_no.'];
}
$sql="INSERT INTO ticket (ticket_no.,emp_code,emp_name,dept,location,emailid,contact_no.,date,issue_type,query,ext_no.,attachment)
VALUES('','$emp_code','$emp_name','$dept','$location','$emailid','$contact_no.','$date','$issue_type','$query','$ext_no.','$attachment')";
if (mysqli_query($conn,$sql))
{
echo "Record added";
}
else
{
die('Error: ' . mysqli_error());
}
?>
Your triggering your script on its first load only. You can try .submit() of jQuery.
I'm not also certain if you can upload files just by getting its content by name/class/id.
Isn't .trim() just for removing extra spaces, and not for checking content?
What is up with those dots(.) in your column names anyway?
You should use $_FILES["upload"]["name"] instead of $_POST["upload"] for getting the file name attached by the user
Where is your code for uploading the file?
You can try required attribute of HTML for the meantime:
<input required="true" type="text" disabled class="form-control" id="text" name="ename" value="<?php echo ucwords($_SESSION['usr_name']); ?>">
And why don't we try .submit() in your case:
First, we have to give a unique data attribute for your <form> by adding an id attribute.
<form id="form-submission" class="form-horizontal" role="form" enctype="multipart/form-data" method="post">
Then for your script:
$(document).ready(function(){
$("form#form-submission").submit(function(){ /* WHEN THE FORM IS SUBMITTED */
var formData = new FormData($(this)[0]); /* ALL THE DATA IS IN HERE INCLUDING THE FILE ATTACHED */
$.ajax({ /* CALL AJAX */
url: "insertticket.php", /* THE FILE WHERE THE DATA WILL GO */
type: "POST", /* TYPE OF METHOD TO BE USED TO PROCESS THE DATA */
data: formData, /* THE DATA TO BE PROCESSED */
contentType: false, /* TYPE OF DATA TO BE PASSED; FOR FILE PURPOSES THAT IS WHY IT IS SET TO FALSE */
processData: false, /* PREVENT AUTOMATIC PROCESSING */
success: function(result){ /* IF DATA IS PROCESSED SUCCESSFULLY */
alert(result); /* ALERT THE RETURNED DATA FROM inserticket.php */
}
});
return false;
});
});
You're also already using mysqli_, so its easier to convert your code to prepared statement instead.
This is your insertticket.php:
<?php
$conn = new mysqli("localhost", "root", "", "helpdesk");
/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if($stmt = $con->prepare("SELECT emp_code, dept, location, emailid, contact_no FROM user WHERE name = ?")){ /* PREPARE YOUR QUERY */
$stmt->bind_param("s", $_POST["ename"]); /* BIND THIS DATA TO YOUR QUERY, REPLACING ? WITH $_POST["ename"]; s STANDS FOR STRING TYPE */
$stmt->execute(); /* EXECUTE QUERY */
$stmt->bind_result($emp_code, $dept, $location, $emailid, $contact_no); /* BIND THE RESULTS TO THESE VARIABLES CORRESPONDINGLY */
$stmt->fetch(); /* FETCH THE RESULT */
$stmt->close(); /* CLOSE THE PREPARED STATEMENT */
}
if($stmt = $con->prepare("INSERT INTO ticket (emp_code, emp_name, dept, location, emailid, contact_no, date, issue_type, query, ext_no, attachment) VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")){
$stmt->bind_param("sssssssssss", $emp_code, $_POST["ename"], $dept, $location, $emailid, $contact_no, $_POST["date"], $_POST["issue"], $_POST["query"], $_POST["ext"], $_FILES["upload"]["name"]);
$stmt->execute();
$stmt->close();
echo 'Record added';
}
move_upload_file($_FILES["upload"]["tmp_name"], "/system/uploads/".$_FILES["upload"]["name"]); /* UPLOAD THE FILE TO /system/uploads/ FOLDER; JUST REPLACE YOUR DESIRED DIRECTORY */
?>
Always take a look at your browser's console log for errors
You should also consider renaming the uploaded file by the user through your code so that it will be unique inside your folder and database. To prevent duplicate file name that would lead to overwriting of files
i want to create a web service to check if the login
i create first an html form
<form action="webservice_ocl.php" method="post">
<p>Username:
<input name="user" type="text" />
</p>
<p>
Password:
<input name="password" type="password" />
</p>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</p>
</form>
then i create a php file " webservice_ocl.php to do the traitement
<?php
session_start();
try {
$dbh = oci_connect('test', '123456', 'localhost/XE');
} catch (PDOException $e)
{
echo $e->getMessage();
}
if ($_POST['user'] != null and $_POST['user'] != "" and $_POST['password'] != null and $_POST['password'] != "")
{
$username = $_POST['user'];
$password = $_POST['password'];
$sth = oci_parse($dbh ,"SELECT * FROM utilisateur WHERE LOGIN='$username' and PASS='$password'");
oci_execute($sth);
if(oci_fetch($sth)){
echo "Nice";
}
else { echo "nono";}
}
?>
i want to konw , the php file " webservice_ocl.php " is a webservice ??
and how to call them in html using ajax ??
i want to use this on mobile developpement
I wouldn't really class webservice_ocl.php as a webservice as such, a webservice (in my opinion) is usually an SOAP/REST complaint API. See http://en.wikipedia.org/wiki/Web_service.
As for calling this with AJAX, I would personally look into jquery - namely the $.post function, I use this all the time and find it much easier than plain javascript.
Lastly, i would advise you look at how you have wrote your SQL statements - as pointed out by Quentin you are vulnerable for injection, which I have had done before (whoops) and believe me it is not nice!
Hope this helps.
Smithey.
Edit - If your looking at mobile apps, take a look at jquery mobile ;). I'm using it for a project im working on at the minute, its pretty cool!
====== in form.html change type="submit" to type="button" and delete action+mithod attr
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
<form id="my-form" >
<p>Username:
<input name="user" type="text" />
</p>
<p>
Password:
<input name="password" type="password" />
</p>
<p>
<input type="submit" name="btnSubmit" id="btnSubmit" value="Submit" />
</p>
</form>
<div id=result >the result will display here</div>
<script type="text/javascript">
$("#btnSubmit").click({
$.post(
"webservice_ocl.php",
$("#my-form").serialize(),
function(data){ $("#result").html(data); }
);
});
</script>
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I'm trying to make a registration form. If you can give me some tips if my code is wrong or not proper
it still showing me this prepare
($sqlinsert); $user = $_POST['user']; $pass = $_POST['pass']; $email = $_POST['email']; $lname = $_POST['lname']; $fname = $_POST['fname']; $stmt->bind_param($user, $pass, $email, $lname, $fname); $stmt->execute(); $rowcount = $stmt->affected_rows; if ($rowcount > 0) { echo "Success!"; } else { echo "Error!"; } //CLOSE EXECUTE $stmt->close(); ?>
Here is my code:
<?php
$mysqli = new mysqli('local','root','','dbtform');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
$sqlinsert = "INSERT INTO tblform (user, pass, email, lname, fname)
VALUES ('sssss',?,?,?,?,?)";
$stmt = $mysqli->prepare($sqlinsert);
$user = $_POST['user'];
$pass = $_POST['pass'];
$email = $_POST['email'];
$lname = $_POST['lname'];
$fname = $_POST['fname'];
$stmt->bind_param($user, $pass, $email, $lname, $fname);
$stmt->execute();
$rowcount = $stmt->affected_rows;
if ($rowcount > 0)
{
echo "Success!";
}
else
{
echo "Error!";
}
//CLOSE EXECUTE
$stmt->close();
?>
<head>
<title>Animated Form Switching with jQuery</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<meta name="description" content="Expand, contract, animate forms with jQuery wihtout leaving the page" />
<meta name="keywords" content="expand, form, css3, jquery, animate, width, height, adapt, unobtrusive javascript"/>
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon"/>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script src="js/cufon-yui.js" type="text/javascript"></script>
<script src="js/ChunkFive_400.font.js" type="text/javascript"></script>
<script type="text/javascript">
Cufon.replace('h1',{ textShadow: '1px 1px #fff'});
Cufon.replace('h2',{ textShadow: '1px 1px #fff'});
Cufon.replace('h3',{ textShadow: '1px 1px #000'});
Cufon.replace('.back');
</script>
</head>
<body>
<div class="wrapper">
<h1>Rythreion</h1>
<h2>Demo: click the <span>orange links</span> to see the form animating and switching</h2>
<div class="content">
<div id="form_wrapper" class="form_wrapper">
<form class="register">
<h3>Register</h3>
<div class="column">
<div>
<label>First Name:</label>
<input type="text" name="fname" />
<span class="error">This is an error</span>
</div>
<div>
<label>Last Name:</label>
<input type="text" name="lname"/>
<span class="error">This is an error</span>
</div>
</div>
<div class="column">
<div>
<label>Username:</label>
<input type="text" name="user"/>
<span class="error">This is an error</span>
</div>
<div>
<label>Email:</label>
<input type="text" name="email"/>
<span class="error">This is an error</span>
</div>
<div>
<label>Password:</label>
<input type="password" name="pass" />
<span class="error">This is an error</span>
</div>
</div>
<div class="bottom">
<div class="remember">
<input type="checkbox" />
<span>Send me updates</span>
</div>
<input type="submit" value="Register" />
You have an account already? Log in here
<div class="clear"></div>
</div>
</form>
<form class="login active">
<h3>Login</h3>
<div>
<label>Username:</label>
<input type="text" name="user" />
<span class="error">This is an error</span>
</div>
<div>
<label>Password: Forgot your password?</label>
<input type="password" name="pass" />
<span class="error">This is an error</span>
</div>
<div class="bottom">
<div class="remember"><input type="checkbox" /><span>Keep me logged in</span></div>
<input type="submit" value="Login"></input>
You don't have an account yet? Register here
<div class="clear"></div>
</div>
</form>
<form class="forgot_password">
<h3>Forgot Password</h3>
<div>
<label>Email:</label>
<input type="text" name="email" />
<span class="error">This is an error</span>
</div>
<div class="bottom">
<input type="submit" value="Send reminder"></input>
Suddenly remebered? Log in here
You don't have an account? Register here
<div class="clear"></div>
</div>
</form>
</div>
<div class="clear"></div>
</div>
<a class="back" href="http://google.com">back to the Codrops tutorial</a>
</div>
<!-- The JavaScript -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
//the form wrapper (includes all forms)
var $form_wrapper = $('#form_wrapper'),
//the current form is the one with class active
$currentForm = $form_wrapper.children('form.active'),
//the change form links
$linkform = $form_wrapper.find('.linkform');
//get width and height of each form and store them for later
$form_wrapper.children('form').each(function(i){
var $theForm = $(this);
//solve the inline display none problem when using fadeIn fadeOut
if(!$theForm.hasClass('active'))
$theForm.hide();
$theForm.data({
width : $theForm.width(),
height : $theForm.height()
});
});
//set width and height of wrapper (same of current form)
setWrapperWidth();
/*
clicking a link (change form event) in the form
makes the current form hide.
The wrapper animates its width and height to the
width and height of the new current form.
After the animation, the new form is shown
*/
$linkform.bind('click',function(e){
var $link = $(this);
var target = $link.attr('rel');
$currentForm.fadeOut(400,function(){
//remove class active from current form
$currentForm.removeClass('active');
//new current form
$currentForm= $form_wrapper.children('form.'+target);
//animate the wrapper
$form_wrapper.stop()
.animate({
width : $currentForm.data('width') + 'px',
height : $currentForm.data('height') + 'px'
},500,function(){
//new form gets class active
$currentForm.addClass('active');
//show the new form
$currentForm.fadeIn(400);
});
});
e.preventDefault();
});
function setWrapperWidth(){
$form_wrapper.css({
width : $currentForm.data('width') + 'px',
height : $currentForm.data('height') + 'px'
});
}
/*
for the demo we disabled the submit buttons
if you submit the form, you need to check the
which form was submited, and give the class active
to the form you want to show
*/
$form_wrapper.find('input[type="submit"]')
.click(function(e){
e.preventDefault();
});
});
</script>
</body>
</html>
If you can give me some tips if my code is wrong or not proper
Sure.
Your code is both wrong and improper because it is using mysqli.
You have to use PDO instead.
Just a sketch to give you an idea:
first, create a connection
$dsn = 'mysql:dbname=test;host=localhost;charset=utf8';
$opt = array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
);
$pdo = new PDO($dsn, $user, $pass, $opt);
then, run your query
$sql = "INSERT INTO tblform (user, pass, email, lname, fname) VALUES (?,?,?,?,?)";
$stmt = $pdo->prepare($sql);
$stmt->execute($_POST); // you may wish to unset non-used fields from POST first
if ($stmt->rowCount())
{
echo "Success!";
}