Submitting two DropZones together with Ajax - javascript

I have a form that I need to submit, as well as two drop zones, I am having no problem submitting them separately but I would like to submit them all as one.
HTML:
<form id="add-product-form">
<div class="form-group row">
<label for="add-product-visible" class="col-4 col-form-label">Visibility</label>
<div class="col-8">
<select class="form-control" id="add-product-visible" required>
<option value="1">Shown</option>
<option value="0">Hidden</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="add-product-brand" class="col-4 col-form-label">Brand</label>
<div class="col-8">
<input class="form-control" type="text" value="" id="add-product-brand" maxlength="50" required>
</div>
</div>
<h4>Product Image Upload</h4>
<div id="photo_upload_primary" action="/file-upload" class="dropzone m-b-15"></div>
<div id="photo_upload_secondary" action="/file-upload" class="dropzone"></div>
<!-- Preview -->
<div class="mt-3" id="formfiles"></div>
<!-- File preview template -->
<div class="d-none" id="formtemplate">
<div class="card mb-3">
<div class="p-2">
<div class="row align-items-start">
<div class="col-auto">
<img data-dz-thumbnail src="#" class="avatar border rounded">
</div>
<div class="col pl-0">
<a href="#" class="text-muted font-weight-bold" data-dz-name></a>
<a href="#" class="text-muted font-weight-bold dz-id" data-dz-id></a>
<p class="mb-0"><small data-dz-size></small>
<small class="d-block text-danger" data-dz-errormessage></small></p>
</div>
<div class="col-auto pt-2">
<a class="btn-lg text-danger" href="#" data-dz-remove><i class="icon-trash-2"></i></a>
</div>
</div>
</div>
</div>
</div>
</form>
<button type="button" class="btn btn-light btn-shadow" onclick="upload()">Upload Images</button>
<button type="submit" form="add-product-form" class="btn btn-light btn-shadow">Submit Form</button>
Javascript:
dropzone.autoDiscover = false;
var image_width = 380, image_height = 507;
var photo_upload_primary = new Dropzone("#photo_upload_primary",{
maxFilesize: 1,
maxFiles: 1,
acceptedFiles: "image/*",
autoProcessQueue: false,
url: "upload.php",
previewsContainer: "#formfiles",
previewTemplate: $("#formtemplate").html(),
dictFileTooBig: "Image is too large ({{filesize}}MiB). Max file size is {{maxFilesize}}MiB.",
dictInvalidFileType: "This file is not an image.",
dictMaxFilesExceeded: "You have already uploaded a primary product image.",
dictDefaultMessage: "Click or drop primary product image here",
success: function (file, response) {
console.log(response);
},
error: function (file, response) {
$.notify({
message: response
},{
type: "danger"
});
this.removeFile(file);
},
init: function() {
this.on("thumbnail", function(file) {
if (file.width !== image_width || file.height !== image_height) {
file.rejectDimensions();
}
else {
file.acceptDimensions();
}
});
},
accept: function(file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function() {
done("Product image resolution outside of specifications. Resolution must be "+image_width+"px x "+image_height+"px");
};
},
renameFile: function (file) {
var ext = file.name.substring(file.name.lastIndexOf('.')+1);
var newName = 'primary.' + ext;
return newName;
},
});
var photo_upload_secondary = new Dropzone("#photo_upload_secondary",{
maxFilesize: 1,
maxFiles: 1,
acceptedFiles: "image/*",
autoProcessQueue: false,
url: "upload.php",
previewsContainer: "#formfiles",
previewTemplate: $("#formtemplate").html(),
dictFileTooBig: "Image is too large ({{filesize}}MiB). Max file size is {{maxFilesize}}MiB.",
dictInvalidFileType: "This file is not an image.",
dictMaxFilesExceeded: "You have already uploaded a secondary product image.",
dictDefaultMessage: "Click or drop secondary product image here",
success: function (file, response) {
console.log(response);
},
error: function (file, response) {
$.notify({
message: response
},{
type: "danger"
});
this.removeFile(file);
},
init: function() {
this.on("thumbnail", function(file) {
if (file.width !== image_width || file.height !== image_height) {
file.rejectDimensions();
}
else {
file.acceptDimensions();
}
});
},
accept: function(file, done) {
file.acceptDimensions = done;
file.rejectDimensions = function() {
done("Product image resolution outside of specifications. Resolution must be "+image_width+"px x "+image_height+"px");
};
},
renameFile: function (file) {
var ext = file.name.substring(file.name.lastIndexOf('.')+1);
var newName = 'secondary.' + ext;
return newName;
}
});
function upload(){
photo_upload_primary.processQueue();
photo_upload_secondary.processQueue();
}
$('#add-product-form').submit(function (e) {
e.preventDefault();
var $form = $(this);
if (!$form.valid) return false;
if (photo_upload_primary.getQueuedFiles().length == 0) {
$.notify({
message: "Please upload a primary product photo."
},{
type: "danger"
});
return false;
}
if (photo_upload_secondary.getQueuedFiles().length == 0) {
$.notify({
message: "Please upload a secondary product photo."
},{
type: "danger"
});
return false;
}
addproduct();
});
function addproduct(){
var datafeilds = Array.from(document.querySelectorAll("[id^='add-product-']"));
var data = {};
datafeilds.forEach(function(field){
let replace = field.id.replace("add-product-", "");
data[replace] = field.value;
});
$.ajax({
type: 'POST',
url: 'addproduct-pdo.php',
data: {data: data},
dataType: 'json',
success: function(data) {
$.notify({
message: data.message
},{
type: data.response
});
if (data.response == "success"){
$("#add-product-form").trigger('reset');
photo_upload_primary.removeAllFiles();
photo_upload_secondary.removeAllFiles();
}
}
});
}
PHP (upload.php):
$ds = DIRECTORY_SEPARATOR;
$foldername = "./uploads";
if (!empty($_FILES)) {
$fileupload = basename( $_FILES['file']['name']);
$fileType = $_FILES['file']['type'];
$fileSize = $_FILES['file']['size'];
$tempFile = $_FILES['file']['tmp_name'];
$targetPath = dirname( __FILE__ ) . $ds. $foldername . $ds;
$targetFile = $targetPath.$fileupload;
move_uploaded_file($tempFile,$targetFile);
echo "File uploaded";
}
PHP (addproduct-pdo.php):
try {
$options = [
\PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION,
\PDO::ATTR_DEFAULT_FETCH_MODE => \PDO::FETCH_ASSOC,
\PDO::ATTR_EMULATE_PREPARES => false,
];
$conn = new PDO("mysql:charset=utf8mb4;host=$servername;dbname=$dbname", $username, $password);
function escape_mysql_identifier($field){
return "`".str_replace("`", "``", $field)."`";
}
function prepared_insert($pdo, $table, $data) {
$keys = array_keys($data);
$keys = array_map('escape_mysql_identifier', $keys);
$fields = implode(",", $keys);
$table = escape_mysql_identifier($table);
$placeholders = str_repeat('?,', count($keys) - 1) . '?';
$sql = "INSERT INTO $table ($fields) VALUES ($placeholders)";
$pdo->prepare($sql)->execute(array_values($data));
}
$data = array_filter($data);
prepared_insert($conn, 'products', $data);
$id = $conn->lastInsertId();
if ($id > 1) {
echo json_encode(array('response'=>'success','message'=>'Product successfully added as ID # '.$id));
}else{
echo json_encode(array('response'=>'danger','message'=>'Product not successfully added'));
}
}catch(PDOException $e){
echo json_encode(array('response'=>'danger','message'=>$e->getMessage()));
}
$conn = null;
I am having trouble on two things:
How can I submit both DropZone's as one?
How can I submit the DropZone(s) with the Ajax? I am going to need to pass off the $id from addproduct-pdo.php to either the DropZone Javascript or upload.php for it to name the file correctly.
Thanks!

Related

php codeigniter Video Upload Not Uploaded Video file

When uploading image files, the upload is complete and successful, but when uploading the video file, it is not uploaded and it does not show where the error is
HTML Code:
<div class="row mb-5">
<div class="col-md-12">
<input type="file" name="slider_image" id="" class="form-control mb-5" onchange="homeSliderUpload(this)">
<div class="progress mb-5" style="--sa-progress--value: 0%">
<div class="progress-bar progress-bar-sa-primary" role="progressbar" aria-valuenow="25" aria-valuemin="0" aria-valuemax="100">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script>
function homeSliderUpload(form) {
alert("First");
var file_data = $("input[name='slider_image']").prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "<?php echo base_url(); ?>/Path/VedioUploader",
dataType: 'text',
method: "post",
cache: false,
contentType: false,
processData: false,
data: form_data,
success: function(data) {
var rJson = $.parseJSON(data);
if (rJson.status == true) {
$(".progress").attr("style", "--sa-progress--value: 100%");
$("input[name='slider_image']").val('');
setInterval(() => {
location.reload();
}, 1000);
} else {
alert("Error");
}
}
});
}
php Code ( Ajax Code):
public function VedioUploader()
{
$validateImage = $this->validate([
'file' => [
'uploaded[file]',
'mime_in[file, video/mp4, image/png, image/jpg,image/jpeg, image/gif]',
'max_size[file, 1000000000]',
],
]);
if ($validateImage) {
$imageFile = $this->request->getFile('file');
$folder = "Vedio/";
$fileName = rand(10005, 100005) . time() . ".mp4";
$imageFile->move($folder, $fileName);
$data = [
'img_name' => $imageFile->getClientName(),
'file' => $imageFile->getClientMimeType(),
'type' => $imageFile->getClientExtension(),
];
if ($fileName) {
$homeSliderModel = new VedioUplaod();
$home_slider["slider_file_url"] = $folder . "/" . $fileName;
$home_slider["slider_show"] = 1;
$home_slider["slider_order"] = 0;
$homeSliderModel->insert($home_slider);
if (!$homeSliderModel->errors()) {
echo json_encode([
"status" => true,
"slider_id" => $homeSliderModel->getInsertID(),
"file_url" => $folder . "/" . $fileName,
"order" => 0
]);
}
}
}
}
I tried removing the image types and retrying to upload the images, but it didn't work. It was similar to uploading the video. I thought it was because of the type, but nothing happened.
'mime_in[file, video/mp4]',

Laravel form with dropzone saves twice to database

I have a model called Masseur and another model MasseurImage connected with a belongsTo() relationship. I also have a form with some basic inputs and Dropzone image upload integrated. The idea is when the "Create new masseur" form is submitted, it creates a new Masseur entry in the db, and creates many MasseurImage entries (based on how many images has been added into the dropzone field).
Everything works fine, except the Masseur model is saved twice in the database after the form is submitted.
View
<form method="post" id="etCreateMasseurForm" action="{{ route('masseur.add') }}" name="etCreateMasseurForm" enctype="multipart/form-data">
#csrf
<input type="hidden" name="masseur_id" id="masseur_id">
<div class="form-group mb-3">
<label class="form-label" for="nickname">Becenév</label>
<input class="form-control" type="text" name="nickname" id="nickname" required>
</div>
<div class="form-group mb-3">
<label class="form-label" for="name">Név</label>
<input class="form-control" type="text" name="name" id="name" required>
</div>
<div id="dropzoneDragArea" class="dropzone dz-default dz-message dropzoneDragArea form-control"></div>
</form>
Controller
public function store(Request $request)
{
$masseur = Masseur::create($request->all());
if ($request->hasFile('file')) {
foreach ($request->file('file') as $file) {
$filename = $file->store('public/files/'.$masseur->id);
MasseurImage::create([
'masseur_id' => $masseur->id,
'filename' => $filename
]);
}
}
return response()->json(['status' => "success", 'masseur_id'=> $masseur->id]);
}
Javascript
Dropzone.autoDiscover = false;
let token = $('meta[name="csrf-token"]').attr('content');
$(function () {
var myDropzone = new Dropzone("div#dropzoneDragArea", {
paramName: "file",
url: "{{ route('masseur.add') }}",
addRemoveLinks: true,
autoProcessQueue: false,
uploadMultiple: true,
parallelUploads: 100,
maxFiles: 100,
params: {
_token: token
},
init: function () {
var myDropzone = this;
$("form[name='etCreateMasseurForm']").submit(function (event) {
event.preventDefault();
URL = $("#etCreateMasseurForm").attr('action');
formData = $('#etCreateMasseurForm').serialize();
$.ajax({
type: 'POST',
url: URL,
data: formData,
success: function (result) {
if (result.status == "success") {
var masseur_id = result.masseur_id;
$("#masseur_id").val(masseur_id);
myDropzone.processQueue();
} else {
console.log("error");
}
}
});
});
this.on('sending', function (file, xhr, formData) {
let masseur_id = document.getElementById('masseur_id').value;
formData.append('masseur_id', masseur_id);
});
this.on("success", function (file, response) {
window.location.href = "/";
});
this.on("queuecomplete", function () {
});
}
});
});
Routes
Route::post('store-masseur', [MasseurController::class, 'store'])->name('masseur.add');

Separating Javascript Ajax codes in a js file in Laravel 8 does not work

I am new to ajax and run into problems. I do my best to explain my problem as best I can.
I am working on a project in Laravel 8.
The user has the option to select a photo. CropperJS is used for this.
Everything works fine, as soon as I put the javascript and Ajax codes in a separate file, I get an error message (The POST method is not supported for this route. Supported methods: GET, HEAD, PATCH.)
How can I get ajax call working in a separate file?
routes
Route::get('/image/create', 'ProfileImage\CreateController#create')->name('image.create');
Route::post('/image/store', 'ProfileImage\StoreController#store')->name('image.store');
Controller
public function create()
{
return view('pages.image.create');
}
public function store(StoreProfileImageRequest $request, ProfileImage $profileImage)
{
$profileId = auth()->user()->profile->id;
$validated = $request->validated();
$image = $validated['image_name'];
$this->profileImageRepositoryInterface->storeImage($profileImage, $profileId, $image, $validated);
session()->flash('success', 'Uw afbeelding is succesvol opgeslagen.');
return response()->json(
[
'status' => 'success',
'message' => 'my message.',
'url' => route('profile.index')
]);
}
form
<form class="text-left"
data-form-output="form-output-global"
data-form-type="contact"
method="post"
enctype="multipart/form-data"
>
#csrf
<div class="member-block-body">
<label for="upload_image">
</label>
<input type="file" name="image_name" class="image" id="upload_image">
</div>
<span class="invalid-feedback ct_invalid_feedback" role="alert">
<strong id="ajax_image_error"></strong>
</span>
</form>
Modal
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalImageCropper" aria-hidden="true">
<div class="modal-dialog ct_modal_lg modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">
#lang('Afbeelding aanpassen voordat u deze uploadt.')
</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">
x
</span>
</button>
</div>
<div class="modal-body">
<div class="ct_img_container">
<div class="row">
<div class="col-md-8">
<img src="" id="sample_image" alt="">
</div>
<div class="col-md-4">
<div class="ct_cropper_image_preview"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" id="crop-image" class="btn btn-primary">
#lang('Opslaan')
</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">
#lang('Annuleren')
</button>
</div>
</div>
</div>
</div>
javascript
custom_function.js
$(document).ready(function () {
let $modal = $('#modal');
let image = document.getElementById('sample_image');
let cropper;
$('#upload_image').change(function (event) {
let files = event.target.files;
let done = function (url) {
image.src = url;
$modal.modal('show');
};
if (files && files.length > 0) {
reader = new FileReader();
reader.onload = function (event) {
done(reader.result);
};
reader.readAsDataURL(files[0]);
}
});
$modal.on('shown.bs.modal', function () {
cropper = new Cropper(image, {
aspectRatio: 1,
viewMode: 3,
preview: '.ct_cropper_image_preview'
});
}).on('hidden.bs.modal', function () {
cropper.destroy();
cropper = null;
});
$('#crop-image').click(function () {
$('#ajax_image_error').text('');
canvas = cropper.getCroppedCanvas({
width: 600,
height: 600
});
canvas.toBlob(function (blob) {
url = URL.createObjectURL(blob);
let reader = new FileReader();
reader.readAsDataURL(blob);
reader.onloadend = function () {
let base64data = reader.result;
$.ajax({
url: '{{ route("image.store") }}',
method: 'POST',
data: {
'_token': '{{ csrf_token() }}',
image_name: base64data
},
success: function (data) {
if (data.status === 'success') {
window.location = data.url;
$modal.modal('hide');
$("#image-preview").attr("src", base64data);
}
},
error: function (data) {
if (data.status === 422) {
let response = $.parseJSON(data.responseText);
$.each(response.errors, function (key, val) {
$("#" + "ajax_" + key + "_error").text(val[0]);
});
}
}
});
};
});
});
});
Thanx for your tips.
just solved the pronblem.
$.ajax({
url: '/image/store',
// url: '{{ route("image.store") }}',
method: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: {
// '_token': '{{ csrf_token() }}',
image_name: base64data
},
success: function (data) {
if (data.status === 'success') {
window.location = data.url;
$modal.modal('hide');
$("#image-preview").attr("src", base64data);
}
},
error: function (data) {
if (data.status === 422) {
let response = $.parseJSON(data.responseText);
$.each(response.errors, function (key, val) {
$("#" + "ajax_" + key + "_error").text(val[0]);
});
}
}
});

Laravel sending data by ajax

I am trying to send data from my form to back-end by ajax but it doesn't send all my data.
preview of sent data
array:6 [
"title" => "xxxxxxxxxxxx"
"slug" => "xxxxxx"
"description" => """xxxxxxxxxxxxxxxxx"""
"publish" => "1"
"user_id" => "1"
"thumbnail" => null
]
Issues
my description is in triple double qoute """ xxxx """ (not sure if it's ok)
Image (thumbnail) didn't send
Categories didn't send
code
form
{{ Form::model($post, array('route' => array('quickedit', $post->id), 'method' => 'POST', 'files' => true)) }}
<div class="modal-body text-left">
{{-- show success message --}}
<div class="msg"></div>
<input type="hidden" name="user_id" id="user_id" value="{{Auth::user()->id}}">
<div class="row">
<div class="col-md-12 mt-3">
{{ Form::label('title', 'Title') }}
{{ Form::text('title', null, array('class' => 'form-control')) }}
</div>
<div class="col-md-12 mt-3">
{{ Form::label('slug', 'Slug') }}
{{ Form::text('slug', null, array('class' => 'form-control')) }}
</div>
<div class="col-md-12 mt-3">
{{ Form::label('description', 'Description') }}
{{ Form::textarea('description', null, array('class' => 'form-control editor')) }}
</div>
<div class="col-md-6 mt-3">
<div class="row">
#if(!empty($post->thumbnail))
<div class="col-md-3">
<img class="img-thumbnail" src="{{url('/images')}}/{{$post->thumbnail}}" alt="{{$post->title}}">
</div>
<div class="col-md-9">
{{ Form::label('thumbnail', 'Thumbnail') }}
{{ Form::file('thumbnail', array('class' => 'form-control')) }}
</div>
#else
<div class="col-md-12">
{{ Form::label('thumbnail', 'Thumbnail') }}
{{ Form::file('thumbnail', array('class' => 'form-control')) }}
</div>
#endif
</div>
</div>
<div class="col-md-6 mt-3">
{{ Form::label('publish', 'Publish') }}
<select name="publish" id="publish" class="custom-select">
<option value="">Select</option>
<option value="1" {{ $post->publish == '1' ? 'selected' : '' }}>Publish</option>
<option value="0" {{ $post->publish == '0' ? 'selected' : '' }}>Draft</option>
</select>
</div>
<div class="col-md-6 mt-3">
{{ Form::label('categories', 'Categories') }}
<select name="categories[]" id="categories" class="custom-select selectbox" multiple>
#foreach($categories as $category)
<option value="{{$category->id}}">{{$category->title}}</option>
#if(count($category->children) > 0)
#foreach($category->children as $children)
<option class="pl-2" value="{{$children->id}}">{{$children->title}}</option>
#if(count($children->children) > 0)
#foreach($children->children as $child)
<option class="pl-4" value="{{$child->id}}">{{$child->title}}</option>
#if(count($child->children) > 0)
#foreach($child->children as $childf)
<option class="pl-5" value="{{$childf->id}}">{{$childf->title}}</option>
#endforeach
#endif
#endforeach
#endif
#endforeach
#endif
#endforeach
</select>
</div>
</div>
</div>
<div class="modal-footer">
<div class="msg"></div>
</div>
{{Form::close()}}
<button class="btn btn-primary updatepost" data-id="{{$post->id}}" type="submit">Update</button>
JavaScript
<script>
$(document).ready(function() {
$('.updatepost').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
var title = $('input[name="title"]').val();
var slug = $('input[name="slug"]').val();
var description = $('.editor').val();
var publish = $('#publish option:selected').val();
var user_id = $('input[name="user_id"]').val();
var thumbnail = $('input[name="thumbnail"]').val();
var categories= $('#categories option:selected').val();
// $(this).attr("disabled", "disabled");
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("/admin/quickedit")}}/'+encodeURI(prdfoId),
type: "POST",
dataType: "json",
data: {
title: title,
slug:slug,
description: description,
publish: publish,
user_id: user_id,
thumbnail: thumbnail,
categories: categories
},
success:function(data) {
$('.msg').empty().append("Updated Successfully");
}
});
});
});
</script>
route
Route::post('quickedit/{id}','BlogController#quickedit')->name('quickedit');
controller
public function quickedit(Request $request, $id)
{
dd($request->all());
$this->validate($request, array(
'title' => 'required',
'slug' => 'required',
'description' => 'required',
'user_id' => 'required|numeric',
'thumbnail' => 'nullable|image',
'publish' => 'required|numeric',
));
$post = Post::find($id);
$post = Post::where('id',$id)->first();
$post->title = $request->input('title');
$post->slug = $request->input('slug');
$post->description = $request->input('description');
$post->user_id = $request->input('user_id');
$post->publish = $request->input('publish');
if ($request->hasFile('thumbnail')) {
$thumbnail = $request->file('thumbnail');
$filename = 'Post' . '-' . time() . '.' . $thumbnail->getClientOriginalExtension();
$location = public_path('images/' . $filename);
Image::make($thumbnail)->resize(850, 565)->save($location);
$post->thumbnail = $filename;
$oldFilename = $post->thumbnail;
$post->thumbnail = $filename;
Storage::delete($oldFilename);
}
$post->save();
$post->tags()->sync($request->tags);
$post->categories()->sync($request->categories);
}
Any idea?
Update
Based on answer and comments the last code I ended up is:
$(document).ready(function() {
$('.updatepost').click(function (event) {
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
});
event.preventDefault();
var title = $('input[name="title"]').val();
var slug = $('input[name="slug"]').val();
var description = $('.editor').val();
var publish = $('#publish option:selected').val();
var user_id = $('input[name="user_id"]').val();
var thumbnail = $('input[type=file]')[0].files[0];
var categories= [];
$("#categories option:selected").each(function(){
categories.push($(this).val());
});
categories = JSON.stringify(categories);
//new
var formData = new FormData();
formData.append('thumbnail', thumbnail);
formData.append('title', title);
formData.append('slug', slug);
formData.append('description', description);
formData.append('publish', publish);
formData.append('user_id', user_id);
formData.append('categories', categories);
//new
var prdfoId = $(this).data('id');
$.ajax({
url: '{{url("/admin/quickedit")}}/'+encodeURI(prdfoId),
type: "POST",
dataType: "json",
data: formData,
contentType: false,
processData: false,
success:function(data) {
$('.msg').empty().append("Updated Successfully");
}
});
});
});
The result of this code is:
array:7 [
"thumbnail" => "undefined"
"title" => "xxxxxxx"
"slug" => "xxxxxxxxx"
"description" => """
xxxxx
"""
"publish" => "1"
"user_id" => "1"
"categories" => "[]"
]
issues
image is undefined
categories are not passed
description is in triple double qoutes """ xxxxx """
any idea?
Your quickedit method calling dd(), what dump data, then just die. Also, quickedit returns void. In must to be an object or array if you going to use AJAX+JSON.
If you send image file you need has to base64 if you need handle in json, Or need use FormData like this:
var formData = new FormData();
formData.append('image', $('input[type=file]')[0].files[0]);
$.ajax({
url: 'Your url here',
data: formData,
type: 'POST',
contentType: false, // NEEDED, DON'T OMIT THIS (requires jQuery 1.6+)
processData: false, // NEEDED, DON'T OMIT THIS
// ... Other options like success and etc
});
I think, a has a simplest way make two call firs send just json data, and then secound call is send the image.
var title = $('input[name="title"]').val();
var slug = $('input[name="slug"]').val();
var description = $('.editor').val();
var publish = $('#publish option:selected').val();
var user_id = $('input[name="user_id"]').val();
var thumbnail = $('input[name="thumbnail"]').prop('files');
var categories= $('#categories option:selected').val();
var formData = new FormData();
//Add a the file to fomr data
formData.append('image', thumbnail[0]);
//And need add data like this
formdData.append('title',title );

Symfony2 Ajax call to display a message on a specific condition

I am beginner in javascript and ajax and I just cant figure out how to display a message on some condition.
Lets say a user can increase or decrease the quantity of the product he wants to buy. I have made that (not saying it was easy). But if the product is out of stock he cant increase the quantity anymore. How can I show that in the message. For example if a user tries to increase the quantity, but the product is out of stock I want to display the message below on the same ajax call.
This is the controller:
public function addQuantityAction( Request $request ) {
$response = new JsonResponse();
$requestData = $request->request->all();
$productid = $requestData['product'];
$quantity = $requestData['quantity'];
/** logic*/
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('MpShopBundle:Product')->find($productid);
$qtyAvailable = $product->getStockAvailable();
$session = $this->getRequest()->getSession();
$cart = $session->get('cart', array());
if ( $qtyAvailable > $cart[ $productid ] ) {
$cart[ $productid ] = $cart[ $productid ] + 1;
$qtyAvailable = $qtyAvailable - 1;
$response->setData(array('success'=>true,'message'=>'Qunatity increased','amount' => $cart[ $productid ]));
$session->set('cart', $cart);
} else {
$response->setData(array('success'=>false,'message'=>'Out of stock'));
}
return $response;
}
The Ajax:
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
And the twig:
<div class="input-append">
<input class="span1" style="max-width:34px" placeholder="{{ key }}" value="{{ item }}" id="appendedInputButtons" size="16" type="text" data-id="{{ key }}"/>
<i class="icon-minus"></i>
<i class="icon-plus"></i>
<button class="btn btn-danger" type="button"><i class="icon-remove icon-white" style="color:white"></i></button>
<p> display message here </p>
</div>
You can also add class depands on success or error status of operation.
Ajax
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
if(data.message != 'undefined') {
$('#ajax_response--message').html(data.message)
}
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
<div class="input-append">
Twig
<p id="ajax_response--message"> display message here </p>
</div>

Categories