My previously edited data is edited again when I update second data in codeigniter using ajax - ajax

I am using codeigniter framework to develop my project. I am also using AJAX to edit the data. When I edit the first data it is being edited correctly but when I am updating the second data without refreshing the browser then previous edited data or current editing data both are updated with new result. Please solve my problem. Thanks in advance.
function editFunction(id)
{
$.ajax({
url: "edit_result/" +id,
data: {id:id},
type: "post",
async: false,
dataType: 'json',
success: function(response){
$('#reg_no').val(response.reg);
$('#total_marks').val(response.tot_marks);
$('#grade').val(response.grade);
},
error: function()
{
alert("error");
}
});
$('#updateBtn').click(function(event){
event.preventDefault();
var grade_id = document.getElementById("grade").value;
var total_id = document.getElementById("total_marks").value;
if(grade_id=='' || total_id=='')
{
$('#updateBtn').prop('disabled',true);
setTimeout(function(){document.getElementById("updateBtn").disabled = false;},2000);
$('.message').html('Please fill all fields').fadeIn().delay(1000).fadeOut('slow');;
}
else
{
$.ajax({
url: "edit_result_valid/" +id,
data: $(this).serialize(),
type: "post",
async: false,
dataType: 'json',
success: function(response){
alert('success');
},
error: function()
{
alert("error");
}
});
}
});
}
I am performing edit operation on modal. Please check also HTML code
<div class="modal fade" id="editModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h2 class="modal-title">Edit Result</h2>
<p class="message" style="color: red;"></p>
</div>
<div class="modal-body">
<form role="form" id="updateForm">
<div class="box-body">
<div class="form-group">
<label for="exampleInputEmail1">Reg No :</label>
<input type="text" class="form-control" id="reg_no" readonly="">
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label>Total Marks :</label>
<input type="number" class="form-control" id="total_marks" placeholder="Enter total marks" onfocus="colorFunction(this)" name="tot_marks">
</div>
</div>
<div class="col-sm-6">
<div class="form-group">
<label>Grade</label>
<?php
$firstItem[''] = 'Please select one...';
$options = array(
'A++' => 'A++ (90% & above)',
'A+' => 'A+ (80% to 89%)',
'A' => 'A (60% to 79%)',
'B+' => 'B+ (50% to 59%)',
'B' => 'B (40% to 49%)',
);
$options = array_merge($firstItem, $options);
$selected_option = $this->input->post('grade', TRUE);
echo form_dropdown('grade', $options,$selected_option,['class'=>'form-control','id'=>'grade','onfocus'=>'colorFunction(this)']); ?>
</div>
</div>
</div>
</div>
<!-- /.box-body -->
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger pull-left" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-success pull-right" data-dismiss="modal" id="updateBtn">Update</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->

I have got an answer of my question. I am using off('click') in code you can see update code below.
$('#updateForm').off('click','#updateBtn').on('click','#updateBtn',function(event){
event.preventDefault();
var grade_id = document.getElementById("grade").value;
var total_id = document.getElementById("total_marks").value;
if(grade_id=='' || total_id=='')
{
$('#updateBtn').prop('disabled',true);
setTimeout(function(){document.getElementById("updateBtn").disabled = false;},2000);
$('.message').html('Please fill all fields').fadeIn().delay(1000).fadeOut('slow');;
}
else
{
$.ajax({
url: "edit_result_valid/" +id,
data: $("#updateForm").serialize(),
type: "post",
async: false,
dataType: 'json',
success: function(response){
if(response=='1')
{
$('.alert-success').show();
$('.alert-success').html('Result Updated Successfully').fadeIn().delay(4000).fadeOut('slow');
$('#example1').DataTable().ajax.reload();s
}
},
error: function()
{
alert("error");
}
});
}
});

play a game at view first. i guess you are not using primary key of db to update. let me explain.
at view:
at one more input element which type is hidden and has value your primary key . assign it an id having value tbl_id example
<input type="hidden" value="<?php echo {variable that has your primary key } ?>" id="tbl_id" >
and at ajax call before you start writing it
var id = $("#tbl_id").val();
when you call controller check you have id available or not
next you are going to call a model to update.
that is where your other all data get update.
when you are going to call model use statement before it
if($id != '') { // $id is what you have shared via ajax call
$this->model_name->update_function($id,$array); // $array is all other fields as per codeigniter need
} else { echo "unable to capture id"; exit; }
and last you update model..
all done by ajax :)

Related

Laravel Post or GET data with html but as raw text

Laravel Post html but as raw text
i'm use tinymce and normal input
i try to normal post and get with url and ajax
<div class="modal fade" id="addpromotion" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="addpromotionLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<form action="{{ route('admin.blog.create') }}" id="addpromotionform" method="post" enctype="multipart/form-data">
#csrf
<input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
<div class="modal-header">
<h1 class="modal-title fs-5" id="addpromotionLabel">เพิ่มโปรโมชั่น</h1>
{{-- <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> --}}
</div>
<div class="modal-body">
<div class="mb-3 mx-5">
<input type="file" class="form-control" name="image" style="border-radius: 15px;">
</div>
<div class="mb-3 mx-5">
<input type="text" name="title" class="form-control" placeholder="Title" style="border-radius: 15px;">
</div>
<div class="mb-3 mx-5">
<input type="text" name="description" class="form-control" placeholder="Description" style="border-radius: 15px;">
</div>
<div class="mb-3 mx-5">
<textarea id="tinymcecreate" class="tinymce" name="body"></textarea>
</div>
<input type="hidden" name="type" value="promotion">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-danger">บันทึก</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">ปิด</button>
</div>
</form>
</div>
</div>
</div>
body=%3Cp%3E%3Cstrong%3Ecustom%3C%2Fstrong%3E%3C%2Fp%3E
when console.log ( data before post )
_token=bNPyuZroL8QIJN3beZJyFYaVELWIyNb9kpvX48Zn&csrf_token=bNPyuZroL8QIJN3beZJyFYaVELWIyNb9kpvX48Zn&title=qwqgqw&description=qgqg&body=%3Cp%3E%3Cstrong%3Ecustom%3C%2Fstrong%3E%3C%2Fp%3E&type=promotion
$('#addpromotionform').on('submit', function(ed) {
tinymce.triggerSave();
ed.preventDefault();
var TinyAjaxPost = $('#addpromotionform').serialize();
var formData = new FormData(this);
console.log(TinyAjaxPost);
$.ajax({
type: "post",
url:'{{URL::to("/admin/blog/create")}}',
data: formData,
cache:false,
dataType: 'html',
contentType: false,
processData: false,
success: function(data) {
console.log('success'+Object.values(data.message));
},
error: function(error) {
console.log('error'+error);
}
});
});
but when post to controller i check with dd($request)
body don't have html tag but have only raw text ... custom
public function admin_blog_create(Request $request)
{
$file_name = time() . '.' . request()->image->getClientOriginalExtension();
$request->image->move(public_path('image/tinymce'), $file_name);
$tiny = [
'image' => $file_name,
'title' => $request->title,
'description' => $request->description,
'body' => $request->body,
'type' => 'blog',
];
blog::create($tiny);
return response()->json(['status'=>true, 'message' => $request->body]);
/* return redirect()->back(); */
}
and i try to use Get with url when check data with dd($request) have only raw text custom
Tools
Laravel 9
TinyMCE 6
How i post or get with full html to database ?
XSS Protection it is a problem.
i'm try to disable xss in controller
$this->middleware('XSS');
Can post ( request ) html data to database
enter image description here
Type this code if you are experiencing error 419
// Ajax CSRF Setup Code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The correct way to send, in addition to viewing the data in the console
$('#addpromotionform').on('submit', function(ed) {
ed.preventDefault();
//console log data
var TinyAjaxPost = $('#addpromotionform').serialize();
var copy = $("#addpromotionform iframe").contents().find('#tinymce').clone();
copy = $(copy).html();
console.log(TinyAjaxPost,copy);
$.ajax({
type: "post",
url:'{{URL::to("/admin/blog/create")}}',
data: new FormData(this),
dataType: 'JSON',
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log('success'+Object.values(data.message));
},
error: function(error) {
console.log('error'+error);
}
});
});

Laravel ajax auto populate field based on selection

I am working to solve an ajax issue I have where I am trying to auto populate an amount field based on the selection from the drop down box.
My table is layout as follows (Table name is Otheritemsmapping):
ID | Item | Amount
1 | Item 1 | Amount 1
2 | Item 2 | Amount 2
My modal in my Blade looks like this
<div class="modal fade" id="accountpayModal" tabindex="-1" role="dialog" aria-labelledby="accountpay" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h3 class="modal-title" id="addaccountModal">Pay from Account of {{$member->first_name}} {{$member->last_name}}</h3>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{!!Form::open(array('action' => ['AccountController#item'], 'method'=>'POST', 'class'=>'form-horizontal'))!!}
<div class="modal-body">
<input type="hidden" name="member" value="{{$member->id}}">
<label class="label-control">Item:</label>
<div class="input-group">
<div class="form-group">
<select type="text" class="selectpicker" data-sytle="select-with-transition" name="item" value="C" id="selectBox">
#foreach ($otheritems as $o)
<option value ={{$o->item}}>{{$o->item}}</option>
#endforeach
</select>
</div>
</div>
<label class="label-control">Amount:</label>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" name="amount" id="textField">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-round btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-round btn-primary">Save Changes</button>
</div>
{!!Form::close()!!}
</div>
</div>
</div>
I have the following JS in the same file as the above modal
<script>
$('#selectBox').change(function() {
var id = $(this).val();
var url = '{{ route("getPayments", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (reponse != null) {
$('textField').val(response.amount);
}
}
});
});
</script>
I have the following on the Controller for getPayments
public function getPayments($id = 0)
{
$data = Otheritemmapping::where('item', $id)->first();
return response()->json($data);
}
I have added the following to my Web.php file
Route::get('get/payments/{id}', 'MemberController#getPayments')->name('getPayments');
However when selecting an item from the dropdown ($o->item), the amount is not being populated in the Amount field.
Any help would be great,
Thanks
in your code there's some typos.
<script>
$('#selectBox').change(function() {
let id = $(this).val();
let url = '{{ route("getPayments", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (response != null) {
$('#textField').val(response.amount);
}
}
});
});
</script>
hope this will solve your problem. if still there's anything wrong then check the browser developer console. let me know the error and i will update the answer for you.
you should use id as the option value as id is unique.

Laravel - How to capture Ajax Request Payload Data?

Not a Duplicate Question!!!
Here is my code, using Laravel 5.4.
Form in .blade.php file:
<form id="read-data-form" name="form" method="post" enctype="multipart/form-data" class="form-horizontal">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<input name="comCode" id="comCode" type="hidden" value=""/>
<label><span class="text-danger">*</span> Upload File :</label>
<input name="file" id="fileToUpload" type="file" accept="text/*" />
</div>
</div>
</div>
<div class="row">
<div class="col-md-6"></div>
<div class="col-md-6 ">
<div class="text-right">
<button type="submit" class="btn operations-btn btn-default" id="upload">Upload</button>
<button type="button" class="btn operations-btn btn-default" id="stop">Stop</button>
</div>
</div>
</div>
</form>
Ajax-request in .js file:
$("form #read-data-form").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
var promise = $.ajax({
url: 'read_data/file/check',
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false,
encode: true
});
promise.done(function(response){
});
promise.fail(function(error){
});
promise.always(function(){
});
}
Browser Console > Network > Headers > Request Payload:
Route in web.php file:
Route::post('read_data/file/check', 'ReadDataController#checkFile');
checkFile() method in ReadDataController.php file:
public function checkFile(Request $request)
{
$comCode = trim($request->comCode);
$file = $request->file('file');
dd($file);
}
Browser Console > Network > Preview > Request Payload:
This is how output of dd().
Issue:
File could not be captured as in a normal 'multipart/form-data' form without ajax request.
OK. Finally, I have a solution which is given by a senior person.
Removed this code:
$file = $request->file('file');
Added the following codes:
$uploadDirPath = 'C:/uploaded_files/';
$uploadFile = "moved_uploded_file.txt";
$request->file('file')->move($uploadDirPath, $uploadFile);
$uploaded_file = $uploadDirPath.$uploadFile;

Cannot read multipart/form-data from request in Laravel

I am trying to send form with upload file and multipart/form-data encoding using AJAX. I am using this form:
{!! Form::model($user, ['method' => 'PATCH', 'url' => ['/administrator/users', $user->id], 'class' => 'form-horizontal', 'files' => 'true', 'id' => 'userEdit']) !!}
<div class="modal-body">
<div class="form-group">
<label class="col-sm-3 control-label">Avatar:</label>
<div class="col-sm-9">
<img src="/dashboard/assets/img/avatar/{{ $user->profile->avatar }}" class="img-circle m-b" />
<input type="file" name="avatar" />
</div>
</div>
<hr />
<div class="form-group">
<label class="col-sm-3 control-label">Name:</label>
<div class="col-sm-9">
<input type="text" name="first_name" value="{{ $user->profile->first_name }}" class="form-control" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label">Surname:</label>
<div class="col-sm-9">
<input type="text" name="last_name" value="{{ $user->profile->last_name }}" class="form-control" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" class="btn btn-info" data-user-id="{{$user->id}}">Save</button>
</div>
{!! Form::close() !!}
I try to send data with Ajax like this:
$('#editUser').submit('#userEdit', function(event) {
event.preventDefault();
$.ajax({
type: 'PATCH',
url: '/administrator/users/1',
data: new FormData(userEdit),
processData: false,
contentType: false,
mimeType: "multipart/form-data",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
alert(data);
},
error: function(xhr, str){
alert(str);
}
});
});
And in result, I cannot read inputs from request in controller. It returns an empty array.
public function update($id, Request $request){
dd($request->all());
}
I think that I'm doing something wrong with sending multipart data. How to send it correctly?
It seems that you aren't adding FormData properly and your event seems to be broken, you should add the data in ajax like this:
$('#editUser').on('submit', function(event) {
event.preventDefault();
var form = $(this); // You need to use standard JS object here
var formData = new FormData(form);
$.ajax({
type: 'PATCH',
url: '/administrator/users/1',
data: formData,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function(data) {
alert(data);
},
error: function(xhr, str){
alert(str);
}
});
});
Hope this helps!

laravel 5.1 formData - AJAX - PHP- Uploading multiple files

I can not get the formData from the file upload
form.blade.php
<form method="POST" class="form-horizontal" enctype="multipart/form-data" id="modal-file-upload">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="folder" value="" id="modal-file-upload-folder">
<div class="modal-header">
<h4 class="modal-title">Upload New File</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label for="file" class="col-sm-3 control-label">
File
</label>
<div class="col-sm-8">
<input multiple="true" accept="image/*" required="true" id="fileToUpload" type="file" name="file[]">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" onclick="close_upload_view()">Cancel</button>
<button class="btn btn-primary" id="btn-upload">Upload File</button>
</div>
</form>
Controller
public function uploadMultiFile(Request $request) {
// getting all of the post data
$data = $request->input('formData');
var_dump($data); current return null
}
<script>
// Confirm file delete
function close_upload_view() {
$("#modal-file-upload").modal("hide");
return false;
}
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$("#modal-file-upload").submit(function(e){
e.preventDefault();
//var formData = new FormData(document.getElementById('modal-file-upload')[0]);
var fd = new FormData();
var ins=document.getElementById('fileToUpload').files.length;
for(var x=0;x<ins;x++)
{
fd.append("fileToUpload[]", document.getElementById('fileToUpload').files[x]);
}
var folder = $("input#modal-file-upload-folder").val();
var token = $("input[name=_token]").val();
var dataString = 'formData='+fd+'&folder='+folder+'&token='+token;
$.ajax({
type: "POST",
url: '{!! url() !!}/admin/upload/multifile',
cache: false,
data : dataString,
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server it
dataType: 'JSON',
success : function(data){
console.log(data);
}
},"json");
});
</script>

Resources