Updating Image in Modal Yajra Datatable - php

I'm trying to achieve updating Image I tried finding for the answer but it seems that they don't work on mine maybe because I am using Yajra DataTables, I already inserted or added the image seems to be working fine but whenever I click the button it doesn't popup the modal Thank you in Advance.
This is my Controller:
public function edit($id)
{
if (request()->ajax()) {
$shippings = Shipping_data::findOrFail($id);
return response()->json(['result' => $shippings]);
}
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, Shipping_data $shippings_data)
{
$rules = array(
'name' ,
'mobile',
'items',
'shippingAddress',
'amount',
'facebookLink',
'facebookName',
"modePayment",
"shipVia"=> 'required',
"trackingNumber"=> 'required',
"shippingReceipt"=> 'required',
"shippingCharged"=> 'required',
"shippingWeight"=> 'required'
);
$error = Validator::make($request->all(), $rules);
if ($error->fails()) {
return response()->json(['errors' => $error->errors()->all()]);
}
// Handle File Upload
if ($request->hasFile('shippingReceipt')) {
// Get filename with the extension
$filenameWithExt = $request->file('shippingReceipt')->getClientOriginalName();
// Get just filename
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
// Get just ext
$extension = $request->file('shippingReceipt')->getClientOriginalExtension();
// Filename to store
$fileNameToStore= $filename.'_'.time().'.'.$extension;
// Upload Image
$path = $request->file('shippingReceipt')->storeAs('public/shippingReceipts', $fileNameToStore);
}else {
$fileNameToStore = '';
}
$form_data = array(
'name' => $request->name,
'mobile'=> $request->mobile,
'items'=> $request->items,
'shippingAddress'=> $request->shippingAddress,
'amount'=> $request->amount,
'facebookLink'=> $request->facebookLink,
'facebookName'=> $request->facebookName,
"modePayment"=> $request->modePayment,
"shipVia"=> $request->shipVia,
"trackingNumber"=> $request->trackingNumber,
"shippingReceipt"=> $request->fileNameToStore,
"shippingWeight"=> $request->shippingWeight,
"shippingCharged"=> $request->shippingCharged,
);
Shipping_data::whereId($request->hidden_id)->update($form_data);
return response()->json(['success' => 'Shipping Data is successfully updated']);
}
This is my blade.php:
#extends('layouts.navbar')
#section('content')
<br />
<br />
<br />
Add Order Data
<br>
<br>
<!-- Table -->
<div style="margin: 10px 15px;">
<table id="shipping_table" class="table table-bordered table-striped ">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Mobile Number</th>
<th scope="col">Item Orders</th>
<th scope="col">Shipping Address</th>
<th scope="col">Amount</th>
<th scope="col">Facebook Link</th>
<th scope="col">Facebook Name</th>
<th scope="col">Mode of Payment</th>
<th scope="col">Ship Via</th>
<th scope="col">Tracking Number</th>
<th scope="col">Shipping Receipt</th>
<th scope="col">Shipping Charged</th>
<th scope="col">Shipping Weight</th>
<th>Action</th>
</tr>
</thead>
</table>
</div>
<br />
<br />
<!-- End Table -->
</body>
</html>
<!-- Modal -->
<div id="formModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title text-center">Add Shipping Data</h4>
</div>
<div class="modal-body">
<span id="form_result"></span>
<form method="post" id="shipping_form" class="form-horizontal">
#csrf
#if(Auth::check() && Auth::user()->role == "admin")
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" placeholder="Please Enter Client Name"
id="name">
</select>
</div>
<div class="form-group">
<label>Mobile</label>
<input type="text" class="form-control" name="mobile" placeholder="Please Enter Mobile Number"
id="mobile">
</div>
<div class="form-group">
<label>Items Order</label>
<input type="text" class="form-control" name="items" placeholder="Please Enter Items Order"
id="items">
</div>
<div class="form-group">
<label>Shipping Address</label>
<input type="text" class="form-control" name="shippingAddress" id="shippingAddress"
placeholder="Please Enter Shipping Address">
</div>
<div class="form-group">
<label>Amount</label>
<input type="text" class="form-control" name="amount" placeholder="Please Enter Amount"
id="amount">
</div>
<div class="form-group">
<label>Facebook Link</label>
<input type="text" class="form-control" name="facebookLink" id="facebookLink"
placeholder="Please Enter Facebook Link">
</div>
<div class="form-group">
<label>Facebook Name</label>
<input type="text" class="form-control" name="facebookName" id="facebookName"
placeholder="Please Enter Facebook Name">
</div>
<div class="form-group">
<label>Mode of Payment</label>
<input type="text" class="form-control" name="modePayment" id="modePayment"
placeholder="Please Enter Mode of Payment">
</div>
#endif
#if(Auth::check() && Auth::user()->role == "employee")
<div class="form-group">
<label>Name</label>
<input type="text" class="form-control" name="name" placeholder="Please Enter Name" id="name"
READONLY>
</div>
<div class="form-group">
<label>Mobile</label>
<input type="text" class="form-control" name="mobile" placeholder="Please Enter Mobile Number"
id="mobile" READONLY>
</div>
<div class="form-group">
<label>Items Order</label>
<input type="text" class="form-control" name="items" placeholder="Please Enter Items Order"
id="items" READONLY>
</div>
<div class="form-group">
<label>Shipping Address</label>
<input type="text" class="form-control" name="shippingAddress" id="shippingAddress" READONLY
placeholder="Please Enter Shipping Address">
</div>
<div class="form-group">
<label>Amount</label>
<input type="text" class="form-control" name="amount" placeholder="Please Enter Amount"
id="amount" READONLY>
</div>
<div class="form-group">
<label>Facebook Link</label>
<input type="text" class="form-control" name="facebookLink" id="facebookLink" READONLY
placeholder="Please Enter Facebook Link">
</div>
<div class="form-group">
<label>Facebook Name</label>
<input type="text" class="form-control" name="facebookName" id="facebookName" READONLY
placeholder="Please Enter Facebook Name">
</div>
<div class="form-group">
<label>Mode of Payment</label>
<input type="text" class="form-control" name="modePayment" id="modePayment" READONLY
placeholder="Please Enter Mode of Payment">
</div>
#endif
<div class="form-group">
<label>Shipping Via</label>
<input type="text" class="form-control" name="shipVia" placeholder="Please Enter Shipping Via"
id="shipVia">
</div>
<div class="form-group">
<label>Tracking Number</label>
<input type="text" class="form-control" name="trackingNumber" id="trackingNumber"
placeholder="Please Enter Tracking Number">
</div>
<div class="form-group">
<label>Shipping Receipt</label>
<br>
<input type="file" class="form-control file-form" name="shippingReceipt" id="shippingReceipt">
</div>
<div class="form-group">
<label>Shipping Charged</label>
<input type="text" class="form-control" name="shippingCharged" id="shippingCharged"
placeholder="Please Enter Shipping Charged">
</div>
<div class="form-group">
<label>Shipping Weight</label>
<input type="text" class="form-control" name="shippingWeight" id="shippingWeight"
placeholder="Please Enter Shipping Weight">
</div>
<br />
<div class="form-group" align="center">
<input type="hidden" name="action" id="action" value="Add" />
<input type="hidden" name="hidden_id" id="hidden_id" />
<input type="submit" name="action_button" id="action_button" class="btn btn-success"
value="Add" />
</div>
</form>
</div>
</div>
</div>
</div>
<div id="confirmModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h2 class="modal-title">Confirmation</h2>
</div>
<div class="modal-body">
<h4 align="center" style="margin:0;">Are you sure you want to remove this data?</h4>
</div>
<div class="modal-footer">
<button type="button" name="ok_button" id="ok_button" class="btn btn-danger">OK</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
</div>
</div>
</div>
</div>
<!-- End Modal -->
<script>
$(document).ready(function () {
$('#shipping_table').DataTable({
processing: true,
serverSide: true,
ajax: {
url: "{{ route('shipping.index') }}",
},
columns: [
{
data: 'name',
name: 'name'
},
{
data: 'mobile',
name: 'mobile'
},
{
data: 'items',
name: 'items'
},
{
data: 'shippingAddress',
name: 'shippingAddress'
},
{
data: 'amount',
name: 'amount'
},
{
data: 'facebookLink',
name: 'facebookLink'
},
{
data: 'facebookName',
name: 'facebookName'
},
{
data: 'modePayment',
name: 'modePayment'
},
{
data: 'shipVia',
name: 'shipVia'
},
{
data: 'trackingNumber',
name: 'trackingNumber'
},
{
data: 'shippingReceipt',
name: 'shippingReceipt',
"render": function (data, type, full, meta) {
return "<img src=\"storage/shippingReceipts/" + data + "\" height=\"50\"/>";
},
},
{
data: 'shippingCharged',
name: 'shippingCharged'
},
{
data: 'shippingWeight',
name: 'shippingWeight'
},
{
data: 'action',
name: 'action',
orderable: false
}
]
});
$('#create_record').click(function () {
$('.modal-title').text('Add Client Data');
$('#action_button').val('Add Client Data');
$('#action').val('Add');
$('#form_result').html('');
$('#formModal').modal('show');
});
$('#shipping_form').on('submit', function (event) {
event.preventDefault();
var action_url = '';
if ($('#action').val() == 'Add') {
action_url = "{{ route('shipping.store') }}";
}
if ($('#action').val() == 'Edit') {
action_url = "{{ route('shipping.update') }}";
}
$.ajax({
url: action_url,
method: "POST",
data: $(this).serialize(),
dataType: "json",
success: function (data) {
var html = '';
if (data.errors) {
html = '<div class="alert alert-danger">';
for (var count = 0; count < data.errors.length; count++) {
html += '<p>' + data.errors[count] + '</p>';
}
html += '</div>';
}
if (data.success) {
html = '<div class="alert alert-success">' + data.success + '</div>';
$('#shipping_form')[0].reset();
$('#shipping_table').DataTable().ajax.reload();
}
$('#form_result').html(html);
}
});
});
$(document).on('click', '.edit', function () {
var id = $(this).attr('id');
$('#form_result').html('');
$.ajax({
url: "/shipping/" + id + "/edit",
dataType: "json",
success: function (data) {
$('#name').val(data.result.name);
$('#mobile').val(data.result.mobile);
$('#items').val(data.result.items);
$('#shippingAddress').val(data.result.shippingAddress);
$('#amount').val(data.result.amount);
$('#facebookLink').val(data.result.facebookLink);
$('#facebookName').val(data.result.facebookName);
$('#modePayment').val(data.result.modePayment);
$('#shipVia').val(data.result.shipVia);
$('#trackingNumber').val(data.result.trackingNumber);
$('#shippingReceipt').val(data.result.shippingReceipt);
$('#shippingCharged').val(data.result.shippingCharged);
$('#shippingWeight').val(data.result.shippingWeight);
$('#hidden_id').val(id);
$('.modal-title').text('Edit Record');
$('#action_button').val('Save');
$('#action').val('Edit');
$('#formModal').modal('show');
}
})
});
var shipping_id;
$(document).on('click', '.delete', function () {
shipping_id = $(this).attr('id');
$('#confirmModal').modal('show');
});
$('#ok_button').click(function () {
$.ajax({
url: "shipping/destroy/" + shipping_id,
beforeSend: function () {
$('#ok_button').text('Deleting...');
},
success: function (data) {
setTimeout(function () {
$('#confirmModal').modal('hide');
$('#shipping_table').DataTable().ajax.reload();
}, 2000);
}
})
});
});
</script>
#endsection

You can't view an image on input field, but you can do it with img tag :
<img class="img-circle" id="view_photo">
Change this line :
$('#shippingReceipt').val(data.result.shippingReceipt);
To,
$("#view_photo").attr("src", data.result.shippingReceipt);

Related

API "POST" shows successful but won't reflect changes on database

I have a basic web application that has been coded in php.
The app carries out CRUD operations by making use of an API made through PHP. When I try to use my update.php API endpoint, I get a successful response but no changes reflect in db.
Project Structure
Project_Structure
update.php in api/mailbox
<?php
// include database and object files
include_once '../config/database.php';
include_once '../objects/mailbox.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
// prepare mailbox object
$mailbox = new Mailbox($db);
//For diagnostics
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data[""];
// set ID property of product to be edited
$mailbox_id->mailbox_id = $data->mailbox_id;
// set mailbox property values
$mailbox->username = $_POST['username'];
$mailbox->password = base64_encode($_POST['password']);
$mailbox->name = $_POST['name'];
$mailbox->quota = $_POST['quota'];
$mailbox->modified = date('Y-m-d H:i:s');
$mailbox->active = $_POST['active'];
$mailbox->mailbox_id = $_POST['mailbox_id'];
// create the mailbox
if($mailbox->update()){
$mailbox_arr=array(
"status" => true,
"message" => "Successfully Updated Mailbox"
);
}
else{
$mailbox_arr=array(
"status" => false,
"message" => "Mailbox already exists!"
);
}
print_r(json_encode($mailbox_arr));
?>
mailbox.php(in objects folder)
// update mailbox
function update(){
$query = "UPDATE
". $this->table_name ."
SET
username='".$this->username."', password='".$this->password."', name='".$this->name."', quota='".$this->quota."', modified='".$this->modified."', active='".$this->active."'
WHERE
mailbox_id= '".$this->mailbox_id."'";
// prepare query
$stmt = $this->conn->prepare($query);
// execute query
if($stmt->execute()){
return true;
}
return false;
}
update.php (The rendered page, on clicking update, the error is: **Mailbox already exists)**
<?php
$content = '<div class="container"
<div class="row">
<!-- left column -->
<div class="col-md-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Update Mailbox</h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<form role="form">
<div class="box-body">
<div class="form-group">
<div class="form-group">
<label for="exampleMBID1">Mailbox ID</label>
<input type="text" class="form-control" id="mailbox_id" placeholder="Mailbox ID" disabled>
</div>
<label for="exampleInputUserName1">User Name</label>
<input type="text" class="form-control" id="username" placeholder="Enter Username e.g jsmith">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="password" placeholder="Enter Password">
</div>
<div class="form-group">
<label for="exampleInputName1">Name</label>
<input type="text" class="form-control" id="name" placeholder="Name of User">
</div>
<div class="form-group">
<label for="exampleInputMaildir1">Maildir</label>
<input type="text" class="form-control" id="maildir" placeholder="Enter Maildir" disabled>
</div>
<div class="form-group">
<label for="exampleInputQuota1">Quota (0=Unlimited)</label>
<input type="text" class="form-control" id="quota" placeholder="Enter Quota">
</div>
<div class="form-group">
<label for="examplelocalpart1">Local Part</label>
<input type="text" class="form-control" id="local_part" placeholder="localpart" disabled>
</div>
<div class="form-group">
<label for="exampledomain1">Domain</label>
<input type="text" class="form-control" id="domain" placeholder="domain" disabled>
</div>
<div class="form-group">
<label for="examplecreated1">Created</label>
<input type="text" class="form-control" id="created" placeholder="Created" disabled>
</div>
<div class="form-group">
<label for="examplemodified1">Modified</label>
<input type="text" class="form-control" id="modified" placeholder="Modified">
</div>
<div class="form-group">
<label for="exampleactive1">Active (0=Not Active, 1=Active)</label>
<input type="text" class="form-control" id="active" placeholder="Enter 0 or 1">
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<input type="button" class="btn btn-primary" onClick="UpdateMailbox()" value="Update"></input>
</div>
</form>
</div>
<!-- /.box -->
</div>
</div>
</div>';
include('../master.php');
?>
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "../api/mailbox/read_single.php?mailbox_id=<?php echo $_GET['mailbox_id']; ?>",
dataType: 'json',
success: function(data) {
$('#username').val(data['username']);
$('#password').val(data['password']);
$('#name').val(data['name']);
$('#maildir').val(data['maildir']);
$('#quota').val(data['quota']);
$('#local_part').val(data['local_part']);
$('#domain').val(data['domain']);
$('#created').val(data['created']);
$('#modified').val(data['modified']);
$('#active').val(data['active']);
$('#mailbox_id').val(data['mailbox_id']);
},
error: function (result) {
console.log(result);
},
});
});
function UpdateMailbox(){
$.ajax(
{
type: "POST",
url: '../api/mailbox/update.php',
dataType: 'json',
data: {
mailbox_id: <?php echo $_GET['mailbox_id']; ?>,
username: $("#username").val(),
password: $("#password").val(),
name: $("#name").val(),
maildir: $("#maildir").val(),
quota: $("#quota").val(),
domain: $("#domain").val(),
modified: $("#modified").val(),
active: $("#active").val()
},
error: function (result) {
alert(result.responseText);
},
success: function (result) {
if (result['status'] == true) {
alert("Successfully Updated Mailbox!");
window.location.href = '/MailEasy/mailbox/listAll.php';
}
else {
alert(result['message']);
}
}
});
}
</script>
1) Why is not updating when using web UI?
2) When using postman, it shows successful, why are requests not reaching the database?
Postman --> Successful response but no changes in db.
Php webpage --> Mailbox already exists.
Thank you

Double insertion of data using modal

I`m working on PHP + MYSQL + AJAX project. I used Bootstrap Modal when adding data. After first time I click add, it will insert two records however it only occurs in its first time click.
Is there any way to prevent saving two records.
I appreciate your help and suggestion. Thanks
This is my modal
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data" class="form-horizontal">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label class="col-lg-3 control-label">Name</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sName" maxlength="150" id="sName" placeholder="Enter your Name" />
<span id='remainingC'></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Username</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sUsername" maxlength="20" id="sUsername" placeholder="Enter your Username"/>
<span id='remainingCu'></span>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Birthday</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sBirthday"
onchange ="getAge();" maxlength="20" id="sBirthday" placeholder="YYYY-mm-dd"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Age</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="iAge" maxlength="3" id="iAge" placeholder="Autofill when you fill Birthday"/>
</div>
</div>
<div class="form-group">
<label class="col-lg-3 control-label">Email</label>
<div class="col-lg-9">
<input type="text" class="form-control" name="sEmail" id="sEmail" placeholder="Enter your Email - eg. jb#gmail.com"/>
</div>
</div>
My AJAX requests
$(document).ready(function(){
$('#add_button').click(function(){
$('#user_form')[0].reset();
$('.modal-title').text("Add User");
$('#action').val("Add");
$('#operation').val("Add");
// $('#user_uploaded_image').html('');
});
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 3, 4],
"orderable":false,
},
],
});
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var sName = $('#sName').val();
var sUsername = $('#sUsername').val();
var sBirthday = $('#sBirthday').val();
var iAge = $('#iAge').val();
var sEmail = $('#sEmail').val();
if(sName != '' && sUsername != '' && sBirthday != '' && iAge != '' && sEmail != '')
{
$.ajax({
url:"insert.php",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Both Fields are Required");
}
});
This is my Function for adding (insert.php)
if($_POST["operation"] == "Add")
{
$statement = $connection->prepare("
INSERT INTO users (sName, sUsername, sBirthday, iAge, sEmail)
VALUES (:sName, :sUsername, :sBirthday, :iAge, :sEmail)
");
$result = $statement->execute(
array(
':sName' => $_POST["sName"],
':sUsername' => $_POST["sUsername"],
':sBirthday' => $_POST["sBirthday"],
':iAge' => $_POST["iAge"],
':sEmail' => $_POST["sEmail"]
)
);
if(!empty($result))
{
echo 'Data Inserted';
}
}
Duplicate data after 1st click of add button in modal:
Duplicate

500 Interval server error in ajax

I would like to ask what are the causes of this error? When i check the inspect elements to check it out, it said console.log(xhr.status); console.log(xhr.responseText); console.log(thrownError); are my errors. what is wrong in here?
My view
<h3> Product
<span class = "fa fa-plus-square-o ">
<div class="modal fade" id="new_product" role="dialog" >
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add New Product</h4>
</div>
<form method="post" id="form-submit" enctype="multipart/form-data">
<!-- <form method="post" enctype="multipart/form-data" name = "select_design"action="<?php echo base_url(); ?>Administrator/new_product"> -->
<div class="modal-body">
<!-- <div class="form-group">
<label class="control-label ">Genre:</label>
<select name = "product_genre" class="select2_multiple " multiple="multiple" >
<option>Choose option</option>
<option value ="drama">Drama</option>
<option value ="action">Action</option>
<option value ="comedy">Comedy</option>
<option value ="horror">Horror</option>
</select>
</div> -->
<div class="form-group">
<label>Product Name</label>
<input type="text" class="form-control" id="product_name" name="product_name" placeholder="Name" value="<?php echo set_value('product_name'); ?>"> </div>
<div class="form-group">
<label>Product Description</label>
<input type="text" class="form-control" id="product_description" name="product_description" placeholder="Description" value="<?php echo set_value('product_description'); ?>">
</div>
<div class="form-group">
<label>Stocks</label>
<input type="number" class="form-control" id="quantity" name="quantity" placeholder="Quantity" value="<?php echo set_value('quantity'); ?>">
</div>
<div class="form-group">
<label>Product Image</label>
<input type="file" required class="form-control" id="userfile" name="userfile">
</div>
<div class="form-group">
<label>Product Price</label>
<input type="number" min="1" class="form-control" id="product_price" name="product_price" placeholder="Price" value="<?php echo set_value('price'); ?>">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Register</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
My js
<script>
$("#form-submit").on('submit',function(event){
// $.LoadingOverlay("show");
var form = new FormData(document.getElementById("form-submit"));
$.ajax({
url: base_url + "Administrator/new_product",
type: "POST",
data: form,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function(data) {
var result = JSON.parse(data);
//alert(data);
if(result===1)
{
swal({
type: 'success',
html: 'New Product Added',
timer: 2000,
})
setTimeout(function() {
document.location.href= base_url + "Administrator/view_products";
}, 2000);
}
else
{
swal({
type: 'error',
html: result
});
}
// $.LoadingOverlay("hide");
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(xhr.responseText);
console.log(thrownError);
}
})
event.preventDefault();
});
</script>
My controller
public function new_product()
{
// $data['new_product'] = $this->AdministratorModel->getCourses();
$config['upload_path'] = './products/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048000';
$config['overwrite'] = TRUE;
$this->load->library('upload', $config);
$this->load->library('form_validation');
$this->form_validation->set_error_delimiters('<div class="alert alert-danger" role="alert">', '</div>');
$this->form_validation->set_rules('product_name', ' Name', 'required|trim');
$this->form_validation->set_rules('product_description', ' Name', 'required|trim');
$this->form_validation->set_rules('quantity', 'stocks', 'required|trim');
$this->form_validation->set_rules('product_price', 'price', 'required|trim');
$this->form_validation->set_rules('userfile', 'image', 'callback_handle_upload');
if ($this->form_validation->run() == FALSE)
{
echo json_encode(validation_errors());
}
else
{
$products = array(
'product_name' => strip_tags($_POST['product_name']),
'product_description' => strip_tags($_POST['product_description']),
'product_category' => "Drama",
'product_quantity' => strip_tags($_POST['quantity']),
'product_image' => $this->input->post('userfile'),
'upload_data' => $this->upload->data(),
'product_price' => strip_tags($_POST['product_price'])
);
$this->AdministratorModel->addProduct($products);
echo json_encode(1);
}
}
My model
public function addProduct($products)
{
$products = array(
'product_name' => strip_tags($_POST['product_name']),
'product_description' => strip_tags($_POST['product_description']),
'product_category' => strip_tags($_POST['product_genre']),
'product_quantity' => strip_tags($_POST['quantity']),
'product_image' => $this->input->post('userfile'),
'product_image' => $this->upload->data('file_name'),
'product_price' => strip_tags($_POST['product_price'])
);
$this->db->insert('products',$products);
}

Codeigneitor data not inserted to the Database

I have create form and i am trying to store the data using Ajax.but data is not inserted to the database.what can be the error.user_id will be auto increment. and also i want to validate sitename.it should restrict inserting same sitenames.
Here is my code
Controller
public function user_add()
{
$data_save = array(
"Mnumber" => $this->input->post("Mnumber"),
"email" => $this->input->post("email"),
"fname" => $this->input->post("fname"),
"address" => $this->input->post("address"),
"sitename" => $this->input->post("sitename"),
"title" => $this->input->post("title"),
"descr" => $this->input->post("descr")
);
if ($this->user_mod->AddUser($data_save)) {
echo "Successfully Saved";
} else {
echo "error";
}
}
}
Model
class user_mod extends CI_Model
{
public function AddUser($data_save)
{
if ($this->db->insert('users', $data_save)) {
return true;
} else {
return false;
}
}
}
View
<script>
function save_user_new() {
var user_id = $('#user_id').val();
var Mnumber = $('#Mnumber').val();
var email = $('#email').val();
var fname = $('#fname').val();
var address = $('#address').val();
var sitename = $('#sitename').val();
var title = $('#title').val();
var descr = $('#descr').val();
if (sitename != "" && Mnumber != "") {
$.ajax({
type: "post",
async: false,
url: "<?php echo site_url('form_con/user_add'); ?>",
data: { "user_id": user_id,
"Mnumber": Mnumber,
"email": email,
"fname": fname,
"address": address,
"sitename": sitename,
"title": title,
"descr": descr,
},
dataType: "html",
success: function (data) {
if (data == 'error') {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : Something wrong.");
} else if (data == 'have') {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : This Employee is already exists.");
} else {
$('#error_msg1').hide();
$('#success_msg').show();
$('#success_msg').html("Entitled leave successfully saved.");
$('#load_leave').html(data);
}
}
});
} else {
$('#success_msg').hide();
$('#error_msg1').show();
$('#error_msg1').html("Error : Please enter Employee Details.");
}
}
</script>
<form action="#">
<div class="form-body">
<div class="form-group">
<label class="control-label">Your First Name</label>
<input type="text" class="form-control" id="fname" name="fname" placeholder="Enter text">
<!--<span class="help-block"> A block of help text. </span>-->
</div>
<div class="form-group">
<label class="control-label">Email Address</label>
<div class="input-group">
<span class="input-group-addon">
<i class="fa fa-envelope"></i>
</span>
<input type="email" class="form-control" id="email" name="email" placeholder="Email Address">
</div>
</div>
<div class="form-group">
<label class="control-label">Your Mobile Number</label>
<input type="text" class="form-control" id="Mnumber" name="Mnumber" placeholder="Enter text">
<!--<span class="help-block"> A block of help text. </span>-->
</div>
<div class="form-group">
<label class="control-label">Your Address</label>
<input type="text" class="form-control" id="address" name="address" placeholder="Enter text">
</div>
<div class="form-group">
<label class="control-label">Your Site Name</label>
<input type="text" class="form-control" id="sitename" name="sitename" placeholder="Enter text">
<!--<span class="help-block"> A block of help text. </span>-->
</div>
<div class="form-group">
<label class="control-label">Title of Your Web site</label>
<input type="text" class="form-control" id="title" name="title" placeholder="Enter text">
</div>
<div class="form-group">
<label class="control-label">Description of Your Web Site</label>
<input type="text" class="form-control" id="descr" name="descr" placeholder="Enter text">
</div>
</div>
<div class="form-actions right">
<button type="submit" class="btn green" onclick="save_user_new()">Submit</button>
<button type="button" class="btn default">Cancel</button>
</div>
</form>

Trouble with registration using codeigniter

I have a registration form for my website, and it is showing username, password and password confirmation required although i am providing all of these. This is the controller code:
{
$this->load->library('form_validation');
$this->form_validation->set_rules('username','Username','trim|required|min_length[4]|xss_clean');
$this->form_validation->set_rules('email','Email','trim|required|valid_email');
$this->form_validation->set_rules('pass1','Password','trim|required|min_length[4]|max_length[32]');
$this->form_validation->set_rules('pass2','Password Confirmation','trim|required|matches[pass1]');
if ($this->form_validation->run() === FALSE)
{
$password = $this->input->post('pass1');
echo json_encode(array('error' => '1', 'message' => validation_errors('<div class="alert alert-error"><strong>Error!</strong> ', '</div>')));
}
else
{
$username = $this->input->post('username');
$password = $this->input->post('pass1');
$email = $this->input->post('email');
$date = date('Y/m/d H:i:s');
$this->load->model('ui_model');
$this->ui_model->register_user($username,$password,$email,$date);
echo json_encode(array('error' => '0', 'message' => '<div class="alert alert-success"><strong>Success!</strong> You have been registered!</div>'));
}
and this is the view code:
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3>Registration</h3>
</div>
<div class="modal-body">
<div id="registerModalerror" style="display: none;"></div>
<?php
$attributes = array('class' => 'form-horizontal','id' => 'registerModalform');
echo form_open('',$attributes);
?>
<div class="control-group">
<label class="control-label" for="Username">Username</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-user"></i></span>
<input type="text" id="inputUser" placeholder="Username" name="username" value ="" >
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">Email</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-envelope"></i></span>
<input type="text" id="inputEmail" placeholder="email" name="email" value = "">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" id="inputPassword" placeholder="Password" name="pass1" value = "">
</div>
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword2">Retype Password</label>
<div class="controls">
<div class="input-prepend">
<span class="add-on"><i class="icon-lock"></i></span>
<input type="password" id="inputPassword2" placeholder="Retype Password" name="pass2" value = "">
</div>
</div>
</div>
<div class="control-group">
<div class="controls">
<button type="submit" class="btn">Register</button>
</div>
</div>
</div>
<?php echo form_close(); ?>
<div class="modal-footer">
</div>
</div>
<script>
$(document).ready(function() {
$('#myModalReg').removeData('modal');
$('#myModalReg').hide();
$('#registerModalform').submit(registerUser);
});
function registerUser(event)
{
//Stop the form from submitting
event.preventDefault();
//Collect our form data.
var form_data = {
username : $("[name='username']").val(),
password1 : $("[name='pass1']").val(),
password2 : $("[name='pass2']").val(),
email : $("[name='email']").val()
};
//Begin the ajax call
$.ajax({
url: "http://localhost/fys/index.php/ui/do_register",
type: "POST",
data: form_data,
dataType: "json",
cache: false,
async : false,
success: function (json) {
// alert(json.pass);
if (json.error==1)
{
$('#registerModalerror').html(json.message).show();
}
else {
//Hide our form
$('#registerModalform').slideUp();
//Show the success message
$('#registerModalerror').html(json.message).show();
}
},
error: function(json)
{
alert(json.message);
}
});
}
</script>
I am not sure where it went wrong, and it is bugging me for almost 24 hours. Can anyone provide some help?
Thanks!
Your POST object is
{
username : $("[name='username']").val(),
password1 : $("[name='pass1']").val(),
password2 : $("[name='pass2']").val(),
email : $("[name='email']").val()
}
But your Controller's POST name is pass1 and pass2. You're passing up password1 and password2
:P

Categories