Ajax modal form validation and submit - codeigniter

I am new to MVC and currently working on a basic website setup. I am trying to have a modal window open where one can input some data and then press submit to submit it back to the database.
Using CodeIgniter and this Jquery Modal (doesn't necessary have to be this one thou).
Again I am very new to MVC so having some trouble visualizing the flow of data.
The modal opens correctly, but I'm trying to display the validation/errors in the same modal without opening a new window. What would I place near echo("error-ajax");, opening a view seems to result in opening a new window.
View -- Opens Modal:
...
...
View -- Actual Form:
<?php echo validation_errors(); ?>
<?php echo form_open('form'); ?>
<h3>New</h3>
<p>
<label>ID: <input class="pull-right" type="text" name="idnumber" value="<?php echo set_value('idnumber'); ?>" size="9"/></label>
</p>
<div><input type="submit" value="Submit" /></div>
</form>
<script>
$(function(){
$('form').submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
async: false,
url: "<?php echo site_url("bondform/save_form"); ?>",
success: function(){alert('Succes');},
error: function(){alert('Error');}
});
});
});
</script>
Controller:
<?php
class Bondform extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$config = array(
array(
'field' => 'idnumber',
'label' => 'Id Number',
'rules' => 'trim|required|min_length[9]|max_length[9]|xss_clean'
)
);
$this->form_validation->set_rules($config);
}
public function view_form()
{
$this->load->view('bond/form');
}
public function save_form()
{
if ($this->form_validation->run() == FALSE)
{
if ($this->input->is_ajax_request())
{
echo("error-ajax"); //placeholder, debug
}
else
{
echo("error-noajax"); //placeholder, debug
}
}
else
{
echo("succes-close"); //placeholder, debug
}
}
}
Thank you very much,

To start, move your ajax function from the modal view to the view that opens it, then you can control the contents of the modal without losing your form view.
Opens Modal:
<script>
$(function(){
$('body').on('submit', 'form', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url("bondform/save_form"); ?>",
data: $(this).serialize();
success: function(response){ $('#form_container').html(response); alert('Succes');},
error: function(){alert('Error');}
});
});
});
</script>
Actual Form:
<div id="form_container">
<?php echo validation_errors(); ?>
<?php echo form_open('bondform/save_form'); ?>
<h3>New</h3>
<p>
<label>ID: <input class="pull-right" type="text" name="idnumber" value="<?php echo set_value('idnumber'); ?>" size="9"/></label>
</p>
<div><input type="submit" value="Submit" /></div>
</form>
</div>
Should get you started in the right direction.

Related

Adding checked attribute to selected input ajax

Made a ajax filter with custom taxonomy on WordPress, everything works fine but problem is that checkbox doesn't get checked attribute when click and new results are shown. I don't know what I'm missing here?
HTML
<div class="categories">
<?php
$cat_args = get_terms(array(
'taxonomy' => 'position',
'orderby' => 'name',
));
$categories = $cat_args;
foreach($categories as $cat) : ?>
<label class="hotel-service block mb-2 font-montserrat text-altumTitle text-lg font-medium">
<input type="checkbox" value="yes" class="checkbox" data-category="<?php echo $cat->term_id ?>" href="<?php echo get_category_link($cat->term_id); ?>"> <?php echo $cat->name; ?></label>
<?php endforeach; ?>
</div>
Ajax call
(function($) {
$(document).ready(function(){
$(document).on('click', '.hotel-service > input', function(e){
e.preventDefault();
var category = $(this).data('category');
$.ajax({
url: wpAjax.ajaxUrl,
// filter here is handler for add_action callback function in ajax-filter.php
data: { action: 'hotelService', category: category},
type: 'post',
success: function(result) {
$('#response').html(result);
},
error: function(result) {
console.warn(result);
}
});
});
});
})(jQuery);

Wordpress Sending email through Ajax without page refresh hangs on admin_ajax.php

I have this test page on a website - https://piclits.com/test-slideshow/
It displays a bunch of images/PICLITS and grabs them randomly from a folder 12 at a time into a slideshow.
I want to email the main image without refreshing the page (which would bring up 12 new images) from the email button which opens up a popup to add email addresses.
All is good - I can grab the image and mail it but the script does something wacky where it flashes on the page and then hangs up at admin-ajax.php rather than just staying on the page and sending the email.
My Form:
<div class="ajax-form-container" style="float: left">
<form id="ajaxformid" action="" method="POST">
<p>Email this PIC-LIT to a friend.<br />You may include multiple emails if you separate them with a comma.</p>
<ul style="list-style-type: none;">
<li>Email: <textarea name="piclit_email" id="piclit_email" rows="4" cols="50" autofocus=""></textarea><input type="hidden" name="founder_piclit" id="founder_piclit" value=""></li>
<li><input type="hidden" name="piclit_bcc" class="piclit_bcc" value="0"></li>
<li>bcc: <input type="checkbox" name="piclit_bcc" class="piclit_bcc" value="1">
<?php wp_nonce_field( 'fiveb_ajax_nonce', 'fiveb_nonce_field' ); ?></li>
<li><input type="submit" name="submit" value="Send"></li>
</ul>
</form>
<div id="ajax_success" style="display: none">Email sent.</div>
<div id="ajax_error" style="display: none">There was an error. Sorry your email was not sent.</div>
</div>
Javascript
<script>
jQuery('#ajaxformid').submit(function(e) {
e.preventDefault();
var piclit_email = jQuery( "#piclit_email" ).val();
if (piclit_email == '')
alert("Please fill in all fields to send an email.");
else {
var founder_piclit = jQuery( "#founder_piclit" ).val();
// alert (founder_piclit);
var piclit_bcc = jQuery('.piclit_bcc').val();
var formData = {
piclit_email: piclit_email,
founder_piclit: founder_piclit,
piclit_bcc: piclit_bcc,
action: 'fiveb_ajax_mail',
};
jQuery.ajax({
type : 'POST',
url : '<?php echo admin_url( 'admin-ajax.php' ); ?>',
dataType : 'json',
data : formData,
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
});
}
});
</script>
and php:
function fiveb_function() {
$subject = 'View A Founder PIC-LIT from piclits.com';
$piclit_email = strval($_REQUEST['piclit_email']);
$founder_piclit = strval($_REQUEST['founder_piclit']);
$piclit_bcc = strval($_REQUEST['piclit_bcc']);
if ($piclit_bcc) {
$headers[] = 'Bcc: '.$piclit_email;
}
$message = '<html><head><title>Founder PIC-LIT</title></head><body><table border="0" cellspacing="2" cellpadding="20" bgcolor="#ffffff" width="100%"><tbody><tr><td></td><td width="600"><p style="text-align: center">Hello!<br />View A Founder PIC-LIT from piclits.com.</p></td><td></td></tr><tr><td></td><td><img src="'.$founder_piclit.'" alt="Founder PIC-LIT" width="600" style="display:block;width:100%" /></td><td></td></tr></tbody></table></body></html>';
$headers[] = 'From: PIC-LITS <hello#piclits.com>';
$headers[] = 'Content-Type: text/html; charset=UTF-8';
if ($bcc) $sent_mail = wp_mail( "", "$subject", $message, $headers );
else $sent_mail = wp_mail( "$piclit_email", "$subject", $message, $headers );
if ($sent_mail) {
echo ('email sent');
die();
} else {
echo ('There was an error. Sorry your email was not sent.');
die();
}
}
add_action("wp_ajax_fiveb_function", "fiveb_function");
add_action("wp_ajax_nopriv_fiveb_function", "fiveb_function");
Seems like I am so close but I cannot get the script to stop hanging up on admin-ajax.php. Any help would be so appreciated! Maybe it has something to do with my popup? I am out of ideas
Your code will look like this.
Note - Form action should be blank.
<form action="" method="POST" id="ajaxformid">
</form>
wp_enqueue_script( 'custom-js', get_stylesheet_directory_uri().'/assets/js/custom.js', array(), '1.0.0', 'true' );
wp_localize_script( 'custom-js', 'fiveb_ajax_mail', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
add_action("wp_ajax_fiveb_ajax_mail", "fiveb_ajax_mail");
add_action("wp_ajax_nopriv_fiveb_ajax_mail", "fiveb_ajax_mail");
function fiveb_ajax_mail()
{
$formdata = $_post['formdata'];
wp_mail($to,$subject,$message,$header);
return 'true';
wp_die();
}
//add below js in custom.js file
$('#ajaxformid').submit(function (e) {
e.preventDefault();
jQuery.ajax({
type: "post",
dataType: "json",
url: fiveb_ajax_mail.ajax_url,
data : {action: "fiveb_ajax_mail","formdata":"your form data variable place here"},
success: function(msg){
console.log(msg);
}
});
}
In my local system, it is working fine.

ajax alert is not working using codeigniter

I am newer to ajax. I want to add two fields using ajax and codeigniter.. When i click the submit button the two fields are added but the alert message is not showing also the page is not refreshing. Can any one solve my issue.. Thanks in advance..
This is my Form
<form action="" id="suggestionsform" method="post">
<div class="form-group">
<label for="suggname">Name</label>
<input type="text" class="form-control" name="suggname" id="suggname" placeholder="Enter Your Name" required="required">
</div>
<div class="form-group">
<label for="suggmessage">Suggestion</label>
<textarea class="form-control" rows="4" name="suggmessage" id="suggmessage"
placeholder="Enter Your Suggestions"></textarea>
</div>
<button type="submit" class="btn btn-default" id="suggestions">Submit</button>
</form>
This is my ajax codeing
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(data) {
if (data=='true')
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Controller Coding
public function addSuggestion()
{
$data=array(
'name' => $this->input->post('name'),
'messages' => $this->input->post('suggestion'),
'date' => now()
);
$data=$this->Helen_model->setSuggestion($data);
echo json_encode($data);
}
Model Coding
public function setSuggestion($data){
$this->db->insert('messages', $data);
return $this->db->insert_id();
}
You can achieve like this..
Model
Return true status if insert successful.
public function setSuggestion($data){
$res = $this->db->insert('messages', $data);
if($res){
$result = array('status'=>true,'message'=>'successful');
}
else
{
$result = array('status'=>false,'message'=>'failed');
}
return $result;
}
JS
Check status in success function
<script>
// Ajax post
$(document).ready(function() {
$("#suggestions").click(function(event) {
event.preventDefault();
var name = $("#suggname").val();
var suggestion = $("#suggmessage").val();
$.ajax({
type: "POST",
url: "<?php echo site_url('Helen/addSuggestion')?>",
dataType: 'json',
data: {name: name, suggestion: suggestion},
success: function(response) {
data = eval(response);//or data = JSON.parse(response)
if (data.status ===true)
{
alert("Thank you for your Suggestion");
}
}
});
});
});
</script>
Try to use echo '{"status": "success"}; on your controller response.
That i see on your script you are shown database response.

Ajax form submit for wordpress

So, here is my codes:
form-checkout.php
<form id="rh_checkout_ajax" name="checkout" method="post" class="checkout woocommerce-checkout" enctype="multipart/form-data">
<?php if ( sizeof( $checkout->checkout_fields ) > 0 ) : ?>
<?php do_action( 'woocommerce_checkout_before_customer_details' ); ?>
<div class="col2-set" id="customer_details">
<div class="col-1">
<?php do_action( 'woocommerce_checkout_billing' ); ?>
</div>
<div class="col-2">
<?php do_action( 'woocommerce_checkout_shipping' ); ?>
</div>
</div>
<?php do_action( 'woocommerce_checkout_after_customer_details' ); ?>
<?php endif; ?>
<?php do_action( 'woocommerce_checkout_before_order_review' ); ?>
<div id="order_review" class="woocommerce-checkout-review-order">
<?php do_action( 'woocommerce_checkout_order_review' ); ?>
</div>
<?php do_action( 'woocommerce_checkout_after_order_review' ); ?>
<input value="send" type="submit" name="buy_product" style="display:none;" id="rh_product_add_done_click"></input>
</form>
my_js.js
//Ajax checkout submit
jQuery('#rh_checkout_ajax').submit(function(e){
var name = jQuery(this).attr('name');
jQuery.ajax({
data: {action: 'contact_form', name:name},
type: 'post',
url: ajaxurl,
success: function(data) {
alert(data);
}
});
});
functions.php
//Ajax submit callback
add_action('wp_ajax_contact_form', 'contact_form');
add_action('wp_ajax_nopriv_contact_form', 'contact_form');
function contact_form()
{
echo $_POST['name'];
}
What happens normally
So, when a product is purchased, then the user is redirected to order-detail page which shows what he/she just bought.
What I want it to happen:
I am trying to make it so that the form is submitted via ajax and the user is NOT redirected to the order-detail page, but rather stays in the product page (so, no refresh nor redirect).
I attempted to submit the form via ajax as above but not much of luck.
Could someone help me out with this?
Thanks!
You have to prevent the form from submitting normally. In your js file, add e.preventDefault(). Something like this:
jQuery('#rh_checkout_ajax').submit(function(e){
e.preventDefault();
var name = jQuery(this).attr('name');
jQuery.ajax({
data: {action: 'contact_form', name:name},
type: 'post',
url: ajaxurl,
success: function(data) {
alert(data);
}
});
});

dropdown is not working i ajax form submit in yii 1x

My drop down is not working in ajax form submit but its working on normal form.
When i do ajax submit i get error in firebug
"NetworkError: 404 Not Found - http://example.com/yii/def/state/create"
But when i do the normal submission the form works.
Please help me to solve this issue
My ajax view is _ajax_create_form.php. Code:
<div class="form">
<?php
$form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id'=>'state-create-form',
'enableAjaxValidation'=>true,
'enableClientValidation'=>true,
'method'=>'post',
'action'=>array("state/create"),
'type'=>'horizontal',
'htmlOptions'=>array(
'onsubmit'=>"return false;",/* Disable normal form submit */
),
'clientOptions'=>array(
'validateOnType'=>true,
'validateOnSubmit'=>true,
'afterValidate'=>'js:function(form, data, hasError) {
if (!hasError)
{
create();
}
}'
),
)); ?>
div class="row"> <?php echo $form->labelEx($model,'country_id'); ?> <?php echo $form->dropDownList($model,'country_id',
CHtml::listData(Country::model()->findAll(),'id','name')); ?> <?php echo $form->error($model,'country_id'); ?> </div>
<div class="modal-footer">
<div class="form-actions">
<?php
$this->widget('bootstrap.widgets.TbButton', array(
'buttonType'=>'submit',
'type'=>'primary',
'icon'=>'ok white',
'label'=>$model->isNewRecord ? 'Create' : 'Save',
));
?>
</div>
</div>
<?php
$this->endWidget(); ?>
</div>
Scipt for ajax submit
<script type="text/javascript">
function create()
{
var data=$("#state-create-form").serialize();
jQuery.ajax({
type: 'POST',
url: '<?php
echo Yii::app()->createAbsoluteUrl("state/create"); ?>',
data:data,
success:function(data){
//alert("succes:"+data);
if(data!="false")
{
$('#state-create-modal').modal('hide');
renderView(data);
$.fn.yiiGridView.update('state-grid', {
});
}
},
error: function(data) { // if error occured
alert("Error occured.please try again");
alert(data);
},
dataType:'html'
});
}
function renderCreateForm()
{
$('#state-create-form').each (function(){
this.reset();
});
$('#state-view-modal').modal('hide');
$('#state-create-modal').modal({
show:true,
});
}
</script>
My Controller code is
public function actionCreate()
{
$model=new State;
// Uncomment the following line if AJAX validation is needed
$this->performAjaxValidation($model,"state-create-form");
if(Yii::app()->request->isAjaxRequest)
{
print_r($_POST['State']);
if(isset($_POST['State']))
{
$model->attributes=$_POST['State'];
if($model->save())
{
echo $model->id;
}
else
{
echo "false";
}
return;
}
}
else
{
if(isset($_POST['State']))
{
$model->attributes=$_POST['State'];
if($model->save())
$this->redirect(array('view','id'=>$model->id));
}
$this->render('create',array(
'model'=>$model,
));
}
}
Chnage your AJAX url
try by this
var href = window.localion.href.split('/');
var SITE_URL = href[0] + '//' + href[2] + '/';
$.ajax({
url: SITE_URL + 'controller/action',
........
........
});

Resources