I have a form that submit email and have a condition if the submitted email isn't verified (status = 1) then it fails to insert to the user_driver table. What I want to achieve is how can I show error message like "Please verify your email" when the user click on add button after filling the email field? I am using jquery to send input post to controller and my form is inside modal bootstrap. It hits success function even though the requirement is not met (email_verified = 1) and then reload the page. So, I am a bit confuse how to show the error message.
My view:
function add_driver()
{
user_email = $("#user_email").val();
$.ajax
({
url : site_url+'portal/add_driver',
type: "POST",
//dataType: "json",
data:{user_email: user_email},
success: function(data)
{
$("#add_driver_modal").modal("hide");
location.reload();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Email already registered');
location.reload();
}
});
};
<div class="modal fade" id="add_driver_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">ADD DRIVER</h4>
</div>
<div class="modal-body" id='add'>
<div class="row" id="add_driver_form">
<input type="hidden" name="user_id" id="user_id" />
<div class="col-sm-4">
<input type="text" class="form-control input-lg" autocomplete="off" id="user_email" name="user_email" placeholder="Email" required>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" data-dismiss="modal">Close</button>
<button id="add" type="button" class="btn btn-primary btn-md" onclick=add_driver()>Add</button>
</div>
</div>
<div id="form_submit_result"></div>
</div>
</div>
My controller:
public function add_driver()
{
$user_email = $this->input->post('user_email');
$array = array(
'user_email' => $user_email,
'email_verified' => 1,
'phone_verified' => 1
);
$this->db->select('*');
$this->db->where($array);
$this->db->from('user');
$query = $this->db->get();
$result = $query->row_array();
$match_id = $result['user_id'];
$match_email = $result['user_email'];
if(!is_null($result))
{
$data_user_driver = array(
'user_id' => $match_id,
'user_email' => $match_email
);
$this->db->insert('user_driver',$data_user_driver);
}
}
You may add a p tag in your modal inside modal-body like
....
<div class="modal-body" id='add'>
<p style="display:none;" id="error" class="alert alert-danger"></p>
...
and add a else block and send any message if no result found (in add_driver method) like
...
if(!is_null($result)){
$data_user_driver = array(
'user_id' => $match_id,
'user_email' => $match_email
);
$this->db->insert('user_driver',$data_user_driver);
} else {//if email not verified
echo 'err';
}
....
Now check this result in your ajax success
....
success: function(data){
if(data == 'err'){
$('#error').show().text('Please verify your email');
return false;
}
$('#error').hide();
$("#add_driver_modal").modal("hide");
location.reload();
},
....
Related
I have a modal form (simple) that I want to insert in my BD, but I'm not getting the expected result
modalview
this is the button that calls my modal:
<button type='button' class='btn btn-info' data-toggle="modal" data-target="#modal-default-cliente"><span class='fa fa-plus'></span></button>
this is my modal:
<div class="modal fade" id="modal-default-cliente">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title">Agregar Usuario</h4>
</div>
<div class="modal-body">
<form method="POST" id="clienteform">
<div class="form-group">
<label for="nombrecompleto">Nombre Completo:</label>
<input type="text" class="form-control" name="nombremodal" id="nombremodal" required="required">
</div>
<div class="form-group">
<label for="telefono">Teléfono:</label>
<input type="text" class="form-control" name="telefonomodal" id="telefonomodal">
</div>
<div class="form-group">
<label for="direccion">Dirección:</label>
<input type="text" class="form-control" name="direccionmodal" id="direccionmodal">
</div>
<div class="form-group">
<input type="submit" name="action" class="btn btn-success" value="Guardar">
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary pull-right" data-dismiss="modal">Cerrar</button>
</div>
</div>
</div>
</div>
This is my Javascript code, which by the way the parameters of the form arrive
$(document).on("submit", "#clienteform", function(event){
event.preventDefault();
var nombre = $("#nombremodal").val();
var telefono = $("#telefonomodal").val();
var direccion = $("#direccionmodal").val();
$.ajax({
url: base_url+"mantenimiento/Ventas/agregarClientemodal",
method:'POST',
success: function(data){
alert(data);
$("#modal-default-cliente").modal("hide");
}
});
});
This is my action in the "Ventas" Controller:
public function agregarClientemodal(){
$data = array(
'Nombre' => $this->input->post("nombremodal") ,
'Telefono' => $this->input->post("telefonomodal"),
'Direccion' => $this->input->post("direccionmodal"),
'Estado' => "1"
);
$this->Ventas_model->agregarClientemodal($data);
}
and finally my function in the Sales model:
public function agregarUsuariomodal($data){
return $this->db->insert("Clientes",$data);
}
I'm new to Codeigniter, and when I click on my save button, my modal window does nothing
Expected behavior: save the record and hide the modal
behavior obtained: clicking on the submit does nothing
what am I doing wrong? What do I need to validate? any help for me?
Hope this will help you :
Pass form post values with ajax's data using var formdata = $(this).serialize();, and use site_url() for the URL
Your ajax should be like this :
$(document).ready(function(){
$("#clienteform").on("submit", function(event){
event.preventDefault();
var formdata = $(this).serialize();
$.ajax({
url: '<?=site_url("mantenimiento/Ventas/agregarClientemodal");?>',
method:'POST',
data : formdata,
success: function(data)
{
alert(data);
$("#modal-default-cliente").modal("hide");
}
});
});
});
Your agregarClientemodal method should be like this :
public function agregarClientemodal()
{
$data = array(
'Nombre' => $this->input->post("nombremodal") ,
'Telefono' => $this->input->post("telefonomodal"),
'Direccion' => $this->input->post("direccionmodal"),
'Estado' => "1"
);
$this->Ventas_model->agregarClientemodal($data);
echo "success";
exit;
}
Your base_url variable is not defined in javascript/jquery.
So you need to change that line into:
$.ajax({
url: '<?php echo base_url("mantenimiento/Ventas/agregarClientemodal");?>',
method:'POST',
success: function(data){
alert(data);
$("#modal-default-cliente").modal("hide");
}
});
it will generate correct url.
Further you can check console for error logs.
i'm making a download button on my website that opens a modal with a request for password and then if the password is right should take the user to the real download. This is my javascript:
function submit() {
var postData = $("#passwd").serialize();
//alert(postData);
$.ajax({
type: "POST",
url: "http://www.redcraft.it/submit.php",
data: postData,
success: function(redirect) {
alert('Submitted')
}/*,
error: function() {
alert('Failure');
}*/
});
}
and this is my php:
<?php
function redirect() {
$data = $_POST["postData"];
if($data == is_null()) {
echo "Error";
} else {
echo "<script>window.open('http://www.google.com/" + $data + "', '_self')</script>";
}
}
?>
I'm using echo with a js script in php to try different methods to redirect since header() doesn't work. I'm sure the php is correctly called because i've added a row to create a file when the function is called, and the file is correctly generated.
Please, i need your help and don't kill me if i've made some "noobie" errors.
Edit:
This is the html of the modal:
<div class="modal fade bs-modal-sm" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel" aria-hidden="true">
<div class="modal-dialog modal-mediom">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Download mondo RedCraft</h4>
</div>
<div class="modal-body">
<p>Per scaricare il mondo della redcraft inserisci la password che trovi nel video di presentazione del download!</p>
<div class="control-group">
<label class="control-label" for="userid">Password:</label>
<div class="controls">
<input id="passwd" required="" name="passwordinput" type="input" class="form-control input-medium">
</div>
</div>
<div class="control-group">
<label class="control-label" for="confirmsignup"></label>
<div class="controls">
<button id="confirm" onClick="submit()" name="confirmsignup" class="btn btn-primary" data-dismiss="modal">Conferma</button>
</div>
</div>
</div>
</div>
</div>
</div>
just add one div in your html
<div id="outputredirect"></div>
and add below line in your ajax success or replace with your alert
if(redirect == "Error"){
alert(redirect);
} else {
jQuery('#outputredirect').html(redirect);
}
Your javascript code should redirect to the url returned by the php script :
function submit() {
var postData = $("#passwd").serialize();
//alert(postData);
$.ajax({
type: "POST",
url: "http://www.redcraft.it/submit.php",
data: postData,
success: function(redirect) {
location.href(redirect);
}/*,
error: function() {
alert('Failure');
}*/
});
}
I'm getting the id but not the name, what's wrong i'm doing ?
Please take a look at my CI code and ajax function below:
This is View on which i'm calling ajax:
<div class="modal fade" id="myModal<?php echo $values->season_id; ?>"
tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Update Seasons</h4>
</div>
<div class="modal-body">
<div class="form-group">
<input type="hidden" id="hiddenValue" name="hiddenValue" value="<?php echo $values->season_id; ?>">
<label class="control-label col-md-3 col-sm-3 col-xs-12" for="first-name">Season Name:
</label>
<div class="title_right">
<div class="input-group">
<input type="text" class="form-control" name="update_name" id="update_name" value="<?php echo $values->names; ?>">
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" class="btn btn-primary" id="submit" value="Save changes">
</div>
</div>
</div>
</div>
This is Ajax Function:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
alert("Ajax function started working");
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
dataType: 'json',
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
alert("changes made");
}
}
});
});
});
And here i'm trying to capture the value:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$result = $this->model_season->update_season($update_id,$update_name);
if ($query)
{
$query = $query->row();
$data = array(
'season_id' => $query->season_id,
'names' =>$query->names
);
echo json_encode($data);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
You use
if ($query)
{
$query = $query->row();
$data = array(
'season_id' => $query->season_id,
'names' =>$query->names
);
echo json_encode($data);
}
but where your $query. As your code It should have as following
if ($result)
{
$data = array(
'season_id' => $result->season_id,
'names' =>$result->names
);
echo json_encode($data);
}
Now use $result->season_id instead of $query->season_id and make sure you use row() method in your model update_season() for returning desired values
My code in view script
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('admin_technical/fileUploadblockquotes')?>";
} else {
url = "<?php echo site_url('admin_technical/ajax_updateblockquotes')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{reload_table();
alert(data.status);
$('#modal_formbq').modal('hide');
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data'+errorThrown);
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
view html modal
<div class="modal fade" id="modal_formbq" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title">Objectives</h3>
</div>
<div class="modal-body form">
<form id="form" class="form-horizontal" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div class="form-group">
<label class="control-label col-md-3">Title</label>
<div class="col-md-9">
<input name="title" placeholder="Caption" class="form-control" type="text">
<span class="help-block"></span>
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
controller
public function ajax_updateblockquotes()
{
$data = array(
'text' => $this->input->post('title'),
'id' => $this->input->post('id'),
);
$this->person->updateblockquotes($data);
echo json_encode(array("status" => TRUE));
}
im my model
public function updateblockquotes($data)
{
extract($data);
$this->db->where('id', $id);
return $this->db->update('technical_slide_blockquotes', array('text' => $text));
}
The problem is when I do a debugging using the developer tool from google chrome the result is true, no errors found but when I look the database nothing change on it.
I've following code for file upload :
HTML code :
<a href="#" id="promotion_status_1">
<button type="button" class="btn btn-default brmodalbtn" data-toggle="modal" data-target="#BrandImageModal" id="1">On</button>
</a>
<div class="container">
<div class="modal fade" id="BrandImgeModaal">
<div class="modal-dialog">
<div class="modal-content">
<form id="form" enctype="multipart/form-data" role="form">
<input type="text" class="form-control" name="brand_id" id="brand_id" value="{$data.id}">
<input type="text" name="admin_url" id="admin_url" value="http://localhost/abc.com">
<input type="text" name="op" value="upload_brand_image">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">Brand Image</h4>
</div>
<div class="modal-body">
<div id="messages"></div>
<input type="file" name="file" id="file">
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
</div>
jQuery AJAX Code :
$('#form').submit(function(e) {
var form = $(this);
var formdata = false;
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
type : 'POST',
url : 'manufacturers.php',
cache : false,
data : formdata ? formdata : form.serialize(),
//data : formdata ? formdata : form.serialize() + '&' + $.param({'op':'upload_brand_image'}),
contentType : false,
processData : false,
success: function(response) {
if(response != 'error') {
//$('#messages').addClass('alert alert-success').text(response);
// OP requested to close the modal
$('#BrandImgeModaal').modal('hide');
} else {
$('#messages').addClass('alert alert-danger').text(response);
}
}
});
e.preventDefault();
});
Now the PHP code is as follows :
$request = $_REQUEST ;
switch( $op ) {
case "add":
case "upload_brand_image":
//print_d($request);
//here if error comes in validation I've an array of errors which needs to be printed in AJAX response. Following is the array
$error_messages = array(
"email" => "Email Id can't be blank",
"email_invalid" => "Email Id is not valid"
);
die;
break;
}
My issue is how should I use the array $error_messages in ajax response and if the error doesn't come then the success message should be passed to ajax function instead of this $errror_messages array.
How to achieve this? Can someone please help me in this regard?
Thanks.
why not use json format?
$.ajax({
dataType : 'json',
........
........
success: function(response) {
if(response.email_invalid){
//do something
}else{
//do something
}
}
});
then in your php echo the error
$error_messages = array(
"email" => "Email Id can't be blank",
"email_invalid" => "Email Id is not valid"
);
echo json_encode($error_messages);