How to use error messages from PHP file into AJAX response? - javascript

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);

Related

Codeigniter & AJAX - Reset/clear the modal form when close the edit modal

I have a problem on my modal form when I open the edit modal ,the modal pop up and it fetched my data and that is WORKING WELL but when I close the modal and click the add new user, the data is automatically fetched why is it fetched when I close the modal it should be reset to blank?
how can I reset or clear my form modal after i close the modal and not doing anything?
here is my Edit Javascript/Ajax code
$('#btnClose').click(function(){
$('#myForm')[0].reset();
}); //I Tried this block of code, but it didnt work
//Edit/Show
$('#showdata').on('click','.item-edit', function(){
var id = $(this).attr('data');
$('#myModal').modal('show');
$('#myModal').find('.modal-title').text('Edit Employee');
$('#myForm').attr('action', '<?php echo base_url() ?>employees/updateEmployee');
$.ajax({
type: 'ajax',
method: 'get',
url: '<?php echo base_url() ?>employees/editEmployee',
data: {id:id},
async: false,
dataType:'json',
success: function(data){
$('input[name=txtEmployeeName]').val(data.employee_name);
$('textarea[name=txtAddress]').val(data.address);
$('input[name=txtId]').val(data.id);
},
error: function(){
aler('Could not edit Data');
}
});
});
and here is my modal (I use this modal to create and edit my data so it is just a one modal)
<!--MODAL-->
<div id="myModal" class="modal fade" tabindex="-1" role="dialog">
<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">Modal title</h4>
</div>
<div class="modal-body">
<form id="myForm" action="" method="post" class="form-horizontal">
<input type="hidden" name="txtId" value="0">
<div class="form-group">
<label for="name" class="label-control col-md-4">Employee Name</label>
<div class="col-md-8">
<input type="text" name="txtEmployeeName" class="form-control">
</div>
</div>
<div class="form-group">
<label for="address" class="label-control col-md-4">Address</label>
<div class="col-md-8">
<textarea class="form-control" name="txtAddress"></textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="btnSave" class="btn btn-primary">Save changes</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<!--END MODAL-->
IN CASE you need to see my add/create javascript code here it is
$('#btnSave').click(function(){
var url = $('#myForm').attr('action');
var data = $('#myForm').serialize();
//form validation
var employeeName = $('input[name=txtEmployeeName]');
var address = $('textarea[name=txtAddress]');
var formValid = true;
if (employeeName.val() == '') {
employeeName.parent().parent().addClass('has-error');
}else{
employeeName.parent().parent().removeClass('has-error');
formValid = false;
}
if (address.val()=='') {
address.parent().parent().addClass('has-error');
}else{
address.parent().parent().removeClass('has-error');
formValid = false;
}
if (!formValid) {
$.ajax({
type: 'ajax',
method: 'post',
url: url,
data: data,
async: false,
dataType: 'json',
success: function(response){
if (response.success) {
$('#myModal').modal('hide');
$('#myForm')[0].reset();
if (response.type=='add') {
var type = 'added'
}else if(response.type=='update'){
var type = 'updated'
}
$('.alert-success').html('Employee '+type+' successfully').fadeIn().delay(3000).fadeOut('slow');
showAllEmployees();
}else{
alert('Error');
}
},
error: function(){
alert('Data is not added');
}
});
}
});
Replace
$('#btnClose').click(function(){
$('#myForm')[0].reset();
});
with the following code,
$("#myModal").on("hidden.bs.modal", function () {
$('#myForm')[0].reset();
});

How to insert data from a modal PHP Codeigniter

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.

PHP redirect after form POST

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');
}*/
});
}

sending error message to view with codeigniter

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();
},
....

Undefined Index error (Codeigniter)

My code was working fine before. But Now it is not working. I am working on codeigniter and I am uploading a file using jquery ajax. I donot know why my code stop working. If you can find the issue please let me know.
Here is the controller code
public function updatedp()
{
$var = $_FILES['fileUp'];
$img=$_FILES['fileUp'];
$config['upload_path'] = 'webim/dp_images';
$config['overwrite'] = 'TRUE';
$config["allowed_types"] = 'jpg|jpeg|png|gif';
$config["max_size"] = '1400';
$config["max_width"] = '1400';
$config["max_height"] = '1400';
$this->load->library('upload', $config);
if(!$this->upload->do_upload('fileUp'))
{
$this->data['error'] = $this->upload->display_errors();
echo json_encode(array("result"=>$this->data['error']));
exit;
} else {
$data=array('active'=>0);
$this->db->where('userid','1');
$this->db->update('music_user_dp',$data);
$uname['uname'] =$this->session->all_userdata('uname');
$uname['id'] =$this->session->all_userdata('id');
$post_data = array(
'id' => '',
'userid' => $uname['id']['id'],
'profilepic'=>$var['name'],
'updatedate' => date("Y-m-d H:i:s"),
'active' => '1'
);
$this->Userpage_model->insert_dp_to_db($post_data);
echo json_encode(array("result"=>"Success"));
exit;
}
}
My jquery code which calling above function:
$("#btnupdate").click(function(event){
if($("#fileupload2").val() != ''){
if (typeof FormData !== 'undefined') {
var form = $('#formname').get(0);
var formData = new FormData(form);
$.ajax({
type: "POST",
url: "Userpage/updatedp",
data: formData,
mimeType:"multipart/form-data",
dataType: 'json',
xhr: function() {
return $.ajaxSettings.xhr();
},
cache:false,
contentType: false,
processData: false,
success: function(result){
toastr8.info({
message:'Profile Picture Updated',
title:"New Image Uploaded",
iconClass: "fa fa-info",
});
}
});
event.preventDefault();
}
} else {
toastr8.info({
message:'Error Occured',
title:"Please try again",
iconClass: "fa fa-info",
});
}
});
HTML:
<div class="modal fade" id="myModal" role="dialog">
<form enctype="multipart/form-data" name="formname" id="formname" method="post" action="">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header ">
<script type="text/javascript">
$(document).ready(function(){
$('#mgupload-dp').click(function(e){
$('#fileupload2').click();
e.preventDefault();
});
});
</script>
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Create profile picture</h4>
</div>
<div class="modal-body">
<div class="text-center" style="width:100%"> <img src="<?php echo base_url(); ?>img/profile.png" alt="add dp" id="pop-dp" >
<button type="button" class="btn btn-default text-center" id="mgupload-dp">Choose picture to upload</button>
<input type="file" id="fileupload2" name="fileUp" class="hidden-dp" accept="image/*">
</div>
<div class="clearfix"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" id="btnupdate">Update Picture</button>
</div>
</div>
</div>
</div>
</form>
</div>
Files are not uploading and I am getting this error
A PHP Error was encountered
Severity: Notice
Message: Undefined index: fileUp
Filename: controllers/Userpage.php
Open the Firebug in FF.
Click on the ajax call URL under Console.
See what are passed under "Post" tab.
If fileUp is present there, use $this->input->post('fileUp'); to fetch the contents.

Categories