I am trying to update two field, but the update isn't working for some reason.
This is the method:
public function actionChangepassword()
{
$model = $this->findModel(Yii::$app->user->identity->id);
$model->scenario = 'changepassword';
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())):
Yii::$app->response->format = Response::FORMAT_JSON;
if(ActiveForm::validate($model))
return ActiveForm::validate($model);
$model->salt = Yii::$app->security->generateRandomString(32);
$model->password = Yii::$app->security->generatePasswordHash($model->salt . $model->password_new);
$model->update();
return 'true';
endif;
return $this->renderAjax('changePassword',
[ 'model' => $model]
);
}
and JS function:
$('body').on('beforeSubmit', '#changePassword', function(event, jqXHR, settings) {
var form = $(this);
if(form.find('.has-error').length) {
return false;
}
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function(data) {
// do something ...
}
});
return false;
});
I am getting true as result, which means that the function it self is working, but the password and salt are not updated (I tried with $model->save(), but the result is the same). What am I doing wrong?
It can be because of this two lines:
if(ActiveForm::validate($model))
return ActiveForm::validate($model);
Here you are checking if model data is valid, and when it is valid you just return true, maybe you mean
//the ! sign is missed
if( ! ActiveForm::validate($model))
and return when model data is invalid. Also look at return 'true'; where you return string 'true' instead of boolean true
First, if you want to use ajax request with JSON you need to add option
$.ajax({
...
dataType: 'json',
...
});
Second, we still want JSON data
return ActiveForm::validate($model); // returns boolean
return 'true'; // returns string
You need JSON,
return \yii\helpers\Json::encode([
'success' => true // or something
]);
Third, I think you mean
if(!ActiveForm::validate($model))
return false;
Related
I have made a function of changing the Avatar. This works, but when I try to return a response in ajax, json content is displayed in my browser and do not get anything in ajax
My ajax
$('changeBlogLogoForm').submit(function (e) {
e.preventDefault();
var form = this;
$.ajax({
url: $(form).attr('action'),
method: $(form).attr('method'),
data: new FormData(form),
processData: false,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log(data);
}
// toastr.remove();
// console.log('+');
// if (data.status === 1) {
// toastr.success(data.msg);
// $(form)[0].reset();
// } else {
// toastr.error(data.msg);
// }
// }
});
My function in controller
public function changeBlogLogo(Request $request)
{
$settings = Setting::find(1);
$logo_path = 'back/dist/img/logo-favicon';
$old_logo = $settings->getAttributes()['blog_logo'];
$file = $request->file('blog_logo');
$filename = time() . '_' . rand(1, 100000) . '_sdblog_logo_png';
if ($request->hasFile('blog_logo')) {
if ($old_logo != null && File::exists(public_path($logo_path . $old_logo))) {
File::delete(public_path($logo_path . $old_logo));
}
$upload = $file->move(public_path($logo_path), $filename);
if ($upload) {
$settings->update([
'blog_logo' => $filename
]);
return response()->json(['status' => 1, 'msg' => 'Success']);
} else {
return response()->json(['status' => 0, 'msg' => 'Error']);
}
} else {
dd('No file');
}
}
I tried to display the data in the console, but nothing is displayed
try this one
let value = e.target.files[0]
let formData = new FormData();
formData.append('blog_logo', value)
and don't forget to add multipart form data in your jquery ajax
contentType: 'multipart/form-data',
hope this work
I want to store Auth::user()->id on the default column user_id in the SQL query shown below.
I tried to set put like this but does not send any data to the database.
public function saveLoadingsData() {
//Validate for a valid Post Request
if (isset($_POST['orderNumber']) && isset($_POST['Truck']) && isset($_POST['receiptNumber']) && isset($_POST['items'])) {
// {"orderNumber":"CRS1104200001","agentId":"3","items":[{"itemId":"4","itemName":"Embe","quantity":"13"}]}
$orderNumber = $_POST['orderNumber'];
$items = $_POST['items'];
$receiptNumber = $_POST['receiptNumber'];
$Truck = $_POST['Truck'];
$driverName = $_POST['driverName'];
foreach ($items as $singleItem) {
$data = array('order_no' => $orderNumber,'user_id'=>Auth::user()->id,"receiptNumber" => $receiptNumber, "Truck" => $Truck, "driverName" => $driverName, "pid" => $singleItem['itemId'], "qty" => $singleItem['quantity']);
// print_r($data);
DB::table('loadings')->insert($data);
// return redirect()->back();
}
// return redirect()->back();
echo "Success";
}
My ajax function
$("#btnSaveOrder").on('click', function(e){
var orderNumber=$("#order_no").val();
var receiptNumber=$("#receiptNumber").val();
var Truck=$("#Truck").val();
var driverName=$("#driverName").val();
var jsonData=convertTableToJson();
$.ajax('/api/loading/saveLoadingsData', {
type: 'POST',
data: {
orderNumber:orderNumber,
receiptNumber:receiptNumber,
Truck:Truck,
driverName:driverName,
items:jsonData
},
success: function (data, status, xhr) {
alert("Data Saved");
document.location.reload(true);
},
error: function (jqXhr, textStatus, errorMessage) {
console.log(errorMessage);
}
});
});
var convertTableToJson = function(){
var rows = [];
$('table#tableSelectedItems tr').each(function(i, n){
if (i!=0) {
var $row = $(n);
rows.push({
itemId: $row.find('td:eq(0)').text(),
itemName: $row.find('td:eq(1)').text(),
quantity: $row.find('td:eq(2)').text(),
});
}
});
return rows;
};
My api route
Route::post('loading/saveLoadingsData', 'LoadingController#saveLoadingsData');
Can someone help me?
I recommend you the following
Pass the $request object in your method and log all object, maybe are missing data and for that reason it does not meet the condition:
saveLoadingsData(Request $request){
Log::info(json_encode($request->all()));`
}
Then check your logs files to see the result in /storage/logs/laravel.log
Testing the bloc pattern is not so clear to me. So, if I have these 2 stream controllers:
final _controller1 = StreamController();
final _controller2 = StreamController<bool>;
Sink get controller1Add = _controller1.sink;
Stream<bool> get controller2Out = _controller2.stream;
and I want to test that, from this function:
submit() {
if (_controller1.value == null ||
_controller1.value.isEmpty) {
print(...)
return;
}else
_controller2.sink.add(true);
}
the _controller2.stream should have true, how should I do?
I tried something like:
test("test", (){
bloc.submit();
expect(bloc.controller2Out, emitsAnyOf([true]));
});
but, of course, it didnĀ“t work.
I've modified your code to use the RxDart's BehaviorSubject and it seems to work. You are using StreamController but I get error cause it doesn't have the value property.
final _controller1 = BehaviorSubject<String>();
final _controller2 = BehaviorSubject<bool>();
Sink get controller1Add => _controller1.sink;
Stream<bool> get controller2Out => _controller2.stream;
submit() {
if (_controller1.value == null || _controller1.value.isEmpty) {
print('Error');
_controller2.sink.add(false);
return;
} else {
print('OK');
_controller2.sink.add(true);
}
}
The test:
bloc.controller1Add.add('');
bloc.submit();
expect(bloc.controller2Out, emits(false));
bloc.controller1Add.add('test');
bloc.submit();
expect(bloc.controller2Out, emits(true));
bloc.controller1Add.add('');
bloc.submit();
expect(bloc.controller2Out, emits(false));
I'm having a hard time trying to stop the loop in promise.all if one promise rejects it. Here's how I did it. Is there something wrong with this?
Promise.all(myArray.map((obj) => {
this.someFunction(obj);
}))
Here's the function I call..
someFunction(){
return new Promise(function (resolve, reject) {
....
reject()
})}
I have updated my code, it is tested and it works on my machine with the mock data I feed it with. I am not exactly sure how the rest of your code is structured but it is something likes this: Oh and you cannot break out of a map, but we will use a simple for loop because we can break out of that:
function someFunction(){
return new Promise(function (resolve, reject) {
// I will be rejeccting a boolean
// If you are resolving something, resolve it as true
reject(false)
})}
async function shouldStopLoop(){
// the boolean will come here
// if it is false, the catch block will return
// if it is true, the try block will return
let stopLoop = null;
let result = null;
try {
result = await someFunction();
return result
} catch(error) {
stopLoop = error;
return stopLoop;
}
}
function mayReturnPromiseAll() {
let myArray = ['stuf to loop over...']
let arraytoGoInPrimiseAll = [];
// Array.prototype.map cannot be stopped
// Thats why we will use a for loop and we will push the data we need
// into another array
for (var i = 0; i < myArray.length; i++) {
if (!this.someFunction(obj)) {
break;
} else {
// push things in arraytoGoInPrimiseAll
}
}
if(arraytoGoInPrimiseAll.length > 0){
return Promise.all(arraytoGoInPrimiseAll)
} else {
// do something else
}
};
Try this:
const arrayOfFunctions = myArray.map(obj => this.someFunction(obj))
Promise.all(arrayOfFunctions).then(values => {
console.log(values);
}).catch(error => {
console.log(error)
});
I'am using dojo.data.ItemFileReadStore to query a json file with data. the main purpose is finding translations at Js level.
The Json data has "id" the word and "t" the translation
function translate(word)
{
var json = '/my/language/path/es.json';
var reader = new dojo.data.ItemFileReadStore({
url: json
});
var queryObj = {};
queryObj["id"] = word;
reader.fetch({
query: queryObj,
onComplete: function(items, request){
if (items.length > 0) {
var t = reader.getValue(items[0], 't');
if (dojo.isString(t)) {
return t;
}
}
return word;
},
onError: function(error, request){
return word;
}
});
}
The return value is always a undefined wether there is a translation or not. any ideas?
I tried typecasting with no success.
You can do it like this:
function translate(wordId) {
var translatedWord= wordId;
var store = new dojo.data.ItemFileReadStore({ data: storeData });
store.fetch({ query: { id: wordId },
onItem: function (item) {
translatedWord= (store.getValue(item, 't'));
}
});
return translatedWord;
}