client side validation not working for model window / ajax-loaded-form in yii - ajax

I am using Yii-user extension in the main layout i have a sign up link which is common to all the Cmenu
view/main layout
echo CHtml::link('Signup','#',array('id'=>'regi'));
$("#regi").click(function(){
$.ajax({
type:'GET',
url:'<?php echo Yii::app()->request->baseUrl;?>/index.php/user/registration',
success:function(res){
$("#dispdata").show();
$("#dispdata").html(res);
}
});
});
<div id="dispdata"><div>
**yii user extension **renders this perfectly and even submit its correctly if form values a re valid.
but if the values are incorrect and blank it redirect to url .../user/registration
which is not what my need .I need guidance what do i do such that if the values are incorrect or blank it should not redirect and display the errors in model window.
I did tried but hardly could get the satisfied results
if i place the following the model window itself doesnt appear what do i do
module registrationController i placed
....//some code here (**in yiiuser register controller**)
if ($model->save()) {
echo CJSON::encode(array(
'status'=>'success',
));
}
....//some code here...
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
$this->renderPartial('registration',array('model'=>$model,),false,true);
in module view registration
<?php echo CHtml::ajaxSubmitButton(Yii::t('registration'),CHtml::normalizeUrl(array('user/registration','render'=>false)),array('dataType'=>'json',
'success'=>'function(data) {
if(data != null && data.status == "success") {
$("#registration-form").append(data.data);
}
}')); ?>
can anyone please guide me am working past 10 ten days tried every hook or crook method but could not obtain the results......how can the model window with client side validation be done appear..... Please guide me or let me know something better can be done
rules in registration model
if (!(isset($_POST['ajax']) && $_POST['ajax']==='registration-form')) {
array_push($rules,array('verifyCode', 'captcha', 'allowEmpty'=>!UserModule::doCaptcha('registration')));
as well was not with attributes for reqired field
have changed to
array_push($rules,array('verifyCode', 'captcha','message' => UserModule::t("captcha cannot be blank.")));
and added the verifycode to required field
yet not working,

The simple way is using render method in your Ajax action and creating empty layout for this action. If you do so, validation scripts will be included in the server response. Also you need to exclude jquery.js and other script with Yii::app()->clientScript->scriptMap and include them in main layout always.

Related

PHPMailer - Show success message after redirect

I building a very simple app with Laravel4 and so far i have managed to set up PHPMailer to work with a contact form, the users fill in their details and send me an email, normal stuff, everything works fine.
After the user sent the email successfully, he is redirected to the home page via
if($m->send()) {
header('Location: /path/to/home/');
die();
}
Now what i need is a success message that appears at the top of the homepage if the user has been redirected after a successfully sent email.
I have a div with .success class sitting on top of my home page, absolutely positioned out of view, with a negative Y value.
I tried pulling it down after on $m->send() like so:
if($m->send()) {
header('Location: /path/to/home/');
echo "<script type='text/javascript'>
$('.success').animate({
top: 0
}, 2000);
</script>";
die();
}
but it didnt work. In fact, nothing i echo after the header() has any effect.
What can I do?
Thank you guys!
This is simple HTTP - when you set the Location header, it's telling the browser to leave the page you're on and go somewhere else - anything that happens afterwards (like that little JS snippet) will never reach the browser. You need to put that snippet on the page you're redirecting to, not on this one.
I solved the problem after realizing that you can't use jquery on the document before you actually link the jquery lib in.
So, in my phpmailer config file, I set $_SESSION['success'] = true before i redirect with the header('Location: /path/to/home/'); , and then, on the Homepage, the page I wanted the success message to be displayed on, I added this bit of code (AFTER linking the jQuery library):
<?php
if(isset($_SESSION['success']) && $_SESSION['success'] == true ) {
?>
<script type='text/javascript'> $('.success').animate({top : 0}, 'normal').delay(3000).animate({top : -57}, 'normal');</script>
<?php
} else {
$_SESSION['success'] = false;
}
?>
I don't know if this is a good practice but it does work.
I also had to session_start(); on my Homepage (obviously).
Hope this helps anyone in the same situation!

How to use AJAX in Joomla component to load the State field based on the country selected?

Inside a component's view, I have something like this:
<?php echo TestcompHelperFind::loadStates(...); ?>
<?php echo TestcompHelperFind::loadCounties(...); ?>
The above static functions load <select> dropdowns with the state names and countries respectively.
The class TestcompHelperFind is located in the file /administrator/components/com_testcomp/helpers/find.php.
How do I load States dropdown list based on the country selected using AJAX? I'm not sure what url I should provide in the ajax function.
On the client, you will need a function that watches the country select for changes, and when it happens calls the appropriate url with a callback that will populate the counties select.
On the server, you need to output the select content.
Since you have the html output already working, let's use this approach. As an alternative you could have your server method return a json object and use the javascript to parse it and populate the select. But let's stick to html communication, i.e. the server returns the html contents of the select.
1. On the server
1.a. Output the counties select
We only need to return the result of the TestcompHelperFind::loadCounties(...); to the ajax call. This is achieved easily writing a new method in the component's controller, i.e. the controller.php in the root of the component folder or one of the sub-controllers if appropriate. It's up to you to place it in a meaningful spot.
Inside the controller simply add a new public task such as
class SomethingController extends JController
{
public function getCountiesHTML() {
$input = JFactory::getApplication()->input;
$country = $input->getCMD('filter_country');
// load helper if necessary, then:
echo TestcompHelperFind::loadCounties($country);
exit; // this will stop Joomla processing, and not output template modules etc.
}
Please note the exit; at the end, this will make Joomla output only the component's output (our echo) and not the whole template/modules etc.
1.b Add an ID to the country and county selects so that it will be possible to manipulate them on the client; I'll assume filter_country and filter_county ;
2. On the client
you will want to invoke the url
index.php?option=com_something&action=getCountiesHTML&filter_country=UK
when the country select is changed. It will also need to cancel any pending requests to avoid overlapping messages. To keep things simple, let's assume you use a library to handle Ajax, I'll write an example for jQuery:
<script>
var xhr;
jQuery(function($) {
$('#filter_country').change(function(){
var filterCountry = $('#filter_country').val();
if (xhr && xhr.abort) {xhr.abort();xhr=false;}
xhr = jQuery.ajax(
url: 'index.php',
data: 'option=com_something&task=getCountiesHTML&filter_country='+filterCountry,
success: function(data){
jQuery('#filter_county').replaceWith(data);
}
);
});
});
</script>
For cancelling the previous request, please see a dedicated answer such as this one.

If condition for 2 forms(2 submit buttons) in one controller in CI

I have a controller auth and there are 2 methods login and register.
And it is working nicely.
However, I need to have another function called login_and_register which will have an if condition that will determine which part will be executed. If the login part (basically code from login method) or register part (code from register method).
The if condition should be checking which submit button was clicked.
But here is the problem.
I need the form_open for both forms (login and register) stay like this:
<?php echo form_open('auth/login_and_register'); ?>
And this cannot be changed to e.g. auth/login_and_register_log or auth/login_and_register_reg or auth/login_and_register/log or auth/login_and_register/reg etc.
The login and register forms are in the same view and after submit is pressed this function login_and_register in auth controller is exectuted.
I was thinking that I can make the if condition base on the name of submit value, because for login form it is called submitlog and for registration form it is called submitreg.
So, maybe something like this:
if( isset($this->form_validation->set_value('submitlog')) ) {
//code for login part
}
elseif ( isset($this->form_validation->set_value('submitreg')) ) {
//code for registration part
}
else {
//code for redirect to homepage
}
But it is not working. Any idea why?
Querying the submit button names is a good idea. Here is a piece of code that works:
if ($this->input->post("submitlog") !== false) {
//code for login part
} elseif ($this->input->post("submitreg") !== false) {
//code for registration part
} else {
//code for redirect
}
instead of that, you can keep a hidden field in both the forms with the value of corresponding form name. In the controller you can check this field value and identify which form is submitted. Then you can redirect into the required function..

How to make sure a file is selected before uploading

Hi I am using codeigniter for file uploading and I am using this code
echo form_open_multipart('controller_a');
echo form_upload('userfile');
echo form_submit('Upload','upload');
echo form_close();
I store the pointer to the uploaded file in the database,
My question is how do I make sure that the user has selected a file before clicking on upload button because as of now the code submits even if the user clicks directly on upload without selecting a file
Along with client side verification, you should use server side verification, too. Currently, CodeIgniter does not provide a function, so one can use native PHP function is_uploaded_file:
if (is_uploaded_file($_FILES['myfile']['tmp_name']))
{
$this->load->library('upload');
$this->upload->do_upload('myfile');
}
You can't, not in CodeIgniter at least. You'll need to have JS overwrite the onsubmit property of the form and then test the userfile input's value.
use JS
very basic code, but it works.
<script type="text/javascript">
<!--
function validate_form ( )
{
valid = true;
if ( document.upload_form.something.value == "" )
{
alert ( "Please select a file before clicking upload ! " );
valid = false;
}
return valid;
}
//-->
</script>
and use onsubmit even in the form
onSubmit="return validate_form ( );"
when a user click on upload button without selecting any file, it will alert the user .
Your best bet is to use a jQuery plugin like the following:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
This will allow you to select what input values will need to be selected, and customize a message to inform the user what field(s) they are missing.

cakephp updating elements

I have an index view which has some elements on it .
index controller code;
$userID = $this->Authsome->get('id');
$qnotes = $this->Qnote->getnotes($userID);
$this->set('qnotes', $qnotes)
$this->render();
elements have been added to the page using
index view code
<?php echo $this->element('lsidebar'); ?>
now the Issue is I also Have an add controller.
add controller code
function add() {
if(!empty($this->data)) {
unset($this->Qnote->Step->validate['qnote_id']);
$this->Qnote->saveAll($this->data);
$this->Session->setFlash('New Note Template has been added.','flash_normal');
}
}
now what I am trying to achieve is once I add a Qnote i want the element('lsidebar') updated
for the new Qnote.
I am Using the Ajax helper. found at http://www.cakephp.bee.pl/
also Here the add qnote View Code :
<?php echo $ajax->submit(
'Submit', array(
'url' => array(
'controller'=>'qnotes',
'action'=>'add')
));
I know its sound like a noob question . can Somebody point me in the right direction atleast.
I have tried everything i could think off. I bet the solution something easy which i didnt think off
help :)
If you want to dynamically update a sidebar with information that is submitted via ajax, there should be a "success" option in your ajax post that would allow you to fire a specific javascript action when the post is finished (or succeeds). You should write a small javascript ajax function to reload the contents of your sidebar when the post succeeds.
See this other stackoverflow answer: CakePHP ajax form submit before and complete will not work for displaying animated gif

Resources