it is my javascript code :
var input = document.getElementById('fileUpload').files[0].name;
var file = doc.output('blob');
var formData = new FormData();
formData.append('file', file);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$.ajax({
method: 'POST',
url:'/saveEditorFiles',
data: {formData,name:input},
processData: false,
contentType: false,
success: function(data){console.log(data)},
error: function(data){console.log(data)}
});
and its controller :
public function storeEditorFiles(Request $request)
{
$validatedData = $request->validate([
'file' => 'required|mimes:pdf',
]);
$file = $request->name('file');
$name = $file->getClientOriginalName();
$uniqueName = bin2hex(random_bytes(3)) . '.' .'pdf';
$file->move(public_path('TempFiles/'), $uniqueName);
$save = new TempFile;
$save->filename = $name;
$save->user_id = Auth::user()->id;
$save->UniqueFileName = $uniqueName;
$save->save();
$response = [
'name' => $name,
'file' => $file,
];
return Response::json(['success' => $response]);
}
the problem is that the file is saving in my database with the name "blob". I am trying to save it with its original name. Any help would be appreciated.
I Found an a soloution append child and in second parameter pass the targeted var name:
var realName= document.getElementById('fileUpload').files[0].name;
var formData = new FormData();
formData.append('file', file);
**formData.append('name','realName');** // realName is targeted file name
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$.ajax({
method: 'POST',
url:'/saveEditorFiles',
data: {formData,name:input},
processData: false,
contentType: false,
success: function(data){console.log(data)},
error: function(data){console.log(data)}
});
and in controller :
public function storeEditorFiles(Request $request)
{
$validatedData = $request->validate([
'file' => 'required|mimes:pdf',
]);
$file = $request->name('file');
$file = $request->name('realName');
$name = $file->getClientOriginalName();
$uniqueName = bin2hex(random_bytes(3)) . '.'
.'pdf';
$file->move(public_path('TempFiles/'),
$uniqueName);
$save = new TempFile;
$save->filename = $name;
$save->user_id = Auth::user()->id;
$save->UniqueFileName = $uniqueName;
$save->save();
$response = [
'name' => $name,
'file' => $file,
];
return Response::json(['success' => $response]);
}
How can I use custom error messages in a json response? I'm using Ajax to validate a login form in frontend and I've already manage how to display the Validator errors, but I can't figure out how I can retrieve a custom error message.
This is the controller:
public function LoginValid(Request $request){
$validator = Validator::make($request->all(), [
'email' => ['required', 'string', 'email' ],
'password' => ['required', 'string', 'max:255'],
]);
if($validator->passes()){
$user = User::where('email', $request->email)->first();
if ($user &&
Hash::check($request->password, $user->password)) {
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
return redirect()->intended('dashboard');
}else{
return response()->json('should be any custom message here');
}
}
}else{
return response()->json(['error'=>$validator->errors()->all()]);
}
}
And here's the Ajax:
$(document).ready(function() {
$("#btn-login").click(function(e) {
e.preventDefault();
var _token = $("input[name='_token']").val();
var email = $("input[name='email']").val();
var password = $("input[name='password']").val();
$.ajax({
url: "{{ route('login-valid') }}",
type: 'POST',
data: { _token: _token, email: email, password:password },
success: function(data) {
if ($.isEmptyObject(data.error)) {
window.location.href = 'dashboard';
} else {
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg(msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display', 'block');
$.each(msg, function(key, value) {
$(".print-error-msg").find("ul").append('<li>' + value + '</li>');
});
}
});
you can customize validation messages in this way. I am using your code for an example.
$validator = Validator::make($request->all(), [
'email' => ['required', 'string', 'email' ],
'password' => ['required', 'string', 'max:255'],
], [
'email.required' => 'email is required',
'email.string' => 'email should be valid',
'email.email' => 'email should be in proper format'
.
.
.
.
and so on
]);
above code will overwrite the laravel default messages.
I'm making a request to my laravel backend.
But the request gets treated as a GET instead of a POST, I can't find that the problem is..
here is the function:
this.$axios
.post('/create_car', {
data: formData
})
.then(res => {
this.status = true
this.isCreatingCar = false
})
and trying to recieve it in this controller function:
public function createCar(Request $request) {
$title = $request->title;
$previewText = $request->previewText;
$fuel = $request->fuel;
$gearbox = $request->gearbox;
$brand = $request->brand;
$model = $request->model;
$year = $request->year;
$miles = $request->miles;
$price = $request->price;
$carType = $request->carType;
$images = $request->images;
$car = Car::create([
'title' => $title,
'previewText' => $previewText,
'fuel' => $fuel,
'gearbox' => $gearbox,
'brand' => $brand,
'model' => $model,
'year' => $year,
'miles' => $miles,
'price' => $price,
'carType' => $carType
]);
// store each image
foreach($images as $image) {
$imagePath = Storage::disk('uploads')->put('/cars' . '/' . $car->id, $image);
carImage::create([
'carImageCaption' => $title,
'carImagePath' => 'uploads' . $imagePath,
'carId' => $car->id
]);
}
return response()->json(['errors' => false, 'data' => $car]);
}
here is the route:
Route::group(['middleware' => 'throttle:20.5'], function () {
Route::post('/create_car', 'CarController#createCar');
});
in the xamp log it seems like it sends two request first a POST and then a GET 3 seconds apart
Ok to fix this you need to call the route properly, since the route inside your api.php call it like this:
this.$axios
.post('/api/create_car', {
data: formData
})
.then(res => {
this.status = true
this.isCreatingCar = false
})
iam try to upload image by ajax in laravel.
here is my js code :
$('#profile_picture').on('submit', function(event){
event.preventDefault();
$.ajax
({
type: "POST",
url: "{{url('all/update-profile-picture')}}",
data:new FormData(this),
dataType:'json',
type:'post',
processData: false,
contentType: false,
cache:false,
}).done( function(data){
//swal("Good job!", "Your information has been successfully updated!", "success")
console.log('Ajax was Successful!')
console.log(data)
}).fail(function(xhr, textStatus, error){
console.log(textStatus)
console.log(error)
});
});
here is controller code :
$validation = Validator::make($request->all(), [
'profile_photo'=> 'required|image|mimies:jpeg,png,jpg,gif|max:2048'
]);
if ($validation->passes()) {
//$image = $request->file('profile_photo');
$new_name = time().'.'.$request->image->getClientOriginalExtension();
$request->image->move(public_path("photo"),$new_name);
return response()->json([
'message' => 'Image uploaded successfully'
]);
} else {
return response()->json([
'message' => $validation->errors()->all(),
'profile_photo' => '',
'class_name' => 'danger'
]);
}
I hope its my controller's problem . when click submit with blank , its seen error message in console.
I don't understand whats the problem ??
you need to use file() method for get your request file.
$validation = Validator::make($request->all(), [
'profile_photo'=> 'required|image|mimies:jpeg,png,jpg,gif|max:2048'
]);
if ($validation->passes()) {
$new_name = time().'.'.$request->file('profile_photo')->getClientOriginalExtension();
$request->file('profile_photo')->move(public_path("photo"),$new_name);
return response()->json([
'message' => 'Image uploaded successfully'
]);
}
return response()->json([
'message' => $validation->errors()->all(),
'profile_photo' => '',
'class_name' => 'danger'
]);
Hi i want to display state drop down based on country select in magento product from in admin can any one please given an idea how to do this.i have googled it but in vain .
Sunel.please check the fallowing solution it may help you.
Open your form which is in Yournamespace/Modulename/Block/Adminhtml/Modulename/Edit/Tab/Form.php then add below fields
$country = $fieldset->addField('country', 'select', array(
'name' => 'country',
'label' => 'Country',
'values' => Mage::getModel('adminhtml/system_config_source_country') ->toOptionArray(),
'onchange' => 'getstate(this)',
));
$fieldset->addField('state', 'select', array(
'name' => 'state',
'label' => 'State',
'values' => Mage::getModel('modulename/modulename')->getstate('AU'),
));
/*
* Add Ajax to the Country select box html output
*/
$country->setAfterElementHtml("<script type=\"text/javascript\">
function getstate(selectElement){
var reloadurl = '". $this->getUrl('modulename/adminhtml_modulename/state') . "country/' + selectElement.value;
new Ajax.Request(reloadurl, {
method: 'get',
onLoading: function (stateform) {
$('state').update('Searching...');
},
onComplete: function(stateform) {
$('state').update(stateform.responseText);
}
});
}
</script>");
Now Create State Action in modulenamecontroller.php file which will be like this
public function stateAction() {
$countrycode = $this->getRequest()->getParam('country');
$state = "<option value=''>Please Select</option>";
if ($countrycode != '') {
$statearray = Mage::getModel('directory/region')->getResourceCollection() ->addCountryFilter($countrycode)->load();
foreach ($statearray as $_state) {
$state .= "<option value='" . $_state->getCode() . "'>" . $_state->getDefaultName() . "</option>";
}
}
echo $state;
}
thank you.
/*
* Add Ajax to the Country select box html output
*/
$url = Mage::getBaseUrl();
$country->setAfterElementHtml("<script type=\"text/javascript\">
function getstate(selectElement){
var reloadurl = '".$url.'admin/customer/state/' . "country/' + selectElement.value;
new Ajax.Request(reloadurl, {
method: 'POST',
onComplete: function(){
},
success: function (response) {
alert(response)
}
});
}
</script>");
Hi Santosh Pal Sir...
i am writing my whole code , please try it on your system... When i choose country then loding process is complete but no value is feteching in the state dropdown.
**app/code/local/Mage/Adminhtml/Block/Customer/Edit/Tab/Account.php** ,please find my custome code
<?php
class Mage_Adminhtml_Block_Customer_Edit_Tab_Account extends Mage_Adminhtml_Block_Widget_Form
{
/**
* Initialize block
*/
public function __construct()
{
parent::__construct();
}
/**
* Initialize form
*
* #return Mage_Adminhtml_Block_Customer_Edit_Tab_Account
*/
public function initForm()
{
$form = new Varien_Data_Form();
$form->setHtmlIdPrefix('_account');
$form->setFieldNameSuffix('account');
$customer = Mage::registry('current_customer');
/** #var $customerForm Mage_Customer_Model_Form */
$customerForm = Mage::getModel('customer/form');
$customerForm->setEntity($customer)
->setFormCode('adminhtml_customer')
->initDefaultValues();
$fieldset = $form->addFieldset('base_fieldset', array(
'legend' => Mage::helper('customer')->__('Account Information')
));
$attributes = $customerForm->getAttributes();
foreach ($attributes as $attribute) {
/* #var $attribute Mage_Eav_Model_Entity_Attribute */
$attribute->setFrontendLabel(Mage::helper('customer')->__($attribute->getFrontend()->getLabel()));
$attribute->unsIsVisible();
}
$disableAutoGroupChangeAttributeName = 'disable_auto_group_change';
$this->_setFieldset($attributes, $fieldset, array($disableAutoGroupChangeAttributeName));
$form->getElement('group_id')->setRenderer($this->getLayout()
->createBlock('adminhtml/customer_edit_renderer_attribute_group')
->setDisableAutoGroupChangeAttribute($customerForm->getAttribute($disableAutoGroupChangeAttributeName))
->setDisableAutoGroupChangeAttributeValue($customer->getData($disableAutoGroupChangeAttributeName)));
if ($customer->getId()) {
$form->getElement('website_id')->setDisabled('disabled');
$form->getElement('created_in')->setDisabled('disabled');
} else {
$fieldset->removeField('created_in');
$form->getElement('website_id')->addClass('validate-website-has-store');
$websites = array();
foreach (Mage::app()->getWebsites(true) as $website) {
$websites[$website->getId()] = !is_null($website->getDefaultStore());
}
$prefix = $form->getHtmlIdPrefix();
$form->getElement('website_id')->setAfterElementHtml(
'<script type="text/javascript">'
. "
var {$prefix}_websites = " . Mage::helper('core')->jsonEncode($websites) .";
Validation.add(
'validate-website-has-store',
'" . Mage::helper('customer')->__('Please select a website which contains store view') . "',
function(v, elem){
return {$prefix}_websites[elem.value] == true;
}
);
Element.observe('{$prefix}website_id', 'change', function(){
Validation.validate($('{$prefix}website_id'))
}.bind($('{$prefix}website_id')));
"
. '</script>'
);
}
$renderer = $this->getLayout()->createBlock('adminhtml/store_switcher_form_renderer_fieldset_element');
$form->getElement('website_id')->setRenderer($renderer);
// if (Mage::app()->isSingleStoreMode()) {
// $fieldset->removeField('website_id');
// $fieldset->addField('website_id', 'hidden', array(
// 'name' => 'website_id'
// ));
// $customer->setWebsiteId(Mage::app()->getStore(true)->getWebsiteId());
// }
$customerStoreId = null;
if ($customer->getId()) {
$customerStoreId = Mage::app()->getWebsite($customer->getWebsiteId())->getDefaultStore()->getId();
}
$prefixElement = $form->getElement('prefix');
if ($prefixElement) {
$prefixOptions = $this->helper('customer')->getNamePrefixOptions($customerStoreId);
if (!empty($prefixOptions)) {
$fieldset->removeField($prefixElement->getId());
$prefixField = $fieldset->addField($prefixElement->getId(),
'select',
$prefixElement->getData(),
$form->getElement('group_id')->getId()
);
$prefixField->setValues($prefixOptions);
if ($customer->getId()) {
$prefixField->addElementValues($customer->getPrefix());
}
}
}
$suffixElement = $form->getElement('suffix');
if ($suffixElement) {
$suffixOptions = $this->helper('customer')->getNameSuffixOptions($customerStoreId);
if (!empty($suffixOptions)) {
$fieldset->removeField($suffixElement->getId());
$suffixField = $fieldset->addField($suffixElement->getId(),
'select',
$suffixElement->getData(),
$form->getElement('lastname')->getId()
);
$suffixField->setValues($suffixOptions);
if ($customer->getId()) {
$suffixField->addElementValues($customer->getSuffix());
}
}
}
// my Custome code for country and state
$country = $fieldset->addField('country', 'select', array(
'name' => 'country',
'label' => Mage::helper('customer')->__('Country'),
'values' => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
'class' => 'required-entry',
'required' => true,
'onchange' => 'getstate(this)',
));
//Edit action pass your custom table to country id and get state
$storeId = $this->getRequest()->getParam('id');
if ($storeId != ''):
$editState = $stateCollection = Mage::getModel('directory/region')->load($storeId);
$stateCollection = Mage::getModel('directory/region')->getResourceCollection()->addCountryFilter($editState->getCountry())->load();
$state = "";
foreach ($stateCollection as $_state) {
$state[] = array('value' => $_state->getCode(), 'label' => $_state->getDefaultName());
}
$fieldset->addField('state', 'select', array(
'label' => Mage::helper('customer')->__('State'),
'required' => false,
'name' => 'state',
'selected' => 'selected',
'values' => $state,
));
else:
//New action
$fieldset->addField('state', 'select', array(
'name' => 'state',
'required' => false,
'label' => Mage::helper('customer')->__('State'),
'values' => '--Please Select Country--',
));
endif;
$url = Mage::getBaseUrl();
$country->setAfterElementHtml("<script type=\"text/javascript\">
function getstate(selectElement){
var reloadurl = '".$url.'admin/customer/state/' . "country/' + selectElement.value;
new Ajax.Request(reloadurl, {
method: 'POST',
onComplete: function(){
},
success: function (response) {
alert(response)
}
});
}
</script>");
/*
/* end my code country and state
*/
if ($customer->getId()) {
if (!$customer->isReadonly()) {
// Add password management fieldset
$newFieldset = $form->addFieldset(
'password_fieldset',
array('legend' => Mage::helper('customer')->__('Password Management'))
);
// New customer password
$field = $newFieldset->addField('new_password', 'text',
array(
'label' => Mage::helper('customer')->__('New Password'),
'name' => 'new_password',
'class' => 'validate-new-password'
)
);
$field->setRenderer($this->getLayout()->createBlock('adminhtml/customer_edit_renderer_newpass'));
// Prepare customer confirmation control (only for existing customers)
$confirmationKey = $customer->getConfirmation();
if ($confirmationKey || $customer->isConfirmationRequired()) {
$confirmationAttribute = $customer->getAttribute('confirmation');
if (!$confirmationKey) {
$confirmationKey = $customer->getRandomConfirmationKey();
}
$element = $fieldset->addField('confirmation', 'select', array(
'name' => 'confirmation',
'label' => Mage::helper('customer')->__($confirmationAttribute->getFrontendLabel()),
))->setEntityAttribute($confirmationAttribute)
->setValues(array('' => 'Confirmed', $confirmationKey => 'Not confirmed'));
// Prepare send welcome email checkbox if customer is not confirmed
// no need to add it, if website ID is empty
if ($customer->getConfirmation() && $customer->getWebsiteId()) {
$fieldset->addField('sendemail', 'checkbox', array(
'name' => 'sendemail',
'label' => Mage::helper('customer')->__('Send Welcome Email after Confirmation')
));
$customer->setData('sendemail', '1');
}
}
}
} else {
$newFieldset = $form->addFieldset(
'password_fieldset',
array('legend'=>Mage::helper('customer')->__('Password Management'))
);
$field = $newFieldset->addField('password', 'text',
array(
'label' => Mage::helper('customer')->__('Password'),
'class' => 'input-text required-entry validate-password',
'name' => 'password',
'required' => true
)
);
$field->setRenderer($this->getLayout()->createBlock('adminhtml/customer_edit_renderer_newpass'));
// Prepare send welcome email checkbox
$fieldset->addField('sendemail', 'checkbox', array(
'label' => Mage::helper('customer')->__('Send Welcome Email'),
'name' => 'sendemail',
'id' => 'sendemail',
));
$customer->setData('sendemail', '1');
if (!Mage::app()->isSingleStoreMode()) {
$fieldset->addField('sendemail_store_id', 'select', array(
'label' => $this->helper('customer')->__('Send From'),
'name' => 'sendemail_store_id',
'values' => Mage::getSingleton('adminhtml/system_store')->getStoreValuesForForm()
));
}
}
// Make sendemail and sendmail_store_id disabled if website_id has empty value
$isSingleMode = Mage::app()->isSingleStoreMode();
$sendEmailId = $isSingleMode ? 'sendemail' : 'sendemail_store_id';
$sendEmail = $form->getElement($sendEmailId);
$prefix = $form->getHtmlIdPrefix();
if ($sendEmail) {
$_disableStoreField = '';
if (!$isSingleMode) {
$_disableStoreField = "$('{$prefix}sendemail_store_id').disabled=(''==this.value || '0'==this.value);";
}
$sendEmail->setAfterElementHtml(
'<script type="text/javascript">'
. "
$('{$prefix}website_id').disableSendemail = function() {
$('{$prefix}sendemail').disabled = ('' == this.value || '0' == this.value);".
$_disableStoreField
."}.bind($('{$prefix}website_id'));
Event.observe('{$prefix}website_id', 'change', $('{$prefix}website_id').disableSendemail);
$('{$prefix}website_id').disableSendemail();
"
. '</script>'
);
}
if ($customer->isReadonly()) {
foreach ($customer->getAttributes() as $attribute) {
$element = $form->getElement($attribute->getAttributeCode());
if ($element) {
$element->setReadonly(true, true);
}
}
}
$form->setValues($customer->getData());
$this->setForm($form);
return $this;
}
/**
* Return predefined additional element types
*
* #return array
*/
protected function _getAdditionalElementTypes()
{
return array(
'file' => Mage::getConfig()->getBlockClassName('adminhtml/customer_form_element_file'),
'image' => Mage::getConfig()->getBlockClassName('adminhtml/customer_form_element_image'),
'boolean' => Mage::getConfig()->getBlockClassName('adminhtml/customer_form_element_boolean'),
);
}
}
////////////////////////////////////////////////////////////////////// Now i add stateAction() in
app/code/core/Mage/Adminhtml/controllers/CustomerController.php, just after saveAction() method finish
public function stateAction() {
$countrycode = $this->getRequest()->getParam('country');
$state = "<option value=''>Please Select</option>";
if ($countrycode != '') {
$statearray = Mage::getModel('directory/region')->getResourceCollection() ->addCountryFilter('US')->load();
foreach ($statearray as $_state) {
$state .= "<option value='" . $_state->getCode() . "'>" . $_state->getDefaultName() . "</option>";
}
}
echo $state;
}
// if (Mage::app()->isSingleStoreMode()) {
// $fieldset->removeField('website_id');
// $fieldset->addField('website_id', 'hidden', array(
// 'name' => 'website_id'
// ));
// $customer->setWebsiteId(Mage::app()->getStore(true)->getWebsiteId());
// }
// $fieldset->addField('country', 'select', array(
// 'name' => 'country',
// 'label' => 'Country',
// 'values' => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
// ));
//
// $fieldset->addField('state', 'select', array(
// 'name' => 'state',
// 'label' => 'State',
// 'values' => Mage::getModel('adminhtml/system_config_source_region')->getResourceCollection(),
// ));
$country = $fieldset->addField('country', 'select', array(
'name' => 'country',
'label' => Mage::helper('customer')->__('Country'),
'values' => Mage::getModel('adminhtml/system_config_source_country')->toOptionArray(),
'class' => 'required-entry',
'required' => true,
'onchange' => 'getstate(this)',
));
//Edit action pass your custom table to country id and get state
$storeId = $this->getRequest()->getParam('id');
if ($storeId != ''):
$editState = $stateCollection = Mage::getModel('directory/region')->load($storeId);
$stateCollection = Mage::getModel('directory/region')->getResourceCollection()->addCountryFilter($editState->getCountry())->load();
$state = "";
foreach ($stateCollection as $_state) {
$state[] = array('value' => $_state->getCode(), 'label' => $_state->getDefaultName());
}
$fieldset->addField('state', 'select', array(
'label' => Mage::helper('customer')->__('State'),
'required' => false,
'name' => 'state',
'selected' => 'selected',
'values' => $state,
));
else:
//New action
$fieldset->addField('state', 'select', array(
'name' => 'state',
'required' => false,
'label' => Mage::helper('customer')->__('State'),
'values' => '--Please Select Country--',
));
endif;
/*
* Add Ajax to the Country select box html output
*/
$country->setAfterElementHtml("<script type=\"text/javascript\">
function getstate(selectElement){
var reloadurl = '". $this->getUrl('adminhtml_customer/state') . "country/' + selectElement.value;
new Ajax.Request(reloadurl, {
method: 'get',
onComplete: function(transport){
var response = transport.responseText;
$('storelocatorstate').update(response);
}
});
}
</script>");