while i am making the point of sale system i ran in to problem with the search.
when i enter the product code on the product code textbox it automatically Search and display product name and price in to the relevant textboxes using ajax and jquery and php. what i tried code i attached below. i didn't get any answer while i ran the code.please read the below code and get good solution for me as soon as possible.
Form Design
<div class="form-group">
<label for="" class="col-sm-2 control-label">Product Code</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="product_code" name="product_code" placeholder="Product Code" required>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Product Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="product_name" name="product_name" placeholder="product_name " required>
</div>
</div>
<div class="form-group">
<label for="" class="col-sm-2 control-label">Price</label>
<div class="col-sm-10">
<input type="text" class="form-control price" id="price" name="price" placeholder="price" required>
</div>
</div>
AJAX
function getProductcode() {
$('#product_code').empty();
$("#product_code").keyup(function(e) {
var q = $("#product_code").val();
$.ajax({
type: 'POST',
url: '../php/project_module/get_purchase.php',
dataType: 'JSON',
async: false,
success: function(data) {
for (var i = 0; i < data.length; i++) {
$('#product_code').append($("<option/>", {
value: data[i].product_id,
text: data[i].product_name,
}));
}
data: {
product_code: $('#product_code').val()
},
}
},
error: function(xhr, status, error) {
alert(xhr.responseText);
//
}
});
}
**get_purchase.php**
$product_code = $_POST["product_code"];
$stmt = $conn->prepare("select product_id,product_name,barcode,category,description,warrenty,product_condition,price_retail,
price_cost,discount,reorderlevel,brand
from product where barcode = ?");
$stmt->bind_param("s", $product_code);
$stmt->bind_result($product_id,$product_name,$price);
if ($stmt->execute()) {
while ( $stmt->fetch() ) {
$output[] = array ("product_id"=>$product_id,"product_name"=>$product_name,"price_retail"=>$price);
}
echo json_encode( $output );
}
$stmt->close();
The data attribute is in the wrong place of the ajax configuration.
Here is a revised version
Add this to your HTML
<p id="output"></p>
And this as your getProductCode() definition
function getProductcode() {
$("#product_code").empty();
$("#product_code").keyup(function(e) {
var q = $("#product_code").val();
$.ajax({
type: "POST",
url: "../php/project_module/get_purchase.php",
dataType: "JSON",
data: { product_code: $("#product_code").val() },
success: function(data) {
if(typeof data === 'undefined'){
return
}
$("#output").val(data[0].product_id + " : " +data[0].product_name)
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
});
});
}
I pasted your code in my editor (VS Code) and it gave helpful syntax errors. Maybe it would be a good idea to look into editors with syntax highlighting and checking capabilities?
Related
I have a jQuery function that does the insert of an image with other fields to the database. Currently my function only inserts the image but does not insert the other form fields. I am using formData object and I don't understand how to append my fields together with the image file so I can pass it to the ajax request body.
Here is what I have tried so far:
// submit function
function Submit_highschool() {
jQuery(document).ready(function($) {
$("#highschool").submit(function(event) {
event.preventDefault();
$("#progress").html(
'Inserting <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');
var formData = new FormData($(this)[0]);
var firstname_h = $("#firstname_h").val();
var middlename_h = $("#middlename_h").val();
formData.append(firstname_h, middlename_h);
$.ajax({
url: 'insertFunctions/insertHighSchool.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function(returndata) {
alert(returndata);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
return false;
});
});
}
// html form
<form method="post" enctype="multipart/form-data" id="highschool">
<div class="card" id="highschool">
<div class="col-3">
<label for="firstname">First name *</label>
<input type="text" class="form-control" id="firstname_h" placeholder="First name" />
</div>
<div class="col-3">
<label for="middlename">Middle name *</label>
<input type="text" class="form-control" id="middlename_h" placeholder="Middle name" />
</div>
<div class="col-6">
<label for="grade11_h">Grade 11 Transcript (image) *</label>
<input type="file" class="form-control" name="grade11_h" id="grade11_h" accept=".png, .jpg, .jpeg">
</div>
<button type="submit" name="submit" class="btn btn-primary float-right" onclick="Submit_highschool();">Submit</button>
</div>
</form>
The image name is succesfully inserted in the db and the image is uploaded to the required target location,However, the fields - firstname and middlename are not inserted and I don't understand how to append these properties to the formData.
How can I pass these fields to the formData please?
You can use the following approach for storing the data with image.
1.In PHP API write logic for Upload image to server using move_uploaded_file() & Insert image file name with server path in the MySQL database using PHP.
2.In JS/JQuery, Read all HTML element & create an object & POST it to the API using AJAX Call.
your JS code should be like this. Hope this will help you to fix the issue.
var RegObj = {
'Field1': $("#Field1").val(),
'Field2': $("#Field2").val(),
'logo': $("#company_logo").attr('src'),
}
console.log(RegObj);
$.ajax({
url: "API_PATH_HERE",
type: "POST",
data: JSON.stringify(RegObj),
headers: {
"Content-Type": "application/json"
},
dataType: 'text',
success: function (result) {
//
},
error: function (xhr, textStatus, errorThrown) {
}
});
Like #Professor Abronsius suggested in the comments section I only needed to add the "name" tag to the form elements and remove the append from my function thus, I have edited the function and the form as follows:
// since I have added the name tag to the form elements, there is now
// no need to use the append() thus, I have commented out the append
// lines.
function Submit_highschool() {
jQuery(document).ready(function($) {
$("#highschool").submit(function(event) {
event.preventDefault();
$("#progress").html(
'Inserting <i class="fa fa-spinner fa-spin" aria-hidden="true"></i></span>');
var formData = new FormData($(this)[0]);
// var firstname_h = $("#firstname_h").val(); // removed this
// var middlename_h = $("#middlename_h").val(); // removed this
//formData.append(firstname_h, middlename_h); // removed this
$.ajax({
url: 'insertFunctions/insertHighSchool.php',
type: 'POST',
data: formData,
async: true,
cache: false,
contentType: false,
processData: false,
success: function(returndata) {
alert(returndata);
},
error: function(xhr, status, error) {
console.error(xhr);
}
});
return false;
});
});
}
// added the "name" tag to the form elements
<form method="post" enctype="multipart/form-data" id="highschool">
<div class="card" id="highschool">
<div class="col-3">
<label for="firstname">First name *</label>
<input type="text" class="form-control" name="firstname_h" id="firstname_h" placeholder="First name" /> // added name="firstname_h"
</div>
<div class="col-3">
<label for="middlename">Middle name *</label>
<input type="text" class="form-control" name="middlename_h" id="middlename_h" placeholder="Middle name" /> // added name="middlename_h"
</div>
<div class="col-6">
<label for="grade11_h">Grade 11 Transcript (image) *</label>
<input type="file" class="form-control" name="grade11_h" id="grade11_h" accept=".png, .jpg, .jpeg">
</div>
<button type="submit" name="submit" class="btn btn-primary float-right" onclick="Submit_highschool();">Submit</button>
</div>
</form>
I write HTML code in controller
public function edit($id)
{
$user = User::find($id);
$rolesForEdit = Role::pluck('name', 'name')->all();
$userRole = $user->roles->pluck('name', 'name')->all();
$html = '<div class="row">
<div class="col-md-6">
<label for="name">Name</label>
<input value="' . $user->name . '" class="form-control"
placeholder="Full Name" type="text" name="name" id="name" />
<br>
<label for="phone">Phone Number</label>
<input value="' . $user->phone . '" class="form-control"
placeholder="Phone Number" type="text" name="phone" id="phone" />
<br>
</div>
<div class="col-md-6">
<label for="roles">Role</label><br>
<select style="width:220px;" name="rolesForEdit[]" multiple id="rolesForEdit"
class="rolesForEdit form-control"></select>
<br>
</div> <!-- kanan -->
</div> <!-- row-->';
return response()->json(['html' => $html]);
}
And then in view, I am trying to get rolesForEdit id and use it for select2. It doesn't work with this way. Any solution?
$.ajax({
url: "user/" + id + "/edit",
method: 'GET',
success: function(data) {
//var roles = $($.parseHTML(data)).find("#rolesForEdit").html();
//var roles = $(data).find('#rolesForEdit').text();
//var roles = $(this).attr('rolesForEdit');
//var roles = $($.parseHTML(data)).filter("#rolesForEdit");
alert(roles);
$(roles).select2({
ajax: {
url: '{{ url('searchrole') }}',
processResults: function(data) {
return {
results: data.map(function(item) {
return {
id: item.id,
text: item.name
}
})
}
}
}
});
$('#dataUserElement').html(data.html);
$('#saveBtn').val("create-product");
$('#user_id').val('');
$('#productForm').trigger("reset");
$('#modelHeading').html("Update User");
$('#ajaxModel').modal('show');
}
});
});
Your server return json as response so add dataType: 'json' to your ajax call. Then , append data return to your dataUserElement i.e : data.html and finally intialize your select2 .
Demo Code :
//suppose data is this :)
var data = {
'html': '<div class="row"><div class="col-md-6"> <label for="name">Name</label><input value="abc" class="form-control" placeholder="Full Name" type="text" name="name" id="name" /><br><label for="phone">Phone Number</label><input value="12346" class="form-control" placeholder="Phone Number" type="text" name="phone" id="phone" /><br></div><div class="col-md-6"><label for="roles">Role</label><br><select style="width:220px;" name="rolesForEdit[]" multiple id="rolesForEdit" class="rolesForEdit form-control"></select><br></div></div>'
}
/*$.ajax({
url: "user/" + id + "/edit",
method: 'GET',
dataType:'json',//add this
success: function(data) {*/
$('#dataUserElement').html(data.html); //then append this
var roles = $('#dataUserElement').find(".rolesForEdit") //get select refernce
$(roles).select2({
ajax: {
url: "https://api.github.com/orgs/select2/repos", //this is for demo change it to your real url
processResults: function(data) {
return {
results: data.map(function(item) {
return {
id: item.id,
text: item.name
}
})
}
}
}
});
//all other codes modal ..etc etc
/*}
});*/
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" />
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.full.min.js"></script>
<div id="dataUserElement">
</div>
I want to pass some form data and file to a flask application from a form. but I can't pass it with ajax. There is a problem in data I guess. I've send data in ajax but in flask application I don't get any string or files.
Here is my html code:
<form id="user_vote" enctype = "multipart/form-data">
<br>
<br>
<div class="row">
<label class="col-sm-2">Name:</label>
<div class="col-sm-10">
<input type="text" name="name" id="name" rows="2" class="form-control" required>
</div>
</div>
<div class="row">
<label class="col-sm-2">National ID Image:</label>
<div class="col-sm-10">
<input type="file" name="national_id_image" id="national_id_image" rows="2" class="form-control" required>
</div>
</div>
<br>
<div class="row">
<label class="col-sm-2">Vote:</label>
<div class="col-sm-10">
<input type="number" name="vote" id="vote" rows="2" class="form-control" required>
</div>
</div>
<div class="row">
<div class="col-lg-12 text-center">
<input type="button" id="submit_vote" class="btn btn-primary btn-lg"
value="Authenticate and Encrypt Vote">
</div>
</div>
And here is my ajax code::
$(function(){
var form = $('#user_vote')[0];
var data = new FormData(form);
//console.log('hello');
//console.log(document.getElementById('submit_vote'));
$('#submit_vote').click(function(){
//console.log(data);
//console.log('hello');
$.ajax({
url: '/encrypt/vote',
type: "POST",
dataType: 'json',
enctype: 'multipart/form-data',
data: data,
contentType: false,
cache: false,
processData:false,
success: function(response){
//console.log("SUCCESS : ", data);
document.getElementById("encrypted_vote").innerHTML = response['encrypted_vote'];
document.getElementById("public_key").innerHTML = response['signature'];
document.getElementById("warning").style.display = "block";
},
error: function(error){
console.log(error);
}
});
});
})
Flask codes::
app.route('/encrypt/vote', methods=['POST'])
def encrypt_vote():
print('test')
name = request.form['name']
print(name)
family_name = request.form['family_name']
birth_date = request.form['birth_date']
national_id = request.form['national_id']
file = request.files['national_id_image']
filename = str(name) + str(family_name)# + secure_filename(file.filename)
#file.save(os.path.join(app.root_path, UPLOAD_FOLDER, filename))
#voter_national_cart_hash = get_digest('files/uploads/' + filename)
print('test vote type')
print(request.form['vote'])
vote = int(float(request.form['vote']))
pk = int(float(request.form['public_key']))
encrypted_vote = encrypt(pk, vote)
response = {
'encrypted_vote': str(encrypted_vote)
}
return jsonify(response), 200
Anyone can help me??
Thanks
It seems that you set enctype: 'multipart/form-data', which is non-existent property of the $.ajax() method. You should correct this error and simplify the request:
$.ajax({
type: "POST",
data: data,
url: '/encrypt/vote',
cache: false,
contentType: false,
processData: false,
success: function(response) {
/*The rest of your code*/
},
error: function(error){
console.log(error);
}
});
There is no need to set dataType, the default is Intelligent Guess (xml, json, script, or html). Read more here.
EDIT: Make sure you are using correct full path in the url, try not to use relative address, use https://www.your-server.com/encrypt/vote instead.
I have created one IMS System. In that i have to create bill on order page and in order page when i select customer name from drop down than customer_address,customer_phone and gst number should automatically fill in text box.In database i have created one table named partys in that all data are available(Customer_name,Customer_address,customer_phone and gst) If anybody knows solution than please help. Below is my code
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Name</label>
<div class="col-sm-7">
<select name="customer_name" id="client" style="width:100%;">
<?php
$dbc = mysqli_connect('localhost', 'root', '', 'stock')
or die('Error connecting to MySQL server.');
$query = "SELECT * FROM partys";
$result = mysqli_query($dbc, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['party_name'] ?>"><?php echo $row['party_name'] ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Address</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="customer_address" name="customer_address" placeholder="Enter Customer Address" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="gross_amount" class="col-sm-5 control-label" style="text-align:left;">Customer Phone</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="customer_phone" name="customer_phone" placeholder="Enter Customer Phone" autocomplete="off">
</div>
</div>
<div class="form-group">
<label for="gstin" class="col-sm-5 control-label" style="text-align:left;">GSTIN</label>
<div class="col-sm-7">
<input type="text" class="form-control" id="gstin" name="gstin" placeholder="Enter GST Number" autocomplete="off">
</div>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// On change of the dropdown do the ajax
$("#client").change(function() {
$.ajax({
// Change the link to the file you are using
url: '/create.php',
type: 'post',
// This just sends the value of the dropdown
data: {customer_name : party_name},
dataType: 'json',
success: function(response) {
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var response = JSON.parse(response);
// These are the inputs that will populate
$("#customer_address").val(response.customer_address);
$("#customer_phone").val(response.customer_phone);
$("#gstin").val(response.gstin);
}
});
});
});
</script>
create separate php file as customer.php and write following code
$content = file_get_contents("php://input");
$customer_data = json_decode($content, true);
$customer_name = $customer_data['customer_name'];
//using mysql query fetch all data of particular customer
$query = mysqli_query($dbc,"SELECT * FROM partys WHERE party_name=$customer_name");
$result = mysqli_fetch_array($query);
echo json_encode($result);
after getting this alert json response in ajax call. This will give customer data.
and modify your ajax call as
<script>
$(document).ready(function() {
// On change of the dropdown do the ajax
$("#client").change(function() {
$.ajax({
// Change the link to the file you are using
url: 'customer.php',
type: 'post',
// This just sends the value of the dropdown
data: {customer_name : party_name},
dataType: 'json',
success: function(response) {
alert(response);
// Parse the jSON that is returned
// Using conditions here would probably apply
// incase nothing is returned
var response = JSON.parse(response);
// These are the inputs that will populate
$("#customer_address").val(response.customer_address);
$("#customer_phone").val(response.customer_phone);
$("#gstin").val(response.gstin);
}
});
});
});
I've my call to ajax
$("#box-modal").on("shown",function(event)
{
$("#selectproductname").change(function(){
var valueProduct = $(this).val();
event.preventDefault();
$.ajax({
type:'GET',
url:'/ajax/products_ajax.php?idProducto='+valueProduct+'&opcion=2',
async:true,
datatype:'text',
success: function(data)
{
$("#editor-panel").load("/ajax/order.html");
$("#editor-actions").removeClass("hidden");
var inputs = document.getElementById('editor-panel').getElementsByTagName('input');
if(debug)
{
inputs[0].value="holaaa";
}
}
first I get the data with php, I get
1#jeans*1.00**0#100
after I want to assign this data a my order.html,
example:
inputs[1].value = jeans
inputs[2].value = 1.00
inputs[3].value = null
I get with console.log(inputs)
[item: function, namedItem: function]
0: input#inputnombre
1: input#inputidproducto
2: input#inputprecio.form-control
3: input#inputcantidad.form-control
4: input#inputdescatalogado.form-control
inputcantidad: input#inputcantidad.form-control
inputdescatalogado: input#inputdescatalogado.form-control
inputidproducto: input#inputidproducto
inputnombre: input#inputnombre
inputprecio: input#inputprecio.form-control
length: 5
When I do inputs[0].value="hello";
I get the error:
Uncaught TypeError: Cannot set property 'value' of undefined
In ajax order I have:
<div class="panel panel-body">
<form role="form" class="form-horizontal" id="form_order">
<div class="form-group">
<label for="inputnombre" class="col-md-4 col-xs-4 control-label">Nombre producto</label>
<div class="col-md-4 col-xs-4 control-label">
<input id="inputnombre" name="inputnombre" required type="text" />
<input type="hidden" name="inputidproducto" id="inputidproducto"/>
</div>
</div>
<div class="form-group">
<label for="descripciontext" class="col-md-4 col-xs-4 control-label">Descripcion</label>
<div class="col-md-4 col-xs-4 control-label">
<textarea cols="30" rows="10" id="descripciontext" name="descripciontext"></textarea>
</div>
</div>
<div class="form-group">
<label for="inputprecio" class="col-md-4 col-xs-4 control-label">Precio</label>
<div class="col-md-4 col-xs-4 control-label">
<input id="inputprecio" name="inputprecio" class="form-control" required type="text" />
</div>
How could I make the code easier?
Ajax .load takes time, you need to assign your values when .load is completed
$("#box-modal").on("shown", function(event) {
$("#selectproductname").change(function() {
var valueProduct = $(this).val();
event.preventDefault();
$.ajax({
type: 'GET',
url: '/ajax/products_ajax.php?idProducto=' + valueProduct + '&opcion=2',
async: true,
datatype: 'text',
success: function(data) {
// Ajax load takes time, you need a complete function here
$("#editor-panel").load("/ajax/order.html", function() {
// do below when "/ajax/order.html" is loaded
$("#editor-actions").removeClass("hidden");
var inputs = document.getElementById('editor-panel').getElementsByTagName('input');
if (debug) {
inputs[0].value = "holaaa";
}
});
}
});
});
});
var inputs = document.getElementById('editor-panel').getElementsByTagName('input');
jquery
var inputs = $("#editor-panel input").eq(0).val("hello");