my data not update in the database in laravel 5.4 - javascript

I am using laravel 5.4 in my app I update some record through ajax jquery I get the data from form values through ajax function and append it in array and pass that array (formData in my code) to ajax data then when I request my data in controller it updated as null message in my database.
This is my view jquery function
$('#updateProduct').on('submit', function(e){
e.preventDefault(e);
var redirect_url = $(this).find("[name='redirect_url']").val();
var url = $(this).attr('action');
var method = $(this).attr('method');
var video = document.getElementById('videoToUpload').files[0];
// console.log(video);
var formData = new FormData();
formData.append('_method', 'patch');
formData.append('name', $(this).find("[name='name']").val());
formData.append('description', $(this).find("[name='description']").val());
formData.append('brand', $(this).find("[name='brand']").val());
formData.append('category', $(this).find("[name='category']").val());
formData.append('condition', $(this).find("[name='condition']").val());
formData.append('shipper', $(this).find("[name='shipper']").val());
formData.append('shipping_from', $(this).find("[name='shipping_from']").val());
formData.append('shipping_paid_by', $(this).find("[name='shipping_paid_by']").val());
formData.append('shipping_within', $(this).find("[name='shipping_within']").val());
formData.append('shipping_weight', $(this).find("[name='shipping_weight']").val());
formData.append('shipping_fee', $(this).find("[name='shipping_fee']").val());
formData.append('seller_get', $(this).find("[name='seller_get']").val());
formData.append('price_per_unit', $(this).find("[name='price_per_unit']").val());
formData.append('selling_fee', $(this).find("[name='selling_fee']").val());
formData.append('seller_id', $(this).find("[name='seller_id']").val());
formData.append('is_active', $(this).find("[name='is_active']:checked").val());
console.log(formData);
$.ajax({
type: method,
url: url,
dataType: 'JSON',
data: formData,
contentType: false,
processData: false,
success: function(data){
alert("Products updated successfullly");
console.log(data);
//window.location.href = redirect_url;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
In my controller
public function update(Request $request, $id)
{
return Response::json([
'message' => $request['name']
], 200);
if(!$request){
return Response::json([
'error' => [
'message' => 'Kindly provide all the required details'
]
], 422);
}
$product = Product::find($id);
$product->name = $request['name'];
$product->sku = $request['sku'];
$product->slug = $request['slug'];
$product->description = $request['description'];
$product->brand = $request['brand'];
$product->condition = $request['condition'];
$product->shipper = $request['shipper'];
$product->shipping_from = $request['shipping_from'];
$product->shipping_fee = $request['shipping_fee'];
$product->shipping_paid_by = $request['shipping_paid_by'];
$product->shipping_within = $request['shipping_within'];
$product->shipping_weight = $request['shipping_weight'];
$product->selling_fee = $request['selling_fee'];
$product->seller_get = $request['seller_get'];
$product->price_per_unit = $request['price_per_unit'];
///$product->seller_id = $request['seller_id'];
$product->is_active = $request['is_active'];
$product->save();
$category = ProductCategory::where('product_id', '=', $id);
$category->update([
'category_id' => $request['category']
]);
return Response::json([
'message' => $product
], 200);
}

Related

How to update image with AJAX in Laravel

I'm having problems updating a record with an image. I don't what I need to do. My image is stored in a public folder called 'img/products'
ProductController.php
This is my controller. It works well without modifying the image.
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price_neto' => 'required',
'iva' => 'required',
'price_total' => 'required',
'image' => '',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$products = Product::find($id);
$products->name = $request->input('name');
$products->category_id = $request->input('category_id');
$products->description = $request->input('description');
$products->price_neto = $request->input('price_neto');
$products->iva = $request->input('iva');
$products->price_total = $request->input('price_total');
$products->image = $request->input('image');
$products->save();
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
Product.js
All I know is that I have to use var formData = new FormData ($ ("# frmAddProduct") [0]); as in the store function. I can enter records with images but not edit them. My image is stored in a public folder called 'img/products'
$(document).ready(function() {
$("#btn-edit").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'PUT',
url: '/product/' + $("#frmEditProduct input[name=product_id]").val(),
data: {
name: $("#frmEditProduct input[name=name]").val(),
category_id: $("#frmEditProduct select[name=category_id]").val(),
description: $("#frmEditProduct input[name=description]").val(),
price_neto: $("#frmEditProduct input[name=price_neto2]").val(),
iva: $("#frmEditProduct input[name=iva2]").val(),
price_total: $("#frmEditProduct input[name=price_total2]").val(),
image: $("#frmEditProduct input[name=image]").val(),
},
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
});
function editProductForm(product_id) {
$.ajax({
type: 'GET',
url: '/product/' + product_id,
success: function(data) {
$("#edit-error-bag").hide();
$("#frmEditProduct input[name=name]").val(data.products.name);
$("#frmEditProduct select[name=category_id]").val(data.products.category_id);
$("#frmEditProduct input[name=description]").val(data.products.description);
$("#frmEditProduct input[name=price_neto2]").val(data.products.price_neto);
$("#frmEditProduct input[name=iva2]").val(data.products.iva);
$("#frmEditProduct input[name=price_total2]").val(data.products.price_total);
$("#frmEditProduct file[name=image]").val(data.products.image);
$("#frmEditProduct input[name=product_id]").val(data.products.id);
$('#editProductModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
You should check if the file exists before trying to delete, for example:
$product = Product::find($id);
if(!$product)
{
return response()->json(['error' => 'Product not found'], 404);
}
if (Storage::disk('local')->exists('img/products/'.$product->image)) {
Storage::disk('local')->delete('img/products/'.$product->image);
}
Take a look one example only:
public function update(UpdateProductFormRequest $request, $id)
{
$product = Product::find($id);
$data = $request->only('name','category_id','description',
'price_neto','iva','price_total');
if(!$product)
{
return response()->json(['error' => 'Product not found'], 404);
}
// when saving the file, delete the old file first
if ($request->hasFile('image')) {
$file = $request->file('image');
$original_filename = $file->getClientOriginalName();
// $mime = $file->getMimeType(); // Suggestion
$extention = $file->getExtension();
// $size = $file->getClientSize(); // Suggestion
$stored_filename = $original_filename; // md5($original_filename); // Suggestion
$file_path = storage_path('public/img/products/');
if (Storage::disk('local')
->exists("public/img/products/{$stored_filename}.{$extention}"))
{
Storage::disk('local')
->delete("public/img/products/{$recordSet->stored_filename}.{$extention}");
}
$file_moved = $file->move($file_path, "{$stored_filename}.{$extention}");
$data->image = "{$stored_filename}.{$extention}";
}
// Updating data
$result = $product->update($data);
if ($result) {
/* return redirect()
->route('products.index')
->withSuccess('Product was successfully updated'); */
return response()->json([
'message' => 'Product was successfully updated'
'product' => $product
]); // You don't have to put 200 because it's the default
}
/* return back()
->withErrors(['Unable to update the product'])
->withInput($request->input()); */
return response()->json(['error' => 'Unable to update the product'], 400);
}
It would be better if you create a form request to do your validations.
Don't forget to create links to the storage path:
php artisan storage:link
I think it would be helpful:
$("#btn-edit").click(function() {
var formData = new FormData($("#frmAddProduct")[0]);
formData.append('_method', 'put');
formData.append('_token', "{{ csrf_token() }}"); // if you are using Blade
var route= "{{ route('products.update', ['id' => ':id']) }}"; // if you are using Blade
route= route.replace(':id', $("#frmEditProduct input[name=product_id]").val())
$.ajax({
method: 'post',
url: route,
data: formData,
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
Is your js script in "Blade" ? If so, try it this way:
var image = '{{ asset("/img/products/_image_file") }}'
image.replace('_image_file', data.products.image)
$("#frmEditProduct file[name=image]").val(image)
Note that we can first use the "asset ()" helper to create the full path to use to find the image, but with a "_image_file" placeholder
After that, we use the replace () function to change the "_image_file" placeholder with the actual image file brought from the ajax response.
Something like this?
ProductController.php
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price_neto' => 'required',
'iva' => 'required',
'price_total' => 'required',
'image' => '',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$products = Product::find($id);
if ($request->hasFile('image')) {
$productImage = $request->file('image');
$productImageName = rand() . '.' . $productImage->getClientOriginalExtension();
if (Storage::disk('local')->exists("img/products/{$productImageName}")) {
Storage::disk('local')->delete("img/products/{$recordSet->$productImageName}");
}
$file_moved = $productImage->move(public_path('img/products'), $productImageName);
$data->image = "{$productImageName}";
}
$products->save([
'name' => $request->name,
'category_id' => $request->category_id,
'description' => $request->description,
'price_neto' => $request->price_neto,
'iva' => $request->iva,
'price_total' => $request->price_total,
'image' => $productImageName,
]);
return response()->json([
'error' => false,
'products' => $products,
]);
}
Product.js
$("#btn-edit").click(function() {
var formData = new FormData($("#frmEditProduct")[0]);
formData.append('_method', 'put');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/product/' + $("#frmEditProduct input[name=product_id]").val(),
data: formData,
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});

ajax passing two forms with codeigniter

I have a problem related with passing two forms in ajax to my controller code igniter. My first form is a file var formData = new FormData($('#form-upload')[0]);
and my second form consists of profile data $('#frm_patientreg').serialize()
now my problem is how can I pass these two forms in ajax?
I already tried this code:
var fileToUpload = inputFile[0].files[0];
if(fileToUpload != 'undefine') {
var formData = new FormData($('#form-upload')[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: $('#frm_patientreg').serialize()+formData,
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
}
else {
alert("No File Selected");
}
but it returns me an error.
When I tried to pass data:formData, only, my image file was successfully uploaded, but when I add the $('#frm_patientreg').serialize(), it outputs an error. How can I pass both forms?
Here is my controller:
public function addpatient() {
$config['upload_path'] = './asset/uploaded_images/';
$config['allowed_types'] = 'gif|jpg|jpeg|png';
$config['max_size'] = 1024 * 8;
$this->load->library('upload', $config);
if($this->upload->do_upload("file")) {
$upload_data = $this->upload->data();
$file_name = base_url().'asset/uploaded_images/'.$upload_data['file_name'];
$mypatiendid = $this->genpatient_id();
$patient_bday = $this->input->post('pabdate');
$DB_date = date('Y-m-d', strtotime($patient_bday));
$patient_height = $this->input->post('paheight');
$DB_height = $patient_height . " cm";
$patient_weight = $this->input->post('paweight');
$DB_weight = $patient_weight . " kg";
$data = array (
'patient_id' => $mypatiendid,
'patient_fname' => $this->input->post('pafname'),
'patient_mname' => $this->input->post('pamname'),
'patient_lname' => $this->input->post('palname'),
'patient_address' => $this->input->post('paaddress'),
'patient_contact_info' => $this->input->post('pacontact'),
'patient_bday' => $DB_date,
'patient_age' => $this->input->post('paage'),
'patient_height' => $DB_height,
'patient_weight' => $DB_weight,
'patient_sex' => $this->input->post('psex'),
'patient_civil_status' => $this->input->post('pmartialstat'),
'patient_photo' => $file_name,
);
var_dump($data);
}
else {
echo "File cannot be uploaded";
$error = array('error' => $this->upload->display_errors()); var_dump($error);
}
}
Not tested..but try this:
var FormTwo = new FormData();
$('#frm_patientreg input, #frm_patientreg select').each(function(index){
FormTwo.append($(this).attr('name'),$(this).val());
});
FormTwo.append('file', $('#frm_patientreg input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: siteurl+"sec_myclinic/addpatient",
data: {formTwo: FormTwo, formOne: formData},
processData: false,
contentType: false,
success: function(msg) {
alert("Successfully Added");
$('#frm_patientreg')[0].reset();
}
});
change this
data: $('#frm_patientreg').serialize()+formData,
into this
data: $('#frm_patientreg').serialize()+'&'+formData,

Symfony2 + Ajax: remove form error

I am trying to create entity via Symfony2 and Ajax. When I try to enter existing name, I want to get error under 'Name' textbox. After entering another correct name, I want error message to remove and submit from successfully. My code is not submitting correct data, but keeps adding more error messages.
Controller
public function createSubmitAction(Request $request){
$collection = new Collection();
$user = $this->getUser();
$form = $this->createForm(
new CollectionType(),
$collection
);
$form->handleRequest($request);
$colname = $form["name"]->getData();
$existing = $this->getDoctrine()->getRepository('CollectionBundle:Collection')->findBy(['name' => $colname, 'user' => $user]);
if ($existing != NULL) {
return new JsonResponse(['error' => 'already exists']);
}
if ($form->isValid() && $form->isSubmitted()) {
$em = $this->getDoctrine()->getManager();
$collection->setUser($user);
$em->persist($collection);
$em->flush();
return new JsonResponse([
'id' => $collection->getId(),
'name' => $collection->getName()
]);
}
}
Javascript
function createInObjectCollection(){
var $form = $('#create-in-object-form');
$($form).submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize()
}).done(function( data ) {
if (data.error){
$('<label class="form-error">Collection with such name already exists</label>').insertAfter('#mymini_collectionbundle_collection_name');
$('#mymini_collectionbundle_collection_name').addClass('error');
}
else{
$("#collection_bundle_add_to_collection option:first-child").after('<option value='+ data.id + '>' + data.name + '</option>');
$('#createCollectionModal').foundation('reveal', 'close');
}
});
});
}
I have a similar situation. And I use EventListener:
$builder->addEventListener(
FormEvents::PRE_SET_DATA,
function (FormEvent $event) {
$form = $event->getForm();
$data = $event->getData();
\\...
}
);
And you can use Events like "SUBMIT" and "PRE_SUBMIT".

How to upload file using ajax/jQuery with Symfony2

Could anyone help me?
I'm trying to write a script that when the user clicks an image, that this triggers an image in the database to be updated.
For this I wrote the code which temporarily makes the Caller Line of the method in the controller, but when I send the form it is not validated because of Cross-Site-Request-Forgery.
$("#upload_picture").on('click', function (e) {
e.preventDefault();
$("#bundle_user_file").trigger('click');
});
$("#bundle_user_file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('.active-img').attr('src', e.target.result);
};
reader.readAsDataURL(this.files[0]);
ajax_formData()
}
});
This is my Caller Line ajax, is do the treatment in the form with the FormData to post, caught the routes and the token. He calls route, but not sure if the image is going or not, even with the Inspector firefox.
function ajax_formData() {
var at = $("form[name=bundle_user]");
var formData = new FormData();
formData.append('file', $("input[type=file]")[0].files[0]);
var url = at.attr('action') + '?_token=' + $("#bundle_user__token").val();
$.ajax({
type: "PUT",
url: url,
data: formData,
success: function (data) {
alert("success: " + data.message);
},
fail: function (data) {
alert("error: " + data.message);
},
cache: false,
contentType: false,
processData: false,
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Avalia se tem suporte a propriedade upload
myXhr.upload.addEventListener('progress', function () {
/* faz alguma coisa durante o progresso do upload */
}, false);
}
return myXhr;
}
});
}
This is the method in controlodor it with a common call with the click the button to submit change my image. But as I said before the ajax call, he replied that the Token not available
public function updateAction(Request $request, $id)
{
$this->denyAccessUnlessGranted('ROLE_USER', null, 'Unable to access this page!');
$em = $this->getDoctrine()->getManager();
$entity = $this->getUser();
if ($entity->getId() != $id) {
$response = new JsonResponse(
array(
'message' => 'Não tem permissao'
), 400);
return $response;
}
$form_update = $this->updateForm($entity);
$form_update->handleRequest($request);
if ($form_update->isValid()) {
$entity->upload();
$em->persist($entity);
$em->flush();
return new JsonResponse(array('message' => 'Success!'), 200);
}
$response = new JsonResponse(
array(
'message' => $form_update->getErrors()
), 400);
return $response;
}
Firstly, I notice that your click event for #upload_image fires a click trigger on #bundle_user_file, but below that you are asking it to look for a change event. Therefore, this would do nothing.
You can re-generate a CSRF token if you want by calling the csrf token_manager service by doing this:
/** #var \Symfony\Component\Security\Csrf\CsrfTokenManagerInterface $csrf */
$csrf = $this->get('security.csrf.token_manager');
$token = $csrf->refreshToken($tokenId);
return new Response($token);
You can determine $tokenId in your form, if you want, or just use your picture ID, or whatever. Normally the CSRF token is generated automatically from your session, so you might want to check that too.
function upload_img(){
var file_data = $('.myform').find('.drawing').prop("files")[0];
var form_data = new FormData();
form_data.append("drawing", file_data);
$.ajax({
url: "upload.php",
type: "POST",
data: form_data,
contentType: false,
dataType:'json',
cache: false,
processData:false,
success: function(data)
{
},
error: function()
{
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class='myform'>
<input type='file' class='drawing' onchange='upload_img()' >
</form>

how to get the checkbox in edit modal popup in MVC-4

I'm using ajax to get the corresponding row values in modal popup for edit in MVC 4 razor..
for username textbox i get like this...
#Html.TextBoxFor(u => u.useredit.userName,new { #class = "input-xlarge focused", id="Edituname", type = "text" })
if i use same method for checkbox..
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
i'm getting plain checkbox.where i gone wrong..or is there any other way for check box,,
Controller:
for getting values through ajax
[HttpPost]
public ActionResult getUserState(int userid)
{
TBLAppUser user = new TBLAppUser();
user = _repository.GetUserByID(userid);
string[] data = new string[10];
data[0] = user.userName;
data[1] = user.firstName;
data[2] = user.lastName;
data[3] = user.email;
data[4] = user.userID.ToString();
data[5] = user.statusID.ToString();
data[6] = user.isdelete.ToString();
data[7] = user.userName;
data[8] = user.password;
data[9] = user.isActive.ToString();
return Json(data);
}
javascript:
<script type="text/javascript">
function Getuser(_StateId) {
var url = "/admin/getUserState/";
$.ajax({
url: url,
data: { userid: _StateId },
cache: false,
type: "POST",
success: function (data) {
$('#Edituname').val(data[0]);
$('#Editfname').val(data[1]);
$('#Editlname').val(data[2]);
$('#Editemail').val(data[3]);
$('#Editid').val(data[4]);
$('#state').val(data[5]);
$('#isdelete').val(data[6]);
$('#Editname1').val(data[7]);
$('#Editpsd').val(data[8]);
$('#EditActiv').val(data[9]);
},
error: function (response) {
alert("error:" + response);
}
});
}
view.cshtml:
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
i'm getting the unchecked checkbox in edit popup..pls smeone help me..thnks in advance...
For your view
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
Make the below changes and see if it working
[HttpPost]
public ActionResult getUserState(int userid)
{
data[9] = user.isActive.ToString()
return Json(data);
}
Try use prop() method
<script type="text/javascript">
function Getuser(_StateId) {
var url = "/admin/getUserState/";
$.ajax({
url: url,
data: { userid: _StateId },
cache: false,
type: "POST",
success: function (data) {
var editCheck=(data[9]=== 'true')?true:false;
$('#EditActiv').prop('checked',editCheck); //use prop()
}
});

Categories

Resources