Yii2 - warning message before submit - php

I have a form with two fields "a" and "b" when in action update if the "b" field changes the "beforeSubmit" event a Modal Bootstrap alert is sent to the user without any button OK or CANCEL, only information during 5 seconds, after this time automatically save if the the "b" field were actually changed, if not change save whitout alert modal windows.
How do I send this condition from the controller to view where I have the javascript?
maybe with ajax? but how?
Controller.php
public function actionUpdate()
{
$model = new Faqs();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
if ($model->oldAttributes["b"] != $model->b){
sleep(5);
}
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
_form.php
$('#form').on('beforeSubmit', function(e) {
if(old_B_attribute != current_B_attribute){ //example
$('#modal').modal('show');
}
});

You want to prompt the user if the attribute values were actually changed before submitting the form.
How I would go for this
Create a separate action in my controller actionAttributeDirty() which would validate if the selected attribute was actually changed.
Then, use a normal Html::button() rather than a Html::submitButton() for the form.
Add a hidden field to hold the current records id in the form.
Bind click event to the button which will send an ajax call to actionAttributeDirty() with the id of the current record.
Then use the success function to display the modal window and use setTimeout with $.yiiActiveForm('submitForm') to trigger the form submission after 5 seconds.
So in the similar order given above,
actionAttributeDirty
public function actionAttributeDirty()
{
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$id = Yii::$app->request->post('id');
$model = Faqs::findOne($id);
$response = ['changed' => false];
$isValidRequest = Yii::$app->request->isAjax && Yii::$app->request->isPost;
if ($isValidRequest && $model->load(Yii::$app->request->post())) {
//get the name of the fields from the dirty attributes
$changedAttributes = array_keys($model->getDirtyAttributes());
//if the attribute name exists in the dirty attributes
if (!empty($changedAttributes) && in_array("b", $changedAttributes)) {
$response['changed'] = true;
}
}
return $response;
}
Your form should have the following buttons along with other fields,
$form = \yii\widgets\ActiveForm::begin(['id' => 'form']);
echo \yii\helpers\Html::hiddenInput('id', $model->id);
echo \yii\helper\Html::button('save', ['id' => 'save-now']);
\yii\widgets\ActiveForm::end();
click Event for the Button
Add the following on the top of your view where you have the form.
Note: change the url of the ajax call '/site/attribute-dirty' accordingly where you copy the actionAttributeDirty() i assume you copy it inside the site controller.
$js = <<< JS
$('#save-now').on('click', function(e) {
e.preventDefault();
let form = $("#form");
$.ajax({
url:'/site/attribute-dirty',
method:'post',
data:form.serialize(),
}).done(function(response){
if(response.changed){
$('#modal').modal('show');
setTimeout(function(){form.yiiActiveForm('submitForm');}
, 5000);
}else{
form.yiiActiveForm('submitForm');
}
}).fail(function(response){
console.log(response.responseText);
});
});
JS;
$this->registerJs($js, \yii\web\View::POS_READY);
EDIT
Pressing Enter button will not submit the form anyhow as there is no submit button, If you want Enter button to submit the form you should add the following along with the script too on the top of the view which will trigger the click event of the save-now button whenever the Enter button is pressed within any input.
$("#form").on('keypress','input',function(e){
e.preventDefault();
if(e.keyCode===13){
$("#save-now").trigger('click');
}
});

your request can not be done on the client side by beforeSubmit.Because you have to decide on the server side.
On the client side you can use
$(document).on("beforeValidate", "form", function(event, messages, deferreds) {
// #code
// console.log('BEFORE VALIDATE TEST');
}).on("afterValidate", "form", function(event, messages, errorAttributes) {
// console.log('AFTER VALIDATE TEST');
//#code
});
Then decide in the rules method.
On the server side, you can also decide on the following events:(For what you want)
 beforeValidate, afterValidate,beforeSave,afterSave,...

if you want show confirmation modal i use as below. you can change as your needs show or hide submit after x seconds
$(function() {
submitting = false;
});
$("form").on("beforeSubmit", function (event, messages, errorAttributes) {
if (typeof(errorAttributes) === "undefined" || errorAttributes.length === 0) {
$('#modal-confirm').modal('show');
return submitting;
}
});
var submit = function() {
submitting = true;
$("form").yiiActiveForm('submitForm');
}
in modal submit
<button type="button" onclick="submit();">Confirm</button>

Related

Using AJAX to send to form data to PHP script and bring up success notification without refreshing the page

Just to preface, I am very new to coding.
I'm working on a contact form for a website and I want, when the user submits the form, the data to be sent to my PHP script that sends an email, and then a notification bar to appear confirming the submission.
As of right now, when I press submit, the form does nothing.
The bar is created already and is contained in a seperate function
The form works if I let the page refresh normally
I've tested it on and off the server already
function successHeader() {
//jQuery for the confirmation box
$(".submittedBox").css("display", "block"); //Displays Pop-Up
$(".form_header").css("display", "none"); //Removes Contact Us
}
function formSubmit() {
$(".contact_form").submit(function(event) { //Submit Handler
var $form = $(this), //Get the action attribute
url = $form.attr('action');
var post = $.post(url, $form.serialize());
post.done(function() { //When the function is successfully submitted
successHeader();
});
});
}
This is where the function is called (the error handling works)
//If the form has no errors
if (error == 0) {
formSubmit();
}
The PHP script is named: form_processing.php
Expected: Form submits, and pop-up appears
Actual: Nothing

Hooking After Validation but Before Order Create in Woocommerce Checkout

I am trying to create a step in checkout to confirm your order. I'm thinking when the place order button is clicked AND the checkout fields are valid I could run some JS to show a modal or whatever.
Is there a JS trigger/event similar to checkout_place_order that runs after validation? For example, I can use the following but it happens before validation. Maybe there is a way to trigger validation from inside there and display my modal based off that?
var checkout_form = $('form.checkout');
checkout_form.on('checkout_place_order', function () {
// do your custom stuff
return true; // continue to validation and place order
return false; // doesn't validate or place order
});
There is also the woocommerce_after_checkout_validation hook but I am not sure how to utilize it to achieve what I'm after.
I am open to ideas...
I was able to figure this out finally, Its more of a workaround since I don't think there is a clear way to do this.
As soon as the "Place Order" button is clicked, we use the checkout_place_order event to place a hidden field with a value set to 1.
var checkout_form = $('form.checkout');
checkout_form.on('checkout_place_order', function () {
if ($('#confirm-order-flag').length == 0) {
checkout_form.append('<input type="hidden" id="confirm-order-flag" name="confirm-order-flag" value="1">');
}
return true;
});
Next, we use the hook woocommerce_after_checkout_validation to check our hidden input and if the value is 1 add in error (This stops the order from going through).
function add_fake_error($posted) {
if ($_POST['confirm-order-flag'] == "1") {
wc_add_notice( __( "custom_notice", 'fake_error' ), 'error');
}
}
add_action('woocommerce_after_checkout_validation', 'add_fake_error');
Last, we use the checkout_error event to determine if there was a real validation or if if there is only 1 error, the error we added. If there is only 1 error it means validation passed so we can show our modal (or whatever you need to do).
$(document.body).on('checkout_error', function () {
var error_count = $('.woocommerce-error li').length;
if (error_count == 1) { // Validation Passed (Just the Fake Error I Created Exists)
// Show Confirmation Modal or Whatever
}else{ // Validation Failed (Real Errors Exists, Remove the Fake One)
$('.woocommerce-error li').each(function(){
var error_text = $(this).text();
if (error_text == 'custom_notice'){
$(this).css('display', 'none');
}
});
}
});
Inside my modal I have a confirm button that sets our hidden field value to nothing and clicks the place order button again. This time the order will go through because we are checking for the hidden input value of 1.
$('#confirm-order-button').click(function () {
$('#confirm-order-flag').val('');
$('#place_order').trigger('click');
});
As far as I know, there is no hooks in between validation and order creation process, that will allow you to interact with customer, making some actions.
Using jQuery and Sweet Alert component (SWAL 2), here is an example of code that will disable the "Place Order" button displaying a Sweet Alert with confirmation buttons. It's not perfect, but it answers partially your question.
Once customer will confirm, the "Place Order" button will be enabled back and it will be triggered by the code… If the customer use the cancel button, Checkout review order will be refreshed (Ajax).
The code:
add_action( 'wp_footer', 'checkout_place_order_script' );
function checkout_place_order_script() {
// Only checkout page
if( is_checkout() && ! is_wc_endpoint_url() ):
// jQuery code start below
?>
<script src="https://unpkg.com/sweetalert2#8.8.1/dist/sweetalert2.all.min.js"></script>
<script src="https://unpkg.com/promise-polyfill#8.1.0/dist/polyfill.min.js"></script>
jQuery( function($){
var fc = 'form.checkout',
pl = 'button[type="submit"][name="woocommerce_checkout_place_order"]';
$(fc).on( 'click', pl, function(e){
e.preventDefault(); // Disable "Place Order" button
// Sweet alert 2
swal({
title: 'Are you sure?',
text: "You are about proceed the order",
type: 'success',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: "Yes let's go!"
}).then((result) => {
if (result.value) {
$(fc).off(); // Enable back "Place Order button
$(pl).trigger('click'); // Trigger submit
} else {
$('body').trigger('update_checkout'); // Refresh "Checkout review"
}
});
});
});
</script>
<?php
endif;
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.
I'm late to the party, but wanted to share a variation of the answers above
jQuery(document).ready(function($){
/* on submit */
$('form#FORMID').submit( function(e) {
/* stop submit */
e.preventDefault();
/* count validation errors */
var error_count = $('.woocommerce-error li').length;
/* see if terms and conditions are accepted */
var terms = $('input#terms').is(':checked');
/* if there are no validation errors and terms are accepted*/
if( error_count == 0 && terms ) {
/* trigger confirmation dialogue */
if( confirm('Are you sure?') ){
/* resume default submit */
$(this).unbind('submit').submit();
} else {
/* do nothing */
e.stopPropagation();
}
}
});
});
I got a fast and simple JS decision for myself in this case (there were woocommerce and stripe forms). That is based on preventing the checkout button from submit but still makes forms verifications.
// making the wrap click event on dinamic element
$('body').on('click', 'button#place_order_wrap', function(event) {
// main interval where all things will be
var validatoins = setInterval(function(){ happen
// checking for errors
if(no_errors==0){
// making the setTimeout() function with limited time like 200ms
// to limit checkout function for just make verification
setTimeout(function(){
// triggering original button
$('button#place_order').click();
// if there some errors, stop the interval, return false
if(($('element').find('ul.woocommerce_error').length!==0)||($('element').find('.woocommerce-invalid-required-field').length!==0)){
clearInterval(validatoins);
return false;
}else{
no_errors=1;
}
}, 200);
}
if(no_errors==1){
// same error checking
if($('#step5').find('ul.woocommerce_error').length!=0||($('#step5').find('.woocommerce-invalid-required-field').length!==0)){
// if there some errors, stop the interval, return false
clearInterval(validatoins);
return false;
}
setTimeout(function(){
// if no errors
if(($('#step5').find('ul.woocommerce_error').length==0)&&($('#step5').find('.woocommerce-invalid-required-field').length==0)){
// do something, mark that finished
return false;
}
}, 1000);
// if something finished
if() {
setTimeout(function(){
// trigger original checkout click
$('button#place_order').click();
clearInterval(validatoins);
}, 1000);
}
}
}, 1000);
}

Trying to make an AJAX edit in place in Codeigniter .. failing

I'm on my first CI project and I'm trying to do basically an AJAX "edit in place".
I have a user profile page with a number of fields. Basically the user is looking at his own data, and I would like to give him the option to edit his info on a field by field basis. I have about 20 fields like so..
<div id="desc_short">
<div class="old_info"><p><?php echo $the_user->desc_short; ?></p></div>
<div class="edit_buttons">
<button type="button" class="btn_edit">Edit Field</button>
<button type="button" class="btn_submit">Submit Change</button>
<button type="button" class="btn_cancel">Cancel</button>
</div>
The submit and cancel buttons start off with display:none. A click on the 'edit' button appends a form to the div with some hidden field info and "shows it in" along with 'submit' and 'cancel' buttons. SO now the user has a text field under the original info, and two new buttons.
$('.btn_edit').on('click', function(){
var this_field_id = $(this).parent().parent().attr('id');
var form_HTML = "<form action='edit_profile' method='post'><input type='text' class='new_info' name='new_info'/><input type='hidden' class='edit_field' name='edit_field' value='"+this_field_id+"'/></form>";
$("#"+this_field_id).append(form_HTML).hide().show(500);
$(this).siblings().fadeIn(1000);
});
So I am dynamically adding the form to the appropriate div, and giving it a hidden field with the name of the datafield that is being edited. I'm also showing the "submit" and "cancel" buttons (although notice that the submit button is not in the form element).
I'll leave out the "cancel button" function, but here is the submit button jquery. As you can see I am trying to submit the form by "remote control", triggering a submit event on the form long distance from the submit button. And then on the submit event, I preventDefault and then try to $.post the info to an AJAX controller..
$('.btn_submit').on('click', function(){
var this_field_id = $(this).parent().parent().attr('id');
var new_info = $("#"+this_field_id+" .new_info").val();
alert(this_button);
$("#"+this_field_id+" form").trigger('submit');
$("#"+this_field_id+" form").submit(function(e){
e.preventDefault();
alert(this_field_id); // alerting correctly
$.post('../ajax/profileEdit', { edit_field: this_field_id , new_info: new_info },
function(data){
if(data = 'true')
{
alert(data); // <<<< alerts "true"
}
else
{
alert("bad");
}
}
);
});
});
Here is the ajax controller
public function profileEdit()
{
$ID = $this->the_user->ID;
$field = $this->input->post('edit_field');
$new_info = $this->input->post('new_info');
$this->load->model('Member_model');
$result = $this->Member_model->edit_profile( $ID, $field, $new_info );
echo $result;
}
And the model..
public function edit_profile($ID, $field, $new_info)
{
$statement = "UPDATE users SET $field=$new_info WHERE UID=$ID"
$query = $this->db->query($statement);
return $query;
}
I am actually getting back "TRUE" back to Jquery to alert out .. but nothing is being edited. No change to the information. Frankly, I am surprised I'm even getting 'true' back (the whole remote submit thing .. I thought "no way this works").. but that makes it tough to see what is going wrong.
Ideas?
Apart from the if(data = 'true) error, i don't see where the other error could be.
When you alert data, what does it show you?
Try this in the model;
public function edit_profile($ID, $field, $new_info)
{
$data = array('field_table' => $field, 'new_info_table' => $new_info);
return ($this->db->where('UID',$ID)->update('tabel_name',$data)) ? TRUE : FALSE;
}
AND in
public function profileEdit()
{
$ID = $this->the_user->ID;
$field = $this->input->post('edit_field');
$new_info = $this->input->post('new_info');
$this->load->model('Member_model');
if($this->Member_model->edit_profile( $ID, $field, $new_info )){
echo 'success';
}else{
echo 'error';
}
}
Then
$('.btn_submit').on('click', function(){
var this_field_id = $(this).parent().parent().attr('id');
var new_info = $("#"+this_field_id+" .new_info").val();
alert(this_button);
$("#"+this_field_id+" form").trigger('submit');
$("#"+this_field_id+" form").submit(function(e){
e.preventDefault();
alert(this_field_id); // alerting correctly
$.post('../ajax/profileEdit', { edit_field: this_field_id , new_info: new_info },
function(data){
if(data == 'success')
{
alert(data); // <<<< alerts "true"
}
else if(data == 'error')
{
alert('Database error');
}
else{
alert('');
}
}
);
});
});
Just wrote it on here, so i haven't tested it. But give it a try, at least you might be able to know where the error is coming from. If you still get the same error, try alert data before the if(data == 'sucess'), to see what the profile edit func is returning.

jquery click function inside form submit function

I have a form with number of submit type as images. Each image has a different title. I need to find out the title of the clicked image. But my click function inside form submit is not working.
My form is:
<form action='log.php' id='logForm' method='post' >
<?
for($j=1;$j<=5;$j++)
{
?>
<input type="image" src="<?=$img;?>" title="<?=$url;?> id="<?="image".$j?> class="images" />
<?
}
?>
</form>
Jquery:
$("#logForm").submit(function(e)
{
$(".advt_image").click(function(event) {
var href=event.target.title;
});
var Form = { };
Form['inputFree'] = $("#inputFree").val();
// if($("#freeTOS").is(":checked"))
Form['freeTOS'] = '1';
$(".active").hide().removeClass('active');
$("#paneLoading").show().addClass('active');
var url="http://"+href;
$.post('processFree.php', Form, function(data)
{
if(data == "Success")
{
$("#FreeErrors").html('').hide();
swapToPane('paneSuccess');
setTimeout( function() { location=url }, 2500 );
return;
}
swapToPane('paneFree');
$("#FreeErrors").html(data).show();
});
return false;
});
How can I get the title value of clicked image inside this $("#logForm").submit(function())?
How can I use the id of clicked image for that?
You can use event.target property
$("#logForm").submit(function(e)
alert($(e.target).attr('title'));
});
http://api.jquery.com/event.target/
[UPDATE]
I just realized it wouldn't work. I don't think there is a simple solution to this. You have to track the click event on the input and use it later.
jQuery submit, how can I know what submit button was pressed?
$(document).ready(function() {
var target = null;
$('#form :input[type="image"]').click(function() {
target = this;
alert(target);
});
$('#form').submit(function() {
alert($(target).attr('title'));
});
});
[Update 2] - .focus is not working, but .click is working
http://jsfiddle.net/gjSJh/1/
The way i see it, you have multiple submit buttons. Instead of calling the function on submit, call it on the click of these buttons so you can easily access the one the user chose:
$('input.images').click(function(e) {
e.preventDefault(); //stop the default submit from occuring
alert($(this).attr('title');
//do your other functions here.
});
// Runtime click event for all elements
$(document).on('vclick', '.control', function (e) { // .control is classname of the elements
var control = e.target;
alert(e.currentTarget[0].id);
});
if you are not getting proper message in alert, just debug using Firebug.
Check following code you can get the title of clicked image.
Single click
$(document).ready(function()
{
$('#logForm').submit(function(e){
$(".images").click(function(event) {
alert(event.target.title);
});
return false;
});
});
Double click
$(document).ready(function()
{
$('#logForm').submit(function(e){
$(".images").dblclick(function(event) {
alert(event.target.title);
});
return false;
});
});
add following ondomready in your rendering page
$(document).ready(function(){
$("form input[type=image]").click(function() {
$("input[type=image]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
});
Now in your form's submitt action add follwing behaviour and yupeee!... you got it!....
$("#logForm").submit(function(e)
{
var title = $("input[type=image][clicked=true]",e.target).attr("title");
.....
.....
});

javascript confirm dialog not working properly

i've been trying to get a confirm box to work, i am using php and jquery to make a confirm box appear when clicking on a delete link, actual code :
$(document).ready(function(){
if (jQuery("a.delete-link").length > 0) {
$("a.delete-link").bind("click", function(){
return confirm("Sunteti sigur ca doriti sa stergeti?");
});
}
});
and the link is called :
sterge
the link is used to submit a form when clicked, the code for that is :
$(document).ready(function(){
if ($(".formSubmit").length > 0) {
if ($(".formSubmit").parents("form").find("input:submit").length == 0) {
$(".formSubmit").parents("form").append('<div style="width:1px;height:1px;overflow:hidden;"><input style="width:0;height:0;overflow:hidden;" type="submit" /></div>');
}
$(".formSubmit").click(function(){
$(this).parents("form").trigger("submit");
return false;
});
}
});
i do get the confirm dialog, but any option i chose, the form submits and the delete action is called.. any idea what i'm doing wrong ?
Bind the confirmation to the onSubmit of the form. You'll save a lot of hassle that way and you will get a confirmation no matter how the form was submited.
$( document ).ready ( function () {
$( 'selector for your form' ).submit ( function () {
return confirm ( 'Are you sure ...?' );
} );
} );
You have two click events bound to the anchor tag. The first event shows the confirm and the second submits the form.
Trigger the form submission only if the user confirmed:
$(document).ready(function(){
if ($(".formSubmit").length > 0) {
if ($(".formSubmit").parents("form").find("input:submit").length == 0) {
$(".formSubmit").parents("form").append('<div style="width:1px;height:1px;overflow:hidden;"><input style="width:0;height:0;overflow:hidden;" type="submit" /></div>');
}
$(".formSubmit").click(function(){
if ($(this).hasClass('delete-link') && confirm("Sunteti sigur ca doriti sa stergeti?"))
{
$(this).parents("form").trigger("submit");
}
return false;
});
}
});
Can you use this:
<a href="#" onclick"return javascript:void(0);" ... />

Categories