Is there any way to do basically this:
this.success = true;
setTimeout(() => {
this.success = false;
}, 1000);
Using RXJS?
const success$ = timer(1000).pipe(map(_ => false), startWith(true));
success$.subscribe(x => console.log(x));
https://stackblitz.com/edit/rxjs-tpeyqk
Sure. use the timer() function:
this.success = true;
timer(1000).subscribe(() => this.success = false);
Related
I am working with laravel and ajax. But when I register I see this error 302.
I know this may be a trivial question but I am just not able to get this ajax call to work.
Auth/RegisterController.php
protected function create(array $data, Request $request)
{
if ($request->hasFile('image')) {
$fileNameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extention;
$path = $request->file('image')->storeAs('public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
return User::create([
'firstname' => $data['firstـname'],
'lastname' => $data['lastـname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'mobile' => $data['mobile'],
'nasional_code' => $data['national_code'],
'birthdate' => $data['birthـdate'],
'document' => $data['document'],
'educational' => $data['educational'],
'gender' => $data['gender'],
'side' => $data['side'],
$fileNameToStore => $data['image']
]);
}
My ajax is register.js file
How do I pass the "Accept'=>'application/json" in request when testing:
I want to add 'accept'=>'application/json' to my request header.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function scroll_to_class(element_class, removed_height) {
var scroll_to = $(element_class).offset().top - removed_height;
if($(window).scrollTop() != scroll_to) {
$('html, body').stop().animate({scrollTop: scroll_to}, 0);
}
}
function bar_progress(progress_line_object, direction) {
var number_of_steps = progress_line_object.data('number-of-steps');
var now_value = progress_line_object.data('now-value');
var new_value = 0;
if(direction == 'right') {
new_value = now_value + ( 100 / number_of_steps );
}
else if(direction == 'left') {
new_value = now_value - ( 100 / number_of_steps );
}
progress_line_object.attr('style', 'width: ' + new_value + '%;').data('now-value', new_value);
}
jQuery(document).ready(function() {
$('form fieldset:first').fadeIn('slow');
$('form input[type="text"], form input[type="password"], form textarea').on('focus', function() {
$(this).removeClass('input-error');
});
$('form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
parent_fieldset.find('input[type="text"], input[type="password"], input[type="email"], input[type="radio"]').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
parent_fieldset.find('input[type="checkbox"]').each(function() {
if( $(this).prop("checked") == false ) {
$('.form-check-label').css("color","red");
next_step = false;
}
else {
$('.form-check-label').css("color","black");
}
});
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
current_active_step.removeClass('active').addClass('activated').next().addClass('active');
bar_progress(progress_line, 'right');
$(this).next().fadeIn();
scroll_to_class( $('form'), 20 );
});
}
});
// previous step
$('form .btn-previous').on('click', function() {
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
$(this).parents('fieldset').fadeOut(400, function() {
current_active_step.removeClass('active').prev().removeClass('activated').addClass('active');
bar_progress(progress_line, 'left');
$(this).prev().fadeIn();
scroll_to_class( $('form'), 20 );
});
});
$('form').on('submit', function(e) {
$(this).find('input[type="text"], input[type="password"], input[type="username"], input[type="email"], input[type="tel"], input[type="url"], textarea').each(function() {
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});
Update your ajax header, according to this:
$.ajaxSetup({
headers: {
accepts: "application/json; charset=utf-8",
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
The possibilities of this issue is CSRF token and missing route.
I am working with laravel and ajax. But when I register I see this error 302.
I know this may be a trivial question but I am just not able to get this ajax call to work.
Auth/RegisterController.php
protected function create(array $data, Request $request)
{
if ($request->hasFile('image')) {
$fileNameWithExt = $request->file('image')->getClientOriginalName();
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
$extention = $request->file('image')->getClientOriginalExtension();
$fileNameToStore = $filename.'_'.time().'.'.$extention;
$path = $request->file('image')->storeAs('public/images', $fileNameToStore);
} else {
$fileNameToStore = 'noimage.jpg';
}
return User::create([
'firstname' => $data['firstـname'],
'lastname' => $data['lastـname'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
'mobile' => $data['mobile'],
'nasional_code' => $data['national_code'],
'birthdate' => $data['birthـdate'],
'document' => $data['document'],
'educational' => $data['educational'],
'gender' => $data['gender'],
'side' => $data['side'],
$fileNameToStore => $data['image']
]);
}
My ajax is register.js file
How do I pass the "Accept'=>'application/json" in request when testing:
I want to add 'accept'=>'application/json' to my request header.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function scroll_to_class(element_class, removed_height) {
var scroll_to = $(element_class).offset().top - removed_height;
if($(window).scrollTop() != scroll_to) {
$('html, body').stop().animate({scrollTop: scroll_to}, 0);
}
}
function bar_progress(progress_line_object, direction) {
var number_of_steps = progress_line_object.data('number-of-steps');
var now_value = progress_line_object.data('now-value');
var new_value = 0;
if(direction == 'right') {
new_value = now_value + ( 100 / number_of_steps );
}
else if(direction == 'left') {
new_value = now_value - ( 100 / number_of_steps );
}
progress_line_object.attr('style', 'width: ' + new_value + '%;').data('now-value', new_value);
}
jQuery(document).ready(function() {
$('form fieldset:first').fadeIn('slow');
$('form input[type="text"], form input[type="password"], form textarea').on('focus', function() {
$(this).removeClass('input-error');
});
$('form .btn-next').on('click', function() {
var parent_fieldset = $(this).parents('fieldset');
var next_step = true;
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
parent_fieldset.find('input[type="text"], input[type="password"], input[type="email"], input[type="radio"]').each(function() {
if( $(this).val() == "" ) {
$(this).addClass('input-error');
next_step = false;
}
else {
$(this).removeClass('input-error');
}
});
parent_fieldset.find('input[type="checkbox"]').each(function() {
if( $(this).prop("checked") == false ) {
$('.form-check-label').css("color","red");
next_step = false;
}
else {
$('.form-check-label').css("color","black");
}
});
if( next_step ) {
parent_fieldset.fadeOut(400, function() {
current_active_step.removeClass('active').addClass('activated').next().addClass('active');
bar_progress(progress_line, 'right');
$(this).next().fadeIn();
scroll_to_class( $('form'), 20 );
});
}
});
// previous step
$('form .btn-previous').on('click', function() {
var current_active_step = $(this).parents('form').find('.form-wizard.active');
var progress_line = $(this).parents('form').find('.progress-line');
$(this).parents('fieldset').fadeOut(400, function() {
current_active_step.removeClass('active').prev().removeClass('activated').addClass('active');
bar_progress(progress_line, 'left');
$(this).prev().fadeIn();
scroll_to_class( $('form'), 20 );
});
});
$('form').on('submit', function(e) {
$(this).find('input[type="text"], input[type="password"], input[type="username"], input[type="email"], input[type="tel"], input[type="url"], textarea').each(function() {
if( $(this).val() == "" ) {
e.preventDefault();
$(this).addClass('input-error');
}
else {
$(this).removeClass('input-error');
}
});
});
});
I want to debounce on all key presses excluding return. I have tried the following but it doesn't debounce.
some_stream.flatMap((event) => {
if(event.keyCode == 13){
return Kefir.stream(emitter => {
emitter.emit(event.target.value);
});
}else{
const debounced_stream = Kefir.stream(emitter => {
emitter.emit(event.target.value);
}).debounce(1000)
return debounced_stream;
}
})
I was able to solve this with the code block below which debounces on every keyCode except 13:
const search_stream = Kefir.fromEvents(self.search_keyword._tag.input, 'keyup');
const debounced_search_stream = search_stream
.filter((event) => {
return event.keyCode != 13;
})
.map((event) => {
return event.target.value;
})
.debounce(1000);
const not_debounced_search_stream = search_stream
.filter((event) => {
return event.keyCode == 13;
})
.map((event) => {
return event.target.value;
})
Kefir.merge([debounced_search_stream, not_debounced_search_stream]).onValue(keyword => {
if(keyword !== null){
if (keyword) {
//do something
}
}
})
i have the following code on my controller:
/**
*
* #Route("/{discountLevelItemId}/manage-product/update", name="discountlevel_manage_product_update", defaults={"_format"="json"} )
* #Method("POST")
*/
public function manageProductUpdateAction($discountLevelItemId, Request $request)
{
$em = $this->getDoctrine()->getEntityManager();
$entity = $em->getRepository('CIInventoryBundle:DiscountLevelItem')->find($discountLevelItemId);
$form = $this->createForm(new DiscountLevelItemCollectionType(), $entity);
$form->bindRequest($request);
if ($form->isValid()) {
//remove items without discount type
foreach ($entity->getDiscountLevelItemProducts() as $item) {
if (!$item->getDiscountType()) {
$entity->getDiscountLevelItemProducts()->removeElement($item);
$em->remove($item);
}
}
$em->persist($entity);
$em->flush();
$responseData = array(
'status' => 'success',
'message' => 'Supplier product discounts successfully saved.'
);
} else {
$responseData = array(
'status' => 'error',
'form' => $this->renderView('CIInventoryBundle:DiscountLevel:manageProducts.html.twig', array(
'entity' => $entity,
'form' => $form->createView()
))
);
}
return new Response(json_encode($responseData), 200, array('Content-Type'=>'application/json'));
}
This action is called via ajax. Before calling this controller i filtered some data out like so:
initForm: function() {
//submit form function
var options = {
delegation: true,
dataType: "json",
beforeSubmit: function(arr, $form, options) {
//holds objects every four looping
var tempArray = new Array();
//holds changed objects that will only be submitted in the server.
var changedArray = new Array();
var found = false;
var idx = 1;
//get the token then remove from arr.
changedArray.push(arr.splice(arr.length-1,1)[0]);
for (var j = arr.length-1; j >= 0; j--) {
var obj = arr[j];
if ( viewCtrl.dliProductsChanged.indexOf(obj.value) != -1 ) {
found = true;
}
tempArray.push(arr[j]);
if(idx % 4 == 0) {
if (found == true) {
for(var i = 0; i < tempArray.length; i++){
changedArray.push(tempArray[i]);
}
found = false;
}
tempArray.length = 0;
}
idx++;
}
arr.length = 0;
for(var i = 0; i < changedArray.length; i++){
arr.push(changedArray[i]);
}
viewCtrl.dliProductsChanged.length = 0;
$form.find( ".submit-button" ).button( "loading" );
$form.find( ".discount-value, .trucking" ).addClass( "uneditable-input" );
$form.find( ".discount-type" ).attr( "readonly", true );
},
success: function(responseText, statusText, xhr, $form) {
if ( responseText.status == "success" ) {
viewCtrl.modal.modal( "hide" );
$.growl.notice({ title: "<strong>Saved</strong>", message: responseText.message, size: "large", duration: 5000, location: "br" });
viewCtrl.dliProductsChanged.length = 0;
} else {
viewCtrl.modal.find( ".modal-content" ).html( responseText.form );
}
$form.find( ".submit-button" ).button( "reset" );
}
};
$( "#manage-products-form" ).ajaxForm( options );
},
My question is, how can i repopulate the form with data i filtered out when the form gets invalid? The first thing came out of my mind is modifying the request object and then rebinding it again but i dont know how to implement that...
Any insights?
PS: I user JQUERY Form Plugin on form submission.
Thanks!
I'm going to test next controller:
public ActionResult Approve(UpdateBalanceCommand input)
{
return TryPush(input, setting => setting.SuccessResult = () => Redirect(Url.Action("Index", "Home").SetHash(Url.Action("Index", "Payment"))));
}
How can I test the fact that the command had been executed with necessary settings?
Sincerelly,
Anton.
Please use like this
Establish establish = () =>
{
command = Pleasure.Generator.Invent<UpdateBalanceCommand >();
mockController = MockController<SomeController>
.When();
};
Because of = () => { result = mockController.Original.Approve(command); };
It should_be_push = () => mockController.ShouldBePush(command);
It should_be_result = () => result.ShouldBeRedirect("your url");
See working solution below
Establish establish = () =>
{
_command = Pleasure.Generator.Invent<UpdateBalanceCommand>();
_paymentController = MockController<PaymentController>.When()
.StubUrlAction("/")
.StubUrlAction("/Payment");
};
Because of = () => _result = _paymentController.Original.Approve(_command);
It should_push_command = () => _paymentController.ShouldBePush(_command);
It should_be_redirect = () => _result.ShouldBeRedirect("/#!Payment?");