codeigniter form_validation with ajax - codeigniter-3

When i submit it with no data, it shows like this. but i want it to show on my modal, because i'm using the form_validation library.
enter image description here
This is my Controller:
$this->form_validation->set_rules('category_name','Category name','trim|required');
if($this->form_validation->run() == FALSE){
echo validation_errors();
} else{
$category = array(
"category_name" => $this->input->post('category_name')
);
$this->category_m->insert($category);
echo "Successfully Added.";
}
This is my ajax file:
$(document).on('submit', '#form' ,function(event){
event.preventDefault();
var form = $(this).serialize();
$.ajax({
url:"<?php echo base_url(); ?>category/operation",
type:"POST",
data:form,
success:function(data){
$('#form')[0].reset();
$('#mymodal').modal('hide');
$('#alert').fadeIn().html('<div class="alert alert-info">'+data+'</div>').fadeOut(5000);
table.ajax.reload();
}
})
});

This is not related to Codeigniter. It's JS/jQuery/HTML/...
Assuming that you have something like this in your HTML
<div id="mymodal">...</div>
Create another div#alert inside
<div id="alert">...</div>
And change the Javascript to something like
//You don't neet fadeIn/fadeOut
$('#alert').html('<div class="alert alert-info">'+data+'</div>');
$('#mymodal').modal('show');

Related

invisible reCAPTCHA javascript

I have the invisible reCAPTCHA set up, but it doesn't seem to want to call my callback function. My form looks like:
<form id='ContactAgentForm' name='ContactAgentForm' class='custom-form-widget-form standard_form' action='contact_agent' listing_id=1233445>
...
<div class='field captcha-field recaptcha_field' >
<div id='g-recaptcha-div' class="g-recaptcha" ></div>
</div>
...
<div class="field button-field">
<button class="button button-primary"><span>Send</span></button>
<a class="button button-cancel btn-close" href="#cancel"><span>Cancel</span></a>
</div>
</form>
In the javascript, I want to handle the fact that there might be multiple forms on the page, so I create a list of all the forms. For each form, I attach/render the reCAPTCHA logic, attaching my callback with the form passed as a parameter:
<script>
var $form_list = jQuery("form.custom-form-widget-form");
var onFormPageSubmit = function(token, $form ) {
console.log("Got here! ", token );
var field = $form.find('.g-recaptcha-response')[0];
field.value = token;
$form[0].submit();
};
var onloadCallback = function() {
$form_list.each( function() {
var $form = jQuery(this);
var $recaptcha = $form.find( ".g-recaptcha" );
if ( $recaptcha.length )
{
var recaptchaId = grecaptcha.render($recaptcha[0], {
'callback': function (token) { onFormPageSubmit(token, $form); },
'sitekey': "{$captcha_config.invisible_captcha_site_key}",
'size': 'invisible',
'badge': 'inline'
});
$form.data("recaptchaid", recaptchaId);
}
});
};
</script>
And just below that, I load the recaptcha/api.js file:
<script src="https://www.google.com/recaptcha/api.js?render=explicit&onload=onloadCallback"></script>
With some judicial 'console.log' statements, we get through all of the code EXCEPT for the callback (onFormPageSubmit). The "protected by reCAPTCHA" logo is there, but it seems that the form is just submitted, ignoring the reCAPTCHA call altogether.
All help appreciated.
Somewhere along the line, the validation function for the form was lost (it's in another file). The validation function was attached to the button, and it executed something like this:
$submit_button.on( 'click', function( event ) {
event.preventDefault();
// get the recaptchaid from form data
var $recaptcha_id = $form.data( "recaptchaid" );
if ( $recaptcha_id != undefined )
{
grecaptcha.execute($recaptcha_id);
}
} );
The "grecaptcha.execute" is the important thing - this is what triggers the actual reCAPTCHA call.

ZF3 redirect()->toUrl() not redirecting

I'm having a weird issue with ZF3.
I have a vanilla form in the view and a jquery ajax to send it to the controller, something like this:
<form>some form</form>
<script>
$("#form").submit(function (e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "stats",
data: {name: 'TEST'} // name selected in the form
});
});
</script>
The controller for action stats looks like this:
$stat = new Stat();
$route_name = $this->params()->fromRoute('name', 'none');
$post_name = $this->params()->fromPost('name', 'none');
if(!strcmp($route_name, 'none')) // if no redirection yet
{
if(!strcmp($post_name, 'none')) // if no form was sent
{
// display the form to choose the customer
return new ViewModel([
'customer_list' => $stat->get_customer_list(),
]);
}
else // if the form was sent, get name and direct to /stats/someName
{
return $this->redirect()->toRoute('stats', ['name' => 'someName']);
}
}
else // after redirection, get the name in the URL and show some data about this customer
{
return new ViewModel([
'avg_time' => $stat->get_avg_time(rawurldecode($route_name)),
]);
}
The problem is that the redirection does not occure on the screen but I still get the route parameter if I print $route_name after submitting the form.
Anyway, the goal is to have a form with a select to choose the customer name and load the customer data into /stats/[name]. Am I going in the wrong direction ? And is the redirection issue a bug or my code is wrong ?
So there I solved it thx to rkeet, this is the form & jquery:
<form id="customer_choice" method="POST" action=""> some form </form>
<script>
$("#customer_choice").submit(function () {
$("#customer_choice").attr('action', 'stats/' + $("#customer_select").val())
});
</script>
And this is the controller (hope no customer is named 'none'):
$stat = new Stat();
$name = $this->params()->fromRoute('name', 'none');
if(!strcmp($name, 'none'))
{
return new ViewModel([
'customer_list' => $stat->get_customer_list(),
]);
}
else
{
return new ViewModel([
'avg_time' => $stat->get_avg_time($name),
]);
}
The result is basepath/stats/[customer name] and changing the url manually works as well.
(if you don't want changing the url manually to change the result, use fromPost instead of fromRoute)

how to integrate the mailchimp with core php

I need to integrate the mail chimp api with core php I tried more type of codes but not working. Finally, I found the below code. I have created an api key with mailchimp, likewise campaigns, template and list in the mailchimp.
<script src="jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$('#subscribe').submit(function() {
if (!valid_email_address($("#email").val()))
{
$(".message").html('The email address you entered was invalid. Please make sure you enter a valid email address to subscribe.');
}
else
{
$(".message").html("<span style='color:green;'>Adding your email address...</span>");
$.ajax({
url: 'subscribe.php',
data: $('#subscribe').serialize(),
type: 'POST',
success: function(msg) {
if(msg=="success")
{
$("#email").val("");
$(".message").html('<span style="color:green;">You have successfully subscribed to our mailing list.</span>');
}
else
{
$(".message").html('The email address you entered was invalid. Please make sure you enter a valid email address to subscribe.');
}
}
});
}
return false;
});
});
function valid_email_address(email)
{
var pattern = new RegExp(/^[+a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i);
return pattern.test(email);
}
</script>
<?php
$api_key = "key";
$list_id = "id";
require('inc/MAPI.class.php');
$Mailchimp = #new Mailchimp( $api_key );
echo bool($Mailchimp);
//$Mailchimp_Lists = #new Mailchimp_Lists( $Mailchimp );
//$subscriber = $Mailchimp_Lists->subscribe( $list_id, array( 'email' => htmlentities($_POST['email']) ) );
if ( ! empty( $subscriber['leid'] ) ) {
echo "success";
}
else
{
echo "fail";
}
?>
<div class="message"></div>
<form role="form" method="post" id="subscribe">
<input type="email" id="email" name="email" placeholder="you#yourself.com" value="">
<button type="submit">SUBSCRIBE</button>
</form>
This is my code, but it's not returning, errors only. Please help me.

calling echo $this->action('panLogin','user') and $this->action('panRegister','user') on same script

I have a problem, i'm trying to render 2 forms (login and register) on one layout scrpt (header.phtml), every time i submit on one of the forms both actions for the controller are getting fired and i'm unsure how to fix it.
The forms are getting rendered fine within the layout, however when you click 'Login' or 'Register' on the forms the code fires in both the 'login' and 'register actions.
the header layout script snippet:-
<div class="left">
<h1>Already a member? <br>Then Login!</h1>
<?php
echo $this->action('panlogin', 'user');
?>
</div>
<div class="left right">
<h1>Not a member yet? <br>Get Registered!</h1>
<?php
echo $this->action('panregister', 'user');
?>
</div>
the action scripts (phtmls)
panregister.phtml
<div id="pan-register">
<?php
$this->registerForm->setAction($this->url);
echo $this->registerForm;
?>
</div>
panlogin.phtml
<div id="pan-login">
<?php
$this->loginForm->setAction($this->url);
?>
</div>
the user controller actions:-
class Ajfit_UserController extends Zend_Controller_Action
{
protected $_loginForm;
protected $_registerForm;
public function init()
{
$this->_loginForm = new Ajfit_Form_User_Login(array(
'action' => '/user/login',
'method' => 'post',
));
$this->_registerForm = new \Ajfit\Form\User\Registration(array(
'action' => '/user/register',
'method' => 'post'
));
}
//REGISTER ACTIONS
public function panregisterAction(){
$this->registerAction();
}
public function registerAction(){
$request = $this->_request;
if ($this->_request->isPost()){
$formData = $this->_request->getPost();
}
$this->view->registerForm = $this->_registerForm;
}
//LOGIN ACTIONS
public function panloginAction(){
$this->loginAction();
}
public function loginAction(){
$request = $this->_request;
if(!$auth->hasIdentity()){
if ($this->_request->isPost()){
$formData = $this->_request->getPost();
}
}
$this->view->loginForm = $this->_loginForm;
}
}
Please can someone with a little more knowlegde with the action('act','cont'); ?> code with in a layout script help me out with this problem.
Thanks
Andrew
While David is correct where best practices are concerned, I have on occasion just added another if() statement. Kinda like this:
if ($this->getRequest()->isPost()) {
if ($this->getRequest()->getPost('submit') == 'OK') {
just make sure your submit label is unique.
Eventually I'll get around to refactoring all those actions I built early in the learning process, for now though, they work.
Now to be nosy :)
I noticed: $formData = $this->_request->getPost(); while this works, if you put any filters on your forms retrieving the data in this manner bypasses your filters. To retrieve filtered values use $formData = $this->getValues();
from the ZF manual
The Request Object
GET and POST Data
Be cautious when accessing data from the request object as it is not filtered in any way. The router and
dispatcher validate and filter data for use with their tasks, but
leave the data untouched in the request object.
From Zend_Form Quickstart
Assuming your validations have passed, you can now fetch the filtered
values:
$values = $form->getValues();
Don't render the actions in your layout. Just render the forms:
<div class="left">
<h1>Already a member? <br>Then Login!</h1>
<?php
echo new \Ajfit\Form\User\Login(array(
'action' => '/user/login',
'method' => 'post'
));
?>
</div>
<div class="left right">
<h1>Not a member yet? <br>Get Registered!</h1>
<?php
echo new \Ajfit\Form\User\Registration(array(
'action' => '/user/register',
'method' => 'post'
));
?>
</div>
Then, whichever form gets used will post to its own action.

Create a form for uploading images

I want to let users upload images from their drives. Searching around the net, here's what I've found :
The form :
class ImageForm extends BaseForm
{
public function configure()
{
parent::setUp();
$this->setWidget('file', new sfWidgetFormInputFileEditable(
array(
'edit_mode'=>false,
'with_delete' => false,
'file_src' => '',
)
));
$this->setValidator('file', new sfValidatorFile(
array(
'max_size' => 500000,
'mime_types' => 'web_images',
'path' => '/web/uploads/assets',
'required' => true
//'validated_file_class' => 'sfValidatedFileCustom'
)
));
}
}
the action :
public function executeAdd(sfWebRequest $request)
{
$this->form = new ImageForm();
if ($request->isMethod('post'))
if ($this->form->isValid())
{
//...what goes here ?
}
}
the template :
<form action="<?php echo url_for('#images_add') ?>" method="POST" enctype="multipart/data">
<?php echo $form['file']->renderError() ?>
<?php echo $form->render(array('file' => array('class' => 'file'))) ?>
<input type="submit" value="envoyer" />
</form>
Symfony doesn't throw any errors, but nothing is transfered. What am I missing ?
Youre missing an impotant part which is binding the the values to the form:
public function executeAdd(sfWebRequest $request)
{
$this->form = new ImageForm();
if ($request->isMethod('post'))
{
// you need to bind the values and files to the submitted form
$this->form->bind(
$request->getParameter($this->form->getName())
$request->getFiles($this->form->getName())
);
// then check if its valid - if it is valid the validator
// should save the file for you
if ($this->form->isValid())
{
// redirect, render a different view, or set a flash message
}
}
}
However, you want to make sure you set the name format for your form so you can grab a the values and files in the fashion... In your configure method you need to call setNameFormat:
public function configure()
{
// other config code
$this->widgetSchema->setNameFormat('image[%s]');
}
Also in configure you dont need to call parent::setUp()... That is called automatically and is actually what invokes the configure method.
LAstly, you ned to have to correct markup - your emissing the form name from your tag:
<form action="<?php echo url_for('#images_add') ?>" name="<?php echo $form->getName() ?>" method="POST" enctype="multipart/data">
Personally I like to use the form object to generate this as well as it looks cleaner to my eyes:
<?php echo $form->renderFormTag(
url_for('#images_add'),
array('method' => 'post') // any other html attriubutes
) ?>
It will work out the encoding and name attributes based on how youve configured the form.