With my CakePHP's registration form, once clicking Submit button, I simply want to display Javascript Confirm dialog box, which should work like:
If pressed Ok, should submit the form
If pressed Cancel, should not go for submit action
But here, when i press Cancel, though it gets submitted. Don't know why?
CakePHP Form Code:
<?php echo $form->create('Noncompetitor', array('type' => 'file', 'url' => '/register', 'onSubmit' => 'confirmfrmSubmit();'));?>
My JS Code:
function confirmfrmSubmit(){
var agree=confirm("Are you sure you wish to continue?");
if (agree)
return true ;
else
return false ;
}
Please let me know, if you fellows have some idea on it.
Thanks !
A simpler method can also be used, Try this:
$this->Form->create('Request',array('onsubmit'=>'return confirm("are you sure?");'))
Update: Credit to bicycle for fixing my broken callback. See below for details. (And a big raspberry to StackO for not allowing the answer author to have the final say on accepting an edit.)
Here's a solution using jQuery:
<?php
$this->Html->scriptBlock("
jQuery(function($){
$('form.noncompetitor').submit(function(event){
if (!confirm('Are you sure?')) { return false; }
});
});
",array('inline'=>false)); // inline => false will put this snippet in the DOM's head.
echo $this->Form->create('Noncompetitor',array(
'type'=>'file','url'=>'/register',
'default'=>false,'class'=>'noncompetitor'
));
/* The rest of your form */
I think your function is failing because you are never actually returning the value from confirmfrmSubmit().
Try adding the return part to the onSubmit field, like so:
<?php echo $form->create('Noncompetitor', array('type' => 'file', 'url' => '/register', 'onSubmit' => 'return confirmfrmSubmit();'));?>
Your JS code should work as it is, the problem is just that the confirm value is never being passed to the form when the onSubmit handler is called.
P.S. note that you can do the following in the JS code:
return confirm("Text");
Hope this helps.
I found a very simple solution to this query:
<?php echo $form->create('ModelName', array('type' => 'file', 'url' => 'url', 'name' => 'frmRegister', 'onsubmit' => 'validatefrm(); return false;')); ?>
With onsubmit function, I simply defined 'validatefrm(); return false;'
function validatefrm(){
// my condition, when i needs it to submitted
document.frmRegister.submit();
return true;
}
and found it working smooch :)
Let me know, if it helps you.
You were actually 99% of the way there in the beginning .. you just needed to add 'return' before your call to the validation function.
<?php echo $form->create('Noncompetitor', array(
'type' => 'file',
'url' => '/register',
'onSubmit' => 'return confirmfrmSubmit();'));
?>
Will do it.
There is the following step:-
- include this jquery file-
echo $this->Html->css('/css/jquery-confirm.min.css', ['block' => 'css']);
Create submit button
<?= $this->Form->button('<i class="fa fa-check"></i><span class="hidden-xs"> ' . __('Save') . '</span>', ['type' => 'submit', 'escape' => false, 'id' => 'submit_form_id', 'class' => 'btn green', 'title' => 'Save']); ?>
$('body').on('click', '#submit_form_id', function (e) {
e.preventDefault();
var submitFormVar=1;
if (submitFormVar!= 0) {
$.confirm({
title: '',
content: 'Do you want to stop submit form' ,
buttons: {
ok: function () {
$(form).submit();
},
cancel: function (o) {
return o;
}
}
});
} else {
$(form).submit();
}
});
Jquery code
if you want to submit the form then the value is 0
if you want to not submit the form then the value is 1
implement as your requirement logic
Related
I have build a search/result page with FacetWP and ACF.
On the result page I add the possibility to edit one specific repeater fields for each result listed.
To do that I include in the FacetWP loop this code:
<?php
$options = array(
'id' => 'acf-form_'.$post->ID,
'post_id' => $post->ID,
'post_title' => false,
'post_content' => false,
'field_groups' => array('group_6166044822675'),
'fields' => array('field_6166066864387'),
);
acf_form($options);
?>
On the main page the button “add row” work well.
When with a Facet I refine the result to show only the post from October 2021 or any other specification, FacetWP import the new search result via ajax.
But this time if I click on a “add row” button, nothing happen.
The javascript and the new HTML code imported via ajax by FacetWP are not binded.
There are many answers about binding problem but I can't find how to solve it because the ACF function has no name.
! function() {
var t = {
...
945: function() {
! function(t) {
var e = acf.Field.extend({
type: "repeater",
wait: "",
events: {
'click a[data-event="add-row"]': "onClickAdd",
'click a[data-event="duplicate-row"]': "onClickDuplicate",
'click a[data-event="remove-row"]': "onClickRemove",
'click a[data-event="collapse-row"]': "onClickCollapse",
showField: "onShow",
unloadField: "onUnload",
mouseover: "onHover",
unloadField: "onUnload"
}, ...
Is there a way to target this function ?
I'm having an issue with submitting a TbActiveForm and the renderPartial wiping my page out and displaying only the partial view. I want to reload only the widget after my action triggers and finishes. I'm also using a modal to display and make changes.
view:
$form = $this->beginWidget(
'booster.widgets.TbActiveForm',
array(
'id' => 'horizontalForm',
'type' => 'horizontal',
'action' => Yii::app()->createUrl('orderControl/order/returns.save'),
)
);
echo $form->hiddenField(
$editReturnFormModel,
'orderId',
array(
'value' => $editReturnFormModel->orderId
)
);
$this->widget(
'bootstrap.widgets.TbButton',
array('buttonType' => 'submit', 'type' => 'primary', 'label' => 'Save')
);
$this->endWidget();
Action:
$this->controller->renderPartial('ScModules.orderControl.widgets.ReturnsWidget.views._returnItems', array('returnsDataProvider'=>$returnsDataProvider, 'editReturnFormModel'=>$editReturnFormModel));
One other point is that the Yii::app()->createUrl('orderControl/order/returns.save') is change the page url all together. On this page page I'm directed to, the view is created fine. I need the widget to rebuild/refresh on the current page and not send me somewhere else. Any ideas on solution would be appreciated.
Here's what I would do:
Wrap your form widget inside a div or whatever block tag you like.<div id="myFormWrapper"> (your widget goes here) </div>
Add a custom ID in your form (id="formId") and submit button (id="submitButtonId")
Add some jQuery in order to submit your form and replace the old widget with the new
$(document).on('click', '#submitButtonId' , function() {
$.ajax({
type: 'POST',
url: $('#formId').attr('action'),
data : $('#formId').serialize(),
beforeSend : function(){
//do anything you want before sending the form
},
success : function(data){
//We'll replace the old form with the new form widget
$('#myFormWrapper').html(data);
},
error : function(data){
console.log('ops');
},
});
return false;
});
Do whatever you want to do in your Controller action and use renderPartial.
//The action below should be the same that you used in the action attribute of the form
public function actionProcessForm(){
$model = new MyFormModelName();
if(isset($_POST['MyFormModelName'])){
$model->attributes = $_POST['MyFormModelName'];
if($model->save()){
//Do whatever you want here
$returnsDataProvider = new CActiveDataProvider('YourModel');
$this->renderPartial('//folder/to/your/view', array('returnsDataProvider'=> $returnsDataProvider, 'editReturnFormModel'=>$editReturnFormModel));
}else{
//You might want to render something else here
$this->renderPartial('errorViewPage');
}
}
}
code in my view is bellow:
<?php echo $form->create( "ChatForm", array("id" => "chat_form", "type" => "post",'class'=>'form_chat',"url" => array( "controller" => "qasamples", "action" => "quick_request" ) ) );
echo $form->hidden( 'ChatForm.pid', array('class'=>'chat_input_hidden') );
echo $form->hidden( 'ChatForm.uid', array('class'=>'chat_input_hidden') );
echo $form->textarea('ChatForm.text',array('id'=>'text_input','rows'=>'14','cols'=>'400','style'=>'resize:none;width:907px;border:0px;','onkeyup'=>"onTextChange()")); ?>
<p style="text-align:center;margin-top:20px;"><button type=submit id="chat_send">Send</button></p>
<?php $form->end(); ?>
here is the controller code:
public function quick_request(){
if(!empty($this->data))
{
$fields=array('QasampleAnswer.uid','QasampleAnswer.pid','QasampleAnswer.text');
$data=array(
'uid'=>$this->data['ChatForm']['uid'],
'pid'=>$this->data['ChatForm']['pid'],
'text'=>$this->data['ChatForm']['text']);
if($this->QasampleAnswer->save($data))
{
$data_update=array(
'id'=>$this->data['ChatForm']['pid'],
'status'=>'0');
if($this->Qasample->save($data_update))
$this->render('text2');
}
}
}
Can I just send the message and without fresh my page?
I heard that CakePHP and AJAX can make it work, but I'm a new learner of CakePHP and Javascript also. I hope you guys can help me with it. Thank you very much. The page text2 is to turn the page back to where I was,but it not working well.So I hope I could send my message and just stay this page without refreshing.
Post your data with Ajax, jquery gives you a lot of options to do that... you can also implement a JavaScript and make it call when the for. is submitted (this can be achieved when you add in the array at $form->create array('onsubmit'=>'return yourFunction()') then you have to red your form data in this function, post it via ajax and very important return false in this function (it will prevent the form submitting) you can also make a button instead of the submit button that calls this function but then you have to implement in the text-field that when the user presses enter it should send the data... it is more comfortable with the onsubmit thing.
If you need an example I can also provide a practical code for this...
I will use a cake-less example of the JavaScript
<?php echo $form->create( "ChatForm", array("id" => "chat_form", "type" => "post",'class'=>'form_chat',"url" => array( "controller" => "qasamples", "action" => "quick_request", "onsubmit"=>"return performPostRequest(this)") ) );
this is the part you use to create the form
<script type="text/javascript">
function performPostRequest(form) {
parameters="";
for(var i=0;i<form.elements.length;i++) {
if(parameters!="")
parameters+="&";
if(form.elements[i].checked==true || !(form.elements[i].type=="radio" || form.elements[i].type=="checkbox"))
parameters+=form.elements[i].name+"="+encodeURIComponent(form.elements[i].value);
}
$.ajax({
url: form.action,
data: parameters,
type : 'POST',
});
return false;
};
</script>
and this is the JavaScript function, I use it myself so it should work without a Problem :) It simulates your post request, but uses Ajax and therefore your page will not reload...
You need a simple Ajax Call like the following and modify the form create so that it does not post automatically.
$ajax->form(array('type' => 'post',
'options' => array(
'model'=>ChatForm,
//'update'=>'UserInfoDiv',
'url' => array(
'controller' => 'chatforms',
'action' => 'quick_request'
)
)
));
I'm trying to create a button that submits a form then redirects to another page.
$('#saveApp').click(function() {
event.preventDefault();
$("form[id='CustomerSaveForm']").submit(); // use the native submit method of the form element
window.location.href = "<?php echo EWConfig::$URL?>/ExpressWay/ProgramApplications/sales/residence";
return true;
});
This will redirect but not submit the form although commenting out the event.preventDefault() will do the opposite.
Ended up using a server-side solution.
View
echo $this->Form->button('Save and Redirect', array('name' => 'data[redirect]'));
Controller
if(!is_null($this->request->data('redirect'))){
$this->redirect(array('controller' => 'Program', 'action' => 'index'));
}
Good day to all,
Been searching all day on how to do this. What I want is to make every 'click' to go into one php file and determine what will be the action.
itemAction.php
include 'inc/database.php';
include 'inc/functions.php';
if ($_GET['action'] == 'delete') {
// do delete action <-- this one is working
} else if ($_GET['action'] == 'edit') {
// do edit action; NOW HERE I WANT TO REDIRECT TO ANOTHER PAGE
header("location: edit.php"); // I can't do something like this. Why?
}
html
<div class="action">
<a id="delete" href="itemAction.php" rel="<!--some_id-->"><img src="images/trash.ico" alt="delete"></a>
<a id="edit" href="itemAction.php" rel="<!--some_id-->"><img src="images/Pencil-icon.png" alt="edit"></a>
</div>
js
$("div.action a#delete").click(function (e) {
var decision = confirm("Are you sure you want to delete the item?");
if (decision) {
e.preventDefault();
$.get('itemAction.php', {action : 'delete', id : $(this).attr("rel")}, function (data) {
location.reload();
alert("Succssfully deleted!");
});
}
return false;
});
$("div.action a#edit").click(function (e) {
e.preventDefault();
$.get('itemAction.php', {action : 'edit', id : $(this).attr("rel")});
});
The delete action seems to be working.. But I can't do I want in the edit action which is to redirect to other page. What better ways are there to do it that way? Any help would be much appreciated. Thanks
You can not do this because ajax will only send you response html, text, xml or json response but can not do redirection.
For redirecting you must return anything say "redirectme." and based on that response you need to add code in javascript to redirect at desired location.
what you can do is?
in php file add below code,
echo json_encode(array('status' => 'edit', 'url' => 'edit.php'));
based on above response modify your $.get response callback as below.
$.get('itemAction.php', {action : 'delete', id : $(this).attr("rel")},
function (data)
{
if(response.status == 'edit'){
window.location = response.url;
}
});
it just a guide line you need set it according to your need.
Comment Response
if js is disabled then you need to code accordingly.
first of all you need to modify your html links as below,
<a id="delete" href="itemAction.php?action=delete&id=someid"
<a id="edit" href="itemAction.php?action=edit&id=someid"
and by clicking on above link use their href attribute to pass into $.get as below.
$.get( $(this).href()
by doing so it js is disabled your code will work too.
Have your button go somewhere
<form method="get" action="someScript.php">
<button>Do things</button>
</form>
Then in someScript.php
<?php
// do things
header("Location: redirectToHere.php");